Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Accessing Weakly Referenced Objects  RSS feed

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()?
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!