Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how multiple threads invoke singleton object's method and work on them?

I have multiple threads running which access singleton object and call its method and pass objects in it. In the method I do some calculations only on recieved object. I have heard that there would not be any problem in this case cause it is stateless and it is free for all.

My question is how it is free for all? I want to know how multiple threads can call the shared method in their own thread without overwriting the passed objects of other threads? Please explain in terms of memory allocation wise and at stack level.

class Singleton class{      //no shared class or object variables and only one copy of this Singleton object exists.      Object someMethod(Object o){         //do some calculation or logic on the object o and return some string result     }  } 
like image 367
beinghuman Avatar asked Aug 31 '13 11:08

beinghuman


People also ask

How singleton works in multi threading applications?

Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can't access it simultaneously.

How do you handle singleton in multithreading?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.

Are singleton objects shared across threads?

Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.

Can multiple threads use the same object?

No. They all use the same object. However, the memory system design of a typical modern computer means that some of the state of an object may be held in machine registers and memory caches associated with more than one processor in a multi-processor system.


2 Answers

I think you have to distinguish between what you've already stored in memory and code execution.

In a Singleton Object you have:

  • Fields: They are stored in memory. They can be shared amongst multiple threads and you have no guarantee they will keep consistent (unless you make them synchronized).
  • Methods to be called: They can be called from more than one thread. Each execution is independent and thread safe, unless they access some shared field improperly.

Now coming to your question: if you share your singleton object among multiple threads and access it concurrently, every single thread will execute Singleton object's portion of code, wrapped in its own execution.

Also if you write a Thread.currentThread().getId(); which basically returns the thread ID you're executing into singleton's methods, you will obtain different ids, because different threads are executing their own method stack. Being stateless means you've no fields into the singleton to be shared amongst them!

A word on Stateless and Stateful

Stateless means that the bean hasn't got any modifiable field to share. That means you have only methods or/and static stuff in your object, so you can use them anywhere and will always return you same result. You don't have to worry about synchronizing the access to the field.

That's a basic example about stateless, let's suppose you have a class that only performs the sum operation:

public class StatelessClass{      public int sum(int a, int b){         return a+b;     }  } 

In the same way, you can declare it as a abstract class (no instantiable itself) and make its methods static, which means you don't need any instance of it to call its methods:

public abstract class StatelessClass{      /**     *   I only sum objects     */     public static int sum(int a, int b){         return a+b;     }  } 

Then you can use it as StatelessClass.sum(1,1);, this actually would be very similar to have a Singleton object itself, with the difference that in the Singleton you have a unique instance shared in the application.

In the same way, having a field which is injected and provides access to a service neither is considered to alter the state of the object:

public class StatelessServiceClass{      private Service service;      public int sum(int a, int b){         return service.sum(a,b);     }      public void setService(Service serv){         this.service=serv;     }  } 

However, having a field which is modifiable makes the Object stateful:

public class StatefulClass{      //This fields make the object STATEFUL     private int totalSum = 0;      public int sum(int a, int b){         int sum = a + b;         totalSum = totalSum + sum;         if (totalSum > 100)             System.out.println("This thread "+Thread.currentThread().getId()+                 +" got it!");         return sum;     }  } 

As sum can be accessed by multiple threads at the same time, you should guarantee that totalSum is accessed in a synchronized way. The printed sentence is not guaranteed to be true unless you do it.

All of this is also properly explained in this answer's Threadsafety piece by @BalusC.

like image 52
Xtreme Biker Avatar answered Sep 17 '22 19:09

Xtreme Biker


Every thread has its own copy of the Object o and so even if multiple threads call the method at the same time, each method call of Thread will have its own stack allocated and the logic will apply there.

Why is it Thread Safe?

Thread Stacks are private to them and are by default thread safe as no other thread can enter in others stack.

NOTE: You can say that this Singleton of yours is Thread safe but not that the application is Thread safe as it also depends on whether the Object o being passed is itself thread safe or not. But as far as safety of Singleton is concerned it is thread safe.

like image 22
Narendra Pathai Avatar answered Sep 19 '22 19:09

Narendra Pathai