I am creating a WeakReference
and keeping it somewhere.
WeakReference<MySpecialObject> mWeakReference = new WeakReference<MySpecialObject>(new MySpecialObject("My","Special","Data"));
But some other external library(which I don't what it is doing it) really needs MySpecialObject
instance. When I used something similar below:
ExternalLibraryThingy#useItWisely(mWeakReference.get());
end of part #1
after some time I do call
ExternalLibraryThingy#doSomethingUsefull(); //which I dont know it kept a reference while calling "useItWisely" method.
end of part #2
Until the end of part #1, is my in place created MySpecialObject
object still weakly referenced? I mean if I call mWeakReference.get()
, is there any chance of getting null
? In other words can OS garbage collect it at will?
Until the end of part #2, if the ExternalLibraryThingy
made and assignment while useItWisely
and using that assigned value while doSomethingUsefull
, can it throw a NullPointerException
?
I guess one simple answer can be the answer for both of the question. Thanks in advance.
You passed the dereferenced object to the ExternalLibraryThingy#useItWisely
method. The external library does not care that you retrieved the object from a weak reference.
So whether the object has strong references in the external library depends entirely on the method that you called on it. Without knowing what the method does, it is impossible to know whether the object will still be referenced.
As for your second question, the library had the MySpecialObject
reference directly. From the point of view of the external library, it is not going to be randomly replaced with null
.