Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WeakReference to String and String constants

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

import java.lang.ref.WeakReference;

public class ReferenceTest {
        public static void main(String[] args) throws InterruptedException {

            WeakReference r = new WeakReference(new String("I'm here"));
            WeakReference sr = new WeakReference("I'm here");
            System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
            System.gc();
            Thread.sleep(100);

            // only r.get() becomes null
            System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());

        }
}

I don't understand in this scenario why only r.get() returns null but not the sr.get(). Can someone let me know the reason?

Many thanks.

like image 924
Kevin Avatar asked Nov 21 '13 12:11

Kevin


People also ask

Is string pool garbage collected in Java?

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.

Are string literals garbage collected?

So string literals were never garbage collected (which also led to out of memory issues many a times) After Java 7, string pool is placed in heap space, which is garbage collected by the JVM. It also reduces the chances of getting Out of memory issues in JVM.

What are strong references and weak references in GC?

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object. A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.

What are strong soft weak and phantom references in Java?

An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable. So in brief: Soft references try to keep the reference. Weak references don't try to keep the reference. Phantom references don't free the reference until cleared.


1 Answers

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

like image 179
radai Avatar answered Oct 14 '22 03:10

radai