Are Spring singleton beans thread-safe?
Asked Answered
D

12

47

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.

Dunigan answered 27/6, 2013 at 12:13 Comment(8)
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.Kathrinekathryn
Thread safety has nothing to do with Singletons. Pure singleton or Spring's doesn't matter.Hush
Isn't the guaranteed creation of only 1 instance in a multithreaded environment thread safety ?Whistler
@AndreiPodoprîgora Of course not--it depends what the bean actually does.Dubai
@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.Whistler
@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.Dubai
@DaveNewton, yep, I agree. That's what I was saying - singleton creation process relate to thread safety too.Whistler
@AndreiPodoprîgora Then I think your question is misleading, because "guaranteed creation of only one instance" isn't sufficient for thread safety.Dubai
S
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.

Sibelle answered 27/6, 2013 at 13:6 Comment(4)
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.Oleaginous
@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?Sibelle
Please refer to the Spring documentation on singleton scope: "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."Oleaginous
@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.Cherimoya
V
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.
Vacant answered 12/10, 2017 at 6:22 Comment(0)
K
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

Kovacs answered 27/6, 2013 at 12:17 Comment(2)
or by making your Spring Bean stateless, which is, I think, the better approach.Thessalonians
or make all shared instance variables to method local variables (move variables from heap to stack).Lundin
V
4

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

Vinous answered 27/6, 2013 at 12:15 Comment(0)
S
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.

Secede answered 3/12, 2018 at 17:48 Comment(0)
D
3

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 value** is of age 26

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

Dangle answered 16/10, 2019 at 10:36 Comment(0)
J
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.

Jimerson answered 18/7, 2022 at 18:29 Comment(0)
A
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.

Addia answered 18/10, 2019 at 15:50 Comment(0)
M
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.

Milkman answered 19/3, 2014 at 16:56 Comment(0)
B
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.

Burgonet answered 14/3, 2017 at 5:24 Comment(3)
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.Train
@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 itTymes
@Tymes ~ 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.Train
M
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.

Mcgaha answered 2/3, 2021 at 19:31 Comment(0)
Y
-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.

Yashmak answered 27/6, 2013 at 12:19 Comment(1)
You don't understand what thread safe is. I voted your answer down.Alfie

© 2022 - 2024 — McMap. All rights reserved.