Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java static variable and process

Tags:

java

If I declare a variable static and compiled this class into a executable jar. If I start this class using batch file like this:

java MyClass
java MyClass
java MyClass

Would all 3 process share the same variable?

like image 652
ilovetolearn Avatar asked Apr 29 '12 12:04

ilovetolearn


People also ask

Are static variables shared between processes?

No. It is not possible. Each process is in a separate address space. One process cannot see anything in another processes address space.

How do you handle static variables in Java?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

What is static variable and method in Java?

The static variable is a class level variable and it is common to all the class objects i.e. a single copy of the static variable is shared among all the class objects. A static method manipulates the static variables in a class.

How are static variables and methods used?

Static variables should be used to track data that are shared in common by all of the instances of a class. These variables are also called class variables. Class variables are distinguished from instance variables. Instance variables track the data that belong to each individual object of a class.


1 Answers

No. The static variable is specific to the JVM instance. More than that, in fact - it's specific to the class loader which loads the class. So if you created three separate class loaders, each responsible for loading MyClass (not just delegating to some common parent) they'd each have a separate, independent static variable in MyClass.

like image 97
Jon Skeet Avatar answered Nov 10 '22 14:11

Jon Skeet