aspose file tools
The moose likes Java in General and the fly likes Strong and weak reference. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Strong and weak reference." Watch "Strong and weak reference." New topic
Author

Strong and weak reference.

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
What are strong reference and weak reference ?

Can someone please point me to any good links for the same ?
Scott J Johnson
Greenhorn

Joined: Mar 09, 2010
Posts: 2
A strong reference is what you would normally consider a reference in java. For example, if I have the following code:



Then x is a strong reference. What this means is that the garbage collector will treat the object (an Integer object) as not able to be collected because it is referred to by a reference (namely, the variable x).

A weak reference, on the other hand, is a reference that allows us to access an object, but it doesn't force the garbage collector not to collect that object. We create a weak reference with the following:

Now, if we do the following:

The garbage collector will now treat the object behind the reference y as collectable.

So, the question is, "why would we want this?" And the answer is that sometimes, we don't want objects to stick around. This creates the Java equivalent of memory leaks. If we had a HashMap with keys that are objects, there isn't a great way to determine if the key is needed any longer. So, we can use the WeakHashMap, which uses WeakReferences as its keys. Thus, if there isn't another variable that is a (strong) reference to the key, it's removed from memory. Thus, we don't have object sticking around long after we need them.

There is a good explanation of this at:
http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

Hope this helps -

~Scott
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strong and weak reference.
 
Similar Threads
WeakReference, SoftReference, caches & canonical tables
Survival of Strongest
soft and hard references in java
Strong,weak & phantom variables
What is Weak Object Reference?