-2

This question : java static variable and process

Is there a way I can achieve sharing static variables between multiple processes ? For instance by writing a custom class loader that loads the same class from the disk.

2
  • The answer is still "No". Don't depend on Singeleton's for your application, load config/data from disk Commented Feb 9, 2016 at 12:38
  • 4
    Possible duplicate of java static variable and process Commented Feb 9, 2016 at 12:46

2 Answers 2

4

No. It is not possible.

Each process is in a separate address space. One process cannot see anything in another processes address space. This applies to all processes, not just Java processes.

The only way for one process to see something in another processes address space is if the 2 processes have a common shared memory segment. In C / C++ it is possible to do that ... if you are careful with the inter-process synchronization.

In Java, the shared memory approach is not practical:

  • You would would need to share not only the variable, but also the closure of the objects that the variable refers to.
  • That means sharing part of the heap. It wouldn't work. The Java heap is not designed for that.
  • Then there is the problem of synchronization and the Java memory model.
  • The only glimmer of a possibility would be if you did this entirely using off-heap storage. But then these are no longer static variables that you can use from Java code.

Classloaders don't help. A classloader in one java process / address space loads classes into that address space. Other processes can't see them, and they can't see the corresponding static variables.

Sign up to request clarification or add additional context in comments.

Comments

0

You could do it by using a database in which you store your variables, and all VM instances should read and write to this base for those variables.

1 Comment

But then you just have separate versions of the static variable in the different VMs ... and no way to keep them in sync. The OP is asking for something that behaves as a single variable. It isn't possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.