I konw the GC in jvm will collect the object once it found the object is weak referenced, but some people say that it maybe tooks several times of gc for the jvm to find the weak referenced objects, I don't really understand it, is anyone can explain it, or tell me is it true? thanks!
2 Answers
Yes, it takes a while before object will be destroyed. I do not know of anything wrong with Java WeakReference or its impact on performance.
- May result in additional Garbage Collection
- You cannot know when the cycle is performed. Garbage Collector working in cycles in own background thread.
- WeakReferences managing depends on implementation of JRE (like everything), see also Cost of using weak references in Java
There are no way to destroy object manually in Java and other advanced languages like C# for example. Garbage collector do that work. In cycles finalize and destroy objects without reference (i.e. strong reference). Weak references does not prevent the object to be collected by Garbage Collector. Difference between reference type are explained here on StackOverflow.
There is no way to trigger collection cycle. You can poke Garbage Collector by System.gc()
but it does not cause immediate execution and "take several times".
Garbage collection for all practical purposes is indeterministic. You simply can't predict when it'll clean something, if it'll cause your app to briefly pause etc. Most of the time it behaves well. You should never rely on underlying gc actions or finalizers.

- 5,168
- 1
- 24
- 37