[java] Question about static class attributes

Started by
2 comments, last by mouserSVK 15 years, 8 months ago
In java, are static class attributes shared by all objects in an application, or by all objects in the JVM? In other words if I have
class MyClass{
static public int var;
}
And I run two instances of the same app, will changing MyClass.var in one instance cause it to update in the other too?
Advertisement
There is no "application". You have run-time environment (JVM process) within which some code runs.

Unless you launch each JVM in its own JVM process, they'll share the static members.
Thanks, that explains the very weird things I was seeing. Coming from a C++ background, I totally missed this.
Well, to be more precise, I must say that Antheus' explanation is not absolutely correct, although many people think it is.

The right saying could be that unless you access the classes (and their static fields) in different ClassLoaders, their static members will be shared.

This might seem like not important and it is true that for many people it is not important. The problems usually occur when people start to implement some 'enterprise' / web applications. It is common that application servers (e.g. Tomcat) load applications in their own ClassLoaders because of safety - all of them, however, run under the same JVM.

More on this is available here.

This topic is closed to new replies.

Advertisement