final variables and hotspot optimization

Maybe the question is also “do you always want multiple copies”.
What if my constructor would look like this:

public MyClass(int optimizationLevel) {…}

so an int instead of a boolean. What if there are 50 different values of the int which would cause some code to be omitted or executed differently. I dunno how great it would be to have 50 slightly different copies of the same class in memory… (especially in my particular case where these kind of classes tend to be quite big). I could imagine that with some applications, the JVM’s footprint could go through the roof if the JVM gets too eager to create multiple versions of the same class.

For now i think I’ll look into how I could get multiple copies through a custom ClassLoader

Because the DEBUG variable is static, the code I’ve pasted below will completely strip all of the “// do something” code from the class file at compile time if DEBUG is set to false in the following way:


Class Test
 {
    static final boolean DEBUG = false;

    void test()
    {
        if (DEBUG)
        {
           // do something
        }
   }
}

However, going back to your example, unless isDebug() is a static method in the class GlobalProperties that has the line “return false;” or “return true;” the result of this call cannot be determined, so all of the code below will remain in the class file. (you could be reading the debug value from a properties file for instance)


Class Test
 {
    static final boolean DEBUG = GlobalProperties.isDebug();

    void test()
    {
        if (DEBUG)
        {
           // do something
        }
   }
}