java - Can object be garbage collected between two subsequent calls to WeakReference.get()? -


i see code of kind in library apis , in someone's code:

class someclass {      private weakreference<someobject> objectweakreference; // initialized elsewhere      public boolean isobjectattached() {         return objectweakreference.get() != null;     }      public someobject getobject() {         return objectweakreference.get();     }  } 

and

public void checkandgetweakreference() {     someclass someclass = new someclass();     if (someclass.isobjectattached()) {         someclass.getobject().dosomethingdirectlyonreturnedobject(); // can returned reference null here ?     } } 

and i'm worried if there nullpointerexception once in blue moon, assuming there no strong reference underlying object @ point.

i don't know when garbage collector can start deleting objects memory , how correlate basic thread flow.

it nice if can shed light on particular subject and/or provide information topic.

p.s. reference once , assign strong reference. point of question proof code above wrong.

the whole point of weakreference (and softreference well) referred object may gc'd @ any time no strong reference object exists.

since there exists no strong reference when isobjectattached() returns, yes can garbage collected before gets execute getobject(). whole idom faulty use case.

the safe way first reference (e.g. local variable) , then check against null. object can not garbage collected in case, because local variable is strong reference.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -