3
@Slf4j
@Service
public class SendServiceImpl implements SendService {

    private final MessageService messageService;

    private Message message;

    public SendServiceImpl (MessageService messageService) {
        this.messageService = messageService;
    }

    @Transactional
    @Override
    public void send(String messageGuid) {
            message = messageService.getOne(messageGuid);
            //...
    }

Is this class thread safe? what problems can there be if I run in 5 threads like this:

taskExecutor.execute(() -> sendService .send(someGuid);//5 different guids

in practice, I studied the logs file and saw that with the same entity work different threads. Do I understand correctly that in this case, threads can change the value of entity message if I declared message like class field?

Can anyone explain this in detail?

ip696
  • 6,574
  • 12
  • 65
  • 128

2 Answers2

5

By default, @Service indicates that a single service object will serve all requests. As a consequence, if you keep mutable state in fields of a @Service, you must make sure that it gets accessed in a thread-safe way.

That's why mutable state is not usually kept in @Service fields.

meriton
  • 68,356
  • 14
  • 108
  • 175
4

No, for the default the scope of the @Service is Singleton. So it`s not thread-safe.

If a bean is Singleton, there is one instance for all the application. So when 5 thread pass there, the value will change after each call.

You shoud try to look at spring scopes in https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Raphael Alves
  • 169
  • 1
  • 3