• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Accessing Weakly Referenced Objects

 
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()?
 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
The longest recorded flight time of a chicken is 13 seconds. But that was done without this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic