2

In the following SCJP Mock Exam question, students are asked to find the exact line that String b of the line marked (0) will be a candidate for Garbage Collection.

public class Q76a9 {
    static String f() {
        String a = "hello";
        String b = "bye"; // (0)
        String c = b + "!"; // (1)
        String d = b; // (2)
        b = a; // (3)
        d = a; // (4)
        return c; // (5)
    }

    public static void main(String[] args) {
        String msg = f();
        System.out.println(msg); // (6)
    }
}

After finding out that the correct answer is 6, i came to the conclusion that if the String objects that are being stored in String Literal Pool lose their reference, don't countinue to be preserved in the Pool any more. If they are not referenced, they are eligible for Garbage Collection.

Is that true? If yes, how does the Literal Pool mechanism treats to Strings without any references?

Edit : The question assumes that no compiler optimizations are being done.

Bedir Yilmaz
  • 3,823
  • 5
  • 34
  • 54
  • @Heuster The book doesn't say so, u got any references? – Bedir Yilmaz May 20 '13 at 14:12
  • 2
    @Heuster: That's not true. Strings which are interned on literal pool can be garbage collected during the execution if the pool becomes full or if the GC decides that it is worth doing it. – Jack May 20 '13 at 14:12
  • 1
    OP is right, strings in the constant pool have been garbage-collectible for a long time now (since Java 1.4 or so). There are resources on the Web to prove it. – Marko Topolnik May 20 '13 at 14:13
  • However, the details of that mechanism are not a part of the JLS, which makes this whole question just misleading. – Marko Topolnik May 20 '13 at 14:14
  • @Marko Topolnik That's a SCJP 6 exam by the way, so i think we can assume that we're using a GC which belongs to that era. GC mechanism is a part of the exam, by the way. – Bedir Yilmaz May 20 '13 at 14:17
  • 1
    So does the question, or exam in general, specify precisely which Java version, build number, platform, and GC params are to be assumed? Otherwise the answer is just arbitrary. – Marko Topolnik May 20 '13 at 14:18
  • @Marko Topolnik Hmm, just the JDK version. And no GC params assumed. No platform and no build number specified. You mean the question is misleading under these conditions? – Bedir Yilmaz May 20 '13 at 14:24
  • @parsifal not clarified in the question. – Bedir Yilmaz May 20 '13 at 15:04
  • I want to emphasize that, if it's not about JLS-specified behavior, then it's specific to the very particular JVM, and JVM invocation, that the question author has tested it on. If the question in any manner implies that the behavior is more general than that, then it is indeed misleading. – Marko Topolnik May 20 '13 at 16:49

0 Answers0