Scope of Java static member in web applications

前端 未结 2 1152
故里飘歌
故里飘歌 2021-01-12 10:54

Are Java static variables shared across instances of the same web application?

class MyClass
{
    private static SomeClass myStaticObject = new SomeClass();         


        
相关标签:
2条回答
  • 2021-01-12 11:20

    I don't quite see the point of having a private static variable in MyClass. If it's private you cannot access it as a class variable from outside the class you defined it in. If you just want other classes to access this variable via a getter method you should remove the static keyword.

    0 讨论(0)
  • 2021-01-12 11:23

    Typically, yes. Most containers will provide separate classloaders for each web application. This will result in the class being loaded multiple times when used by several applications, and thus resulting in multiple instances of the static variable.

    Stating the Java Language Specification for reference:

    At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.

    By inference, multiple instances of static variables will exist, unless the classes are loaded only once by a parent class loader, and never loaded elsewhere by any other class loader.

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