WeakReference to String and String constants

后端 未结 2 1303
闹比i
闹比i 2021-01-12 17:34

I have come across this example from wikipedia regarding weak reference:

import java.lang.ref.WeakReference;

public class ReferenceTest {
        public sta         


        
相关标签:
2条回答
  • 2021-01-12 18:21

    the literal "I'm here" is a compile time constant string and as such gets placed in the constant string pool, which (up until java 7) was never garbage collected. that means sr points to an object that will never be garbage collected. r, on the other hand, points to a copy of that string, which is not in any const pool and so is eligible for collection.

    see the documentation for String.intern() for some more details on this string pool

    0 讨论(0)
  • 2021-01-12 18:29

    If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null.

    very well explained here

    0 讨论(0)
提交回复
热议问题