0

Environment: Spring Container

Say i have the service layer configured as Singleton and that there are no instance variables (state variables) in the service class.

@Singleton
class MyService{
    public List<String> getNames(){
        List<String> list = entityManager.createQuery("");
        list.add("uknown");

        return list;
    }
}

If there are multiple requests (multiple threads) trying to access simultaneously the method getNames(), is it possible to have any synchronization problems?

For example, is it possible for a request to return the "uknown" name twice?

user711189
  • 4,383
  • 4
  • 30
  • 48

2 Answers2

0

Everything in the method

public List<String> getNames(){
    List<String> list = entityManager.createQuery("");
    list.add("uknown");

    return list;
}

is scoped to the request. The entityManager call returns a new List instance to which you add a new String. You then return that list. Only the thread that called the method will have access to that List instance (unless you later share it).

There are no synchronization problems.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

Since service class does not hold any state here (in your example, there are no instance variables in the service class), your service is safe. Local variables and parameters are local to the thread (reside on stack, not on heap).

If you have other objects like say userProfile in your service then since such objects depend on every request, these objects will need to scoped as prototypes. Otherwise, this service is safe.

This is similar to one of my questions. Are Spring MVC Controllers Singletons? Do take a look at the link posted in the answer by Tomasz about thread safety in servlets.

Community
  • 1
  • 1
Atul
  • 2,673
  • 2
  • 28
  • 34