2

I have the following Java class:

public class Test {

    public static void main(String[] args) {
        if (false) {
            log("String_to_be_never_printed_1");
        }

        if (isPrintable()) {
            log("String_to_be_never_printed_2");
        }

    }

    private static boolean isPrintable() {
        return false;
    }

    private static void log(String s) {
        System.out.println(s);
    }

}

In both if statements, the result will be false. When I output the constant pool table for this class, I get:

Constant pool:
   #1 = Class              #2             // Test
   #2 = Utf8               Test
   ....
  #18 = Utf8               isPrintable
  #19 = Utf8               ()Z
  #20 = String             #21            // String_to_be_never_printed_2
  #21 = Utf8               String_to_be_never_printed_2
  #22 = Methodref          #1.#23         // Test.log:(Ljava/lang/String;)V
  #23 = NameAndType        #24:#25        // log:(Ljava/lang/String;)V
  ...

The String_to_be_never_printed_2 is present (#20), when String_to_be_never_printed_1 is nowhere to be seen. This is expected as the compiler optimized the first if statement.

My question is whether the VM will manage to remove the String_to_be_never_printed_2 from the constant pool (as this will never be used)?

benjamin.d
  • 2,801
  • 3
  • 23
  • 35
  • Answer on this question might help you why it will not be removed http://stackoverflow.com/questions/23121345/jvm-the-constant-pool-the-heap-and-the-addresses – kosa Apr 27 '16 at 16:21

2 Answers2

3

Nothing is ever removed from the constants pool. There would be no purpose in this anyway, as removal would have no effect on actual memory size

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    The `javac` does inline constants known at compile time. If the compile knows the code cannot be run, it can be removed +1 – Peter Lawrey Apr 27 '16 at 16:10
  • You mean there is no purpose because the actual size of the string pool is nothing compared to the heap size ? – benjamin.d Apr 27 '16 at 17:26
  • @benjamin.d No, what I mean is that the constant pool is set up in memory with a fixed size and outside of the heap before execution begins. Garbage Collection only runs on that are in the heap, and it makes no sense for it to run on the constant pool, as nothing else could ever go into this memory – ControlAltDel Apr 27 '16 at 17:52
0

Objects which are present in heap memory are eligible to garbage collections by JVM itself. The Objects in the Constant Pool are not garbage collected all because they don't have much effect on the memory size assigned to the JVM.

KayV
  • 12,987
  • 11
  • 98
  • 148