Wednesday, January 29, 2014

WeakReference example

WeakReference is a great mechanism.
Usual references are called Strong References.
For example,
string referenceToString = new string("The string!");

Garbage Collector collects and destroys the object if there is no any Strong reference to it.

string referenceToString = null;
If there is no strong reference to "The string!" then it will be collected by garbage collector and destroyed.

WeakReference is a wrapper on top of a Strong reference with one core distinction "WeakReference does not protect from garbage collection".

string referenceToString = new string("The string!");
var wr = new WeakReference(referenceToString);
referenceToString = null;

// some execution time left
// here wr can point to: 
// 1) NULLL if it was garbage collected or
// 2) object "The string!" if it was not garbage collected

var wrTarget = wr.Target as string; // return internal object of weak reference

Usually weak references are used wrong. Take the dialog from my old interview:
Interviewer: What is WeakReference?
Me: I did not know.
Interviewer: (answers the definition)
Me: But where it can be applied?
Interviewer: Mmmm... for example, in a cache. You can have very heavy resources, and resource can be recreated after WeakReference internal object will be garbage collected.


It is very hard to find good example of proper usage for WeakReference. Why on the earth cache mechanism should depend on Garbage Collection time? There are lots of customisable and convenient solutions for caching.

One of the great example was found for Android development (Java).
UI thread can be locked if the image will be loaded not from memory (disk, net). This can be solved by creating asynchronous task that will load the image. The problem arises if user goes out from current page of the application or Android unloads invisible part of the page. Then the image container on the page (ImageView) will not be needed at all when async operation finishes. This can be smartly solved with WeakReference:

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    // Method for getting bitmap is removed for code clearness

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}
Now image container can be garbage collected.

8 comments:

  1. Thanks for this post - it was useful.

    ReplyDelete
  2. Buy Vyvanse and Promethazine–Codeine Cough Syrup by Actavis Online Our Online Pharmacy herbipharm best place to buy online without prescription boasts of one of the largest collection of Prescription pills for sale online. Our website is designed to facilitate the shopping process and is secured, all to ensure you are Safe and Secure when purchasing from us. From our listed inventory, you can buy the following pills and powders online;Vyvanse,Hydrocodone, Oxycontin,Ecstasy (MDMA),buy aderall online. Buying prescription drugs online has never been made easier. What are you waiting for? Do not hesitate to order from us today. Are you concerned about dosage and recommendations? Contact our LiveChat Agent and have your queries solved. buy oxycodone online You can equally contact us HERE. Order Prescription Pain Pills and more online from us and benefit from our amazing pricing!Despite its long history, we didn’t discover how aspirin works until the early 1970s. Unlike narcotics, aspirin drugs are real workhorses that actually go to buy viagra online the source of pain and stop it. When cells are damaged, they produce large quantities of an enzyme called cyclooxygenase-2. This enzyme, buy anxiety pills online in turn, produces chemicals called prostaglandins, buy anxiety pills online which send pain signals to the brain. They also cause the area that has been damaged to release fluid from the blood to create a cushion so the damaged cells don’t take any more of a beating. buy pain killers online An analgesic or painkiller is any member of the group of drugs used to achieve analgesia, relief from pain. Analgesic drugs act in various ways on the peripheral and central nervous systems. They are distinct from anesthetics, which temporarily affect, and in some instances completely eliminate, sensation buy xanax online
    For more information on our products visit our website herbipharm.com
    contact us:
    email: infor@herbipharm.com
    text/whatsapp…+1(304)508-3011

    ReplyDelete
  3. Get Shifting/Relocation Quotation from ###Packers and Movers Delhi. Packers and Movers Delhi 100% Affordable and Reliable ***Household Shifting Services. Compare Transportation Charges and Save Time, Verified and Trusted Packers and Movers in Delhi, Cheap and Safe Local, Domestic House Shifting @
    Packers And Movers Delhi
    Packers And Movers Noida

    ReplyDelete
  4. Packers and Movers Chennai Give Safe and Reliable ***Household Shifting Services in Chennai with Reasonable ###Packers and Movers Price Quotation. We Provide Household Shifting, Office Relocation, ✔✔✔ Local and Domestic Transportation Services, Affordable and Reliable Shifting Service Charges @ Packers And Movers Chennai

    ReplyDelete
  5. Get Packers and Movers Jaipur List of Top Reliable, 100% Affordable, Verified and Secured Service Provider. Get Free ###Packers and Movers Jaipur Price Quotation instantly and Save Cost and Time. Packers and Movers Jaipur ✔✔✔Reviews and Compare Charges for household Shifting, Home/Office Relocation, ***Car Transportation, Pet Relocation, Bike SHifting @ Packers And Movers Jaipur

    ReplyDelete
  6. Packers and Movers Hyderabad Give Certified and Verified Service Providers, Cheap and Best ###Office Relocation Charges, ***Home Shifting, ✔✔✔Goods Insurance worth Rs. 10,000, Assurance for Local and Domestic House Shifting. Safe and Reliable Household Shifting Services in Hyderabad with Reasonable Packers and Movers Price Quotation @ Packers And Movers Hyderabad

    ReplyDelete