• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing Weakly Referenced Objects  RSS feed

 
Alec Lee
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not quite familiar with the proper way to use WeakReference. I got some objects referenced by java.lang.ref.WeakReference. Occasionally, I want to inspect those objects. But since weakly referenced objects would be gc'ed at any time, how can I make sure they are still there by the time I inspect them?

Say, I first check that the WeakReference still contains a non-null value returned by get(). Does that mean this value will still be non-null when I use it some time later? By calling get() would I now create another strong reference to the object? And, if yes, does it mean I must set null to any variable I used to store the reference obtained from the get()?
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your program holds strong reference to the 'weak' object - this object wont be 'nulled' by GC.

Make a simple test:


result is:
i1 = null
i2 = 2
i2 = null

If you get it at one time and it is not null - if you do not hold strong reference to the object, this object can be nulled even 5 ms later.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!