2

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!

Neo
  • 2,196
  • 5
  • 32
  • 58
  • This component is not thread-safe by virtue of being stateful. A good rule of thumb is to avoid storing state in Spring beans - makes life *much* easier. – kryger Nov 11 '14 at 09:53

2 Answers2

1

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();
    }
}
Community
  • 1
  • 1
kazbeel
  • 1,378
  • 19
  • 40
  • Thanks for your answer, I've read this post already. I just want to know will multiple threads modify the same `name` variable concurrently? – Neo Nov 11 '14 at 07:44
  • Yep! I believe you're mixing concepts. Perhaps you could instance a new object (the one that contains the string name) every time an `SayHello` method is called. That way you are sure that it's thread-safe. – kazbeel Nov 11 '14 at 10:38
0

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

Neo
  • 2,196
  • 5
  • 32
  • 58
  • This would be suboptimal if `AccountService` was costly to create, and service components usually are. Consider reorganizing your code to move state into a different layer. – kryger Nov 11 '14 at 09:55