what's the scope of a static field?

穿精又带淫゛_ 提交于 2019-12-07 09:00:44

问题


I meet a problem in static field. I think the root cause must be the scope of the static field.

The project is based on Apache servicemix and consists of many sub-projects.

In sub-project 'A', I defined a static list field 'reg' in class 'Registration' and some static method to operate the field like 'add' and 'getAll'. Once the sub-projectA is deployed, the name of the project 'A' will be added into the static list for registration.

The problem is when it comes to sub-project 'B', when the sub-project 'B' is deployed, I want its name would be added into the exactly same static list for registration. But when I call static method getAll or add on 'Registration', it seems that the 'reg' in sub-projectB is totally different from the one in sub-projectA. So the registration function doesn't work.

So I want to ask one basic question, what's the scope of a static field? Is it valid in a JVM or some other things?

Thanks for your help


回答1:


The scope of a static is global - within its owning classloader. A JVM can create multiple classloaders and load separate instances of your class in each of new classloaders.

Statics are not global per JVM, they are global per classloader. If the class with the static field is loaded in a different classloader, its static members won't be visible within a different classloader.

How are project A and project B deployed? Are they in the same classloader?

I'm not familiar with servicemix, but I imagine it deploys separate apps in separate classloaders, just like a Java EE app will deploy different versions of the same app in different classloaders, so you can run app 1.0 and app 1.1 side-by-side, and they won't affect each other.

This is by design.

If this is the case, you need something independent to maintain shared state. (e.g. a database)



来源:https://stackoverflow.com/questions/10712897/whats-the-scope-of-a-static-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!