Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring@Service中的类字段是线程安全的吗?_Java_Spring_Multithreading - Fatal编程技术网

Java Spring@Service中的类字段是线程安全的吗?

Java Spring@Service中的类字段是线程安全的吗?,java,spring,multithreading,Java,Spring,Multithreading,这个类是线程安全的吗?如果我以这样的方式运行5个线程,会出现什么问题: @Slf4j @Service public class SendServiceImpl implements SendService { private final MessageService messageService; private Message message; public SendServiceImpl (MessageService messageService) {

这个类是线程安全的吗?如果我以这样的方式运行5个线程,会出现什么问题:

@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);
            //...
    }
在实践中,我研究了日志文件,发现同一个实体使用不同的线程。我是否正确理解在这种情况下,如果我声明了类消息字段,线程可以更改实体
message
的值


有人能详细解释一下吗?

没有,默认情况下,@Service的作用域是Singleton。所以它不是线程安全的

如果一个bean是单例的,那么所有应用程序都有一个实例。因此,当5个线程经过那里时,值在每次调用后都会改变


您应该尝试查看中的spring作用域,默认情况下,
@Service
指示单个服务对象将为所有请求提供服务。因此,如果在
@服务的字段中保持可变状态,则必须确保以线程安全的方式访问它

这就是为什么可变状态通常不保存在
@Service
字段中的原因

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