Strong Reference: What Makes Them "Strong"?
Strong Reference: What Makes Them "Strong"?
A strong reference is an every day Java reference.
User user = new User();
What makes them "strong"?
It is the way they interact with the garbage collector.
if an object is reachable via a chain of strong references
(strongly reachable), it is not eligible for garbage collection.
Java References Stronger or Weaker? Luca Sepe 1
Weak reference
It 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 weakUser = new WeakReference(user);
and then elsewhere in the code you can use to
weakUser.get()
get the actual object.
User
The weak reference isn't strong enough to prevent garbage
collection, so you may find (if there are no strong references to the
user) that weakUser.get() return null .
Java References Stronger or Weaker? Luca Sepe 2
Tracking dead references
The class makes it easy to keep track of dead
ReferenceQueue
references.
ReferenceQueue<User> userQ = new ReferenceQueue<User>();
WeakReference<User> userRef =
new WeakReference<User>(user, userQ);
If you pass a
ReferenceQueue into a weak reference's constructor,
the reference object will be automatically inserted into the
reference queue when the object to which it pointed becomes
garbage.
You can then, at some regular interval, process the
ReferenceQueue and perform whatever cleanup is needed for
dead references.
Java References Stronger or Weaker? Luca Sepe 3
Soft references
A soft reference is exactly like a weak reference, except that it is
less eager to throw away the object to which it refers.
SoftReferences aren't required to behave any differently than
WeakReferences, but 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, 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.
Java References Stronger or Weaker? Luca Sepe 4
Java References Stronger or Weaker? Luca Sepe 5