Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the scope of a static field?

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

like image 692
Javen Avatar asked Jan 17 '23 14:01

Javen


1 Answers

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)

like image 143
ianpojman Avatar answered Jan 20 '23 15:01

ianpojman