Neo
Neo

Reputation: 2226

In Spring MVC, is singleton bean thread-safe?

Assuming we have the following bean:

@Service
public class AccountService {
    private String name;

    public String sayHello(String name) {
        this.name = name;

        return "hello, " + this.name;
    }
}

In Spring MVC, if several users call sayHello() method at the same time but pass different parameters, will they get the correct greeting response?

I just want to know will multiple threads modify the same name variable concurrently? Thanks very much!

Upvotes: 2

Views: 304

Answers (2)

kazbeel
kazbeel

Reputation: 1436

Have a look at this answer.

Summing up... Both concepts are completely different since thread-safe is related to the code of the bean itself and has nothing to do with its instantiation.

I hope it helps.

** UPDATE after comment **

You may try something like this:

Greetings.java

public class Greetings {
    private String name;

    public Greetings (String name) {
        this.name = name;
    }

    public String sayHello () {
        return "Hello, " + this.name;
    }
}

AccountService.class

@Service
public class AccountService {
    public String sayHello (String name) {
        Greetings greetings = new Greetings(name);
        return greetings.sayHello();
    }
}

Upvotes: 1

Neo
Neo

Reputation: 2226

Maybe the best solution is change the scope from singleton to request.

Upvotes: 0

Related Questions