question 7

Posted Thursday, September 03, 2009 by SacrosanctBlood in

How do you guarantee that the garbage collector can reclaim a particular
object when JVM is running very low on memory? Say, for example an image
or a file object is loaded into memory, and is frequently being used.
But, at the time of crunching situation in memory, it can be released to
increase the available memory.



1 comment(s) to... “question 7”

1 comments:

SacrosanctBlood said...

There are 4 types of references in java. Strong, Soft, Phantom and Weak
reference.

The solution to the problem is to use Soft reference.



The references we create normally in java are Strong references. For eg:
String str = “Hi;”; here, str is a strong reference. The GC will not
remove the object till there exist a strong reference for an object.



A Weak reference, simply put, is a reference that isn't strong enough to
force an object to remain in memory. Weak references allow you to
leverage the garbage collector's ability to determine reachability for
you, so you don't have to do it yourself.

WeakReference are created by:



String str = “hi”;

WeakReference sr = new WeakReference (str);

str=null; // This is very very imp, as strong reference has to be
removed…Also, sr.get() returns the object if it has not been garbage
collected. Else, it returns null.





A soft reference is exactly like a weak reference, except that it is
less eager to throw away the object to which it refers. An object which
is only weakly reachable (the strongest references to it are
WeakReferences) will be discarded at the next garbage collection cycle,
but an object which is softly reachable will generally stick around for
a while.

String str = “hi”;

SoftReference sr = new SoftReference (str);

str=null;

In practice softly reachable objects are generally retained as long as
memory is in plentiful supply. This makes them an excellent foundation
for a cache, such as the image cache, since you can let the garbage
collector worry about both how reachable the objects are (a strongly
reachable object will never be removed from the cache) and how badly it
needs the memory they are consuming.

Phantom Reference are little different and would suggest you to read it
more on net, as it needs us to know concept of ReferenceQueue and also,
how exactly the garbage collector works.



So, for the solution of our problemo, SoftReference is the most
preferred choice.



Post a Comment