Declaring variable final and static

前端 未结 2 1909
自闭症患者
自闭症患者 2021-02-18 14:31

This comment was made in a code review and the person who made it is no longer on our team.

Any type that must be resolved by the classloader at runtime

相关标签:
2条回答
  • 2021-02-18 14:48

    The comment is most likely related to a problem of Classloader Leaking (here is a good article).

    In a nutshell, this problem happens in environments where classloader needs to be reloaded. If you load a class dynamically through a classloader and then try reloading the classloader, keeping static final fields with objects of classes created through this classloader will prevent unloading the classloader itself. Once this happens, you get an OutOfMemoryError.

    The article linked above lists logging libraries among the top culprits that could produce this behavior, along with measures you can take to work around the leaks (such as releasing classloaders explicitly).

    0 讨论(0)
  • 2021-02-18 14:49

    The line of code is perfectly fine, and there is no real problem because the variable is final and static.

    Maybe the person who made that comment was confused by the following.

    In Java, when you create a public final static variable of type int (for example; it also works with some other types), then the compiler might, in places where you use that variable, substitute the actual constant value instead of a reference to the variable. For example, suppose you have the following:

    class A {
        public final static int VALUE = 3;
    }
    
    public class B {
        public static void main(String[] args) {
            System.out.println(A.VALUE);
        }
    }
    

    When you compile and run this, it will obviously print 3.

    Now suppose that you change class A and set VALUE = 4. You would expect that if you recompile class A and then run class B (without recompiling class B), you would see 4. But what happens is that you will still see 3. That is because the A.VALUE in class B was replaced by the actual constant value 3 when you compiled class B.

    This is an optimization that the Java compiler does for constants.

    As you can see this can cause problems, if you have such constants in the public API of your classes. Users of your code will have to recompile their code if you change the value of such constants.

    But in the code you posted in your question this is not a problem, because the variable is private.

    More details:

    Java Language Specification 13.4.9

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