Web应用程序中Java静态成员的范围 [英] Scope of Java static member in web applications

查看:67
本文介绍了Web应用程序中Java静态成员的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同一Web应用程序实例之间是否共享Java静态变量?

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

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

如果某个Web应用程序使用 MyClass ,并且该应用程序的多个实例在Web服务器上运行,那么 myStaticObject 是否会多次初始化?

If a web application uses MyClass and multiple instances of that application is run on a web server, is myStaticObject initialized multiple times?

推荐答案

通常,是的.大多数容器将为每个Web应用程序提供单独的类加载器.当多个应用程序使用该类时,这将导致该类被多次加载,从而导致该静态变量的多个实例.

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.

Java语言规范供参考:

在运行时,有几种参考类型具有相同的二进制名称可能是由不同的人同时加载类装载机.这些类型可能或可能不代表同一类型宣言.即使有两种这样的类型代表相同的类型声明,它们被认为与众不同.

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.

这篇关于Web应用程序中Java静态成员的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆