• Advertisement
Sign in to follow this  

[java] Question about static class attributes

This topic is 3498 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Thanks, that explains the very weird things I was seeing. Coming from a C++ background, I totally missed this.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement