45

I want to know whether the Spring singleton beans are thread-safe, if yes then why, if not then why?

As I am beginner with spring so help would be appreciated.

kolossus
  • 20,559
  • 3
  • 52
  • 104
Mounica Reddy
  • 533
  • 2
  • 5
  • 8
  • 1
    Spring doesn't guarantee thread-safety. It will be your responsibility . Spring will create a Singleton , but if its mutable then it might not be thread safe. – AllTooSir Jun 27 '13 at 12:15
  • Thread safety has nothing to do with Singletons. Pure singleton or Spring's doesn't matter. – Ravi K Thapliyal Jun 27 '13 at 12:15
  • Isn't the guaranteed creation of only 1 instance in a multithreaded environment thread safety ? – StKiller Jun 27 '13 at 12:22
  • 1
    @AndreiPodoprîgora Of course not--it depends what the bean actually *does*. – Dave Newton Jun 27 '13 at 12:30
  • @DaveNewton - if the developer don't care about thread safety and doesn't write the singleton in a right way - many instances are created - so the singleton isn't thread safe. – StKiller Jun 27 '13 at 12:35
  • @AndreiPodoprîgora That's the "singleton" part. Whether or not the singleton's *code* is thread-safe is a completely separate issue. There's singleton *creation*, and there's singleton *execution*: two different things. – Dave Newton Jun 27 '13 at 12:38
  • @DaveNewton, yep, I agree. That's what I was saying - singleton creation process relate to thread safety too. – StKiller Jun 27 '13 at 13:03
  • @AndreiPodoprîgora Then I think your question is misleading, because "guaranteed creation of only one instance" isn't sufficient for thread safety. – Dave Newton Jun 27 '13 at 13:04

12 Answers12

41

No. The two concepts are not even related.

Singletons are about creation. This design pattern ensures that only one instance of a class is created.

Thread safety is about execution. To quote Wikipedia:

A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

So eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe per se.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • 5
    I realize this is old but since this was one of the first Google results I came to for a search on spring thread safety I wanted to point out that Spring "singleton beans" are different than the "singleton" design pattern that this answer refers to . . . "Spring singleton bean" really means a Spring bean with singleton scope. – Scott Shipp Dec 15 '16 at 00:12
  • 2
    @ScottShipp And do you think it's a coincidence that it's named singleton scope? Spring creates a bean if it doesn't exist and provides the existing instance otherwise. Does that sound familiar? – a better oliver Dec 15 '16 at 10:28
  • 2
    Please refer to the [Spring documentation on singleton scope](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-singleton): "Spring’s concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four (GoF) patterns book. The GoF Singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean." – Scott Shipp Dec 19 '16 at 19:29
  • @Faraz and the answer is no. Eventhough the scope differs (per classloader vs. per container), the initial statement from OP holds. It depends on how the code is implemented that uses the shard memory. In other words, they're not related. – Younes El Ouarti Nov 28 '19 at 07:54
11

I have different perception: Spring singleton beans are created once and there can be only one instance available at any point of time.

Lets say your have an instance variable which is modified in an non-synchronized method. In multi-threaded environment,same class instance will be assigned to all the threads and 2 concurrent threads can update/change the instance variables which may lead unexpected situation. Singleton beans does not provide thread safety and now you know that instance variables usage may lead to unexpected result, you have 2 options to solve the same :

  1. Don't use instance variables in multithreaded environment. OR
  2. Use synchronized block/keyword on methods wherever the instance variables are modified to avoid unexpected results.
sunil bhardwaj
  • 259
  • 3
  • 6
5

Spring just manage the life cycle of singleton bean and maintains single instance of object. Thread safety has nothing to do with it.

if not then why?

Because singleton and thread safety are two different concepts. You can go for thread safety with synchronized keyword

M Sach
  • 33,416
  • 76
  • 221
  • 314
4

Spring singleton beans are NOT thread-safe just because Spring instantiates them. Sorry.

Arthur Dent
  • 785
  • 3
  • 7
4

Singleton Beans is thread safe or not depends on how the class whose scope is singleton is written. Each calling thread will have its own execution and does not interfere with another thread's execution unless there is some code in the singleton scoped class which is shared by all calling threads.e.g if a class has globally declared variables that is being accessed by its method and the values are modified then this may cause concurrency issue so it is better to have those variables at the method level and not at the class level.

Ripudaman Singh
  • 363
  • 3
  • 10
2

Spring singleton bean define the single instance is created by BeanAwareFactory in spring IOC container. But when we try to use the same bean in multiple threads then the simultaneous access can cause unexpected behaviour as it not thread safe.

Singleton is about creating object instance in IOC container. So when running multiple thread then it’s about runtime behaviour.

And the value of same object can be performed by both threads as there’s no restriction on it for multiple thread accesst.

1

No , Spring singelton bean is not thread safe , Here is example

public class Emmloyee {

private int id;

private String name;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


}

And here is applicationContext.xml

  <bean id="emp" class="com.manikant.Emmloyee" p:id="26"  p:name="Manikant Gautam">

And here is test class

   public class Test {

public static void main(String[] args) {

    ApplicationContext ctx=new ClassPathXmlApplicationContext("com/manikant/config.xml");
    Emmloyee emp=(Emmloyee)ctx.getBean("emp");
    System.out.println("User "+emp.getName() + " is of age "+emp.getId());
    emp.setName("Changed value");

    Emmloyee emp1=(Emmloyee)ctx.getBean("emp");
    System.out.println("User "+emp1.getName() + " is of age "+emp1.getId());


}

}

Here is output

      User Manikant Gautam is of age 26

      User Changed name is of age 26

change in value by emp.setName("Changed value"); reflects on different bean emp1 also .

manikant gautam
  • 3,521
  • 1
  • 17
  • 27
1

According to my view, it totally thread safety of your singleton class totally depends on you have design/written your singleton class.

If there is any global variable defined the singleton class then it will not be thread safe because if multiple thread share the singleton object and execute the method which can updates the global variable it will not be thread safe.

To make any singleton class thread safe it is advised that make that class stateless means you should avoid defining the global variable in the singleton class.

0

Spring doesn't guarantee thread-safety. It will be your responsibility . Spring will create a Singleton , but if its mutable then it might not be thread safe. IT'S programmer responsibility to take care the spring bean class such way it should be thread safe.

0

In Spring, singleton beans will not have any state (stateless). Singleton bean scope ensures that single instance per BeanFactory. So in multi threading environment it will not assure the single instance even with singleton bean scope.

So to fix this, we need to change the bean scope from singleton scope to prototype scope as it is the developers responsibility to ensure the thread safety.

Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39
  • 1
    Based on your assertion, how exactly is it thread-safe simply by changing the scope to `prototype`? Bean scope has nothing to do with thread safety. – Edward J Beckett Aug 10 '18 at 17:43
  • @EddieB why not changing the scope from Singleton to Prototype/request supports thread safety as each thread then have single instance of those beans? Sorry, i am new to spring and trying to understand it – tiktok Oct 02 '20 at 20:15
  • @tiktok ~ Making the bean a `Prototype` doesn't mean that it supports thread-safety --- as a matter of fact... a `Prototype` by definition cannot be thread-safe because there are (1-*) instances whereas a `Singleton` bean applies instantiation logic to enforce only one instance exists. However, there are use cases where that can be circumvented as well. – Edward J Beckett Oct 03 '20 at 01:13
0

My service was called by upstream using parallel processing and it crashed my application. While thread 1 was working on beanA, another request arrived and it set some parameters of beanA. When my beanA was stored in database, I verified that it was a complete mess. I fixed it by using prototype.

Mowgli
  • 73
  • 2
  • 10
-1

if not then why?

becuase you could have a reference to non-threadsafe objects in your singleton.

But if you don't, and you use spring to inject any instance variables then yes they are thread safe.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311