Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are method-local variables stored?

I am having some questions related a very specific situation we can encounter when dealing with Singleton objects and concurrent call events.

I know there are other questions somehow related to mine, but they are not quite what I wanted to know. (example: Concurrently invoking Java method of singleton object)

Say for example I have the following code:

public class MyClass{
   private static MyClass myInstance = new MyClass();

   private new MyClass() {}

   public MyClass getInstance(){
      return myInstance;
   }

   public String doSomething(String message){
      java.util.Date d = new java.util.Date();
      System.out.println(message);
      System.out.println("Today is: " + d);
   }
}

In a concurrent scenario in which I am calling this same class instance many times I want to know what happens to the Date d variable, memory wise, will it be stored in a different memory stack for everyone that calls getInstance().doSomething()?

In my understanding since the class instance is static but it has no mutable global variables declared it should be creating separate d objects for different processes with no concurrency problems at all.

Could someone please clarify this part?

like image 585
Carlos Roberto Claramount Ruiz Avatar asked Dec 07 '25 03:12

Carlos Roberto Claramount Ruiz


1 Answers

You are right. Each thread has it's own call stack and d reference placed on it. Object itself allocated in heap but JIT compiler may even place it on stack if during escape analysis variable will be considered local. In your example there is no contention on d so doSomething may be considered thread-safe.

However you need to keep in mind that threads may interference with each other in case if "local" objects produce read/write operations to mutable shared state (for example writable static field).

like image 100
vsminkov Avatar answered Dec 08 '25 16:12

vsminkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!