What is the scope of a static field?

I encounter a problem in a static field. I believe that the main reason is the scope of the static field.

The project is based on Apache servicemix and consists of many subprojects.

In subproject "A" I defined a static list field "reg" in the "Registration" class and some static method for controlling the "add" and "getAll" type fields. After subproject A is deployed, the project name "A" will be added to the static list for registration.

The problem is when it comes to subproject “B”, when subproject “B” is deployed, I want its name to be added to the exact same static list for registration. But when I call the static getAll method or add it to "Registration", it seems that "reg" in sub-project B is completely different from what is in sub-projectA. Therefore, the registration function does not work.

So, I want to ask one basic question: what is the scope of a static field? Is this really in the JVM or some other things?

thanks for the help

+4
source share
1 answer

The scope of static - global - is within its class loader class. The JVM can create multiple class loaders and load individual instances of your class in each of the new class loaders.

Statics are not global to the JVM, they are global to every classloader. If a class with a static field is loaded into another classloader, its static members will not be visible in another classloader.

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

I am not familiar with servicemix, but I believe that it deploys separate applications in separate classloaders, just as a Java EE application will deploy different versions of the same application in different classloaders, so you can run application 1.0 and application 1.1 side -by-side, and they will not influence each other.

This is by design.

If so, you need something independent to maintain overall health. (e.g. databases)

+8
source

Source: https://habr.com/ru/post/1413875/


All Articles