Java 当以异步方式访问时,单例中的类级变量会导致脏读吗?

Java 当以异步方式访问时,单例中的类级变量会导致脏读吗?,java,spring,multithreading,spring-boot,Java,Spring,Multithreading,Spring Boot,如果通过注释为@RestController的类调用@Service注释类的异步方法,我们的服务类的全局变量会在线程之间共享吗 我这样问是因为我知道每个线程都会获得其执行的类的本地副本,如果单例类中的共享全局变量不是易失的,它还会共享值或导致脏读或写 需要注意的是,这两个变量是原语,因此我假设它们将存储在堆栈上,而不是堆上 由于每个线程都将获得类的一个副本,因为变量是基本变量,那么每个线程是否都会在堆栈而不是堆上进行本地更新 @RestController @RequestMapping(val

如果通过注释为@RestController的类调用@Service注释类的异步方法,我们的服务类的全局变量会在线程之间共享吗

我这样问是因为我知道每个线程都会获得其执行的类的本地副本,如果单例类中的共享全局变量不是易失的,它还会共享值或导致脏读或写

需要注意的是,这两个变量是原语,因此我假设它们将存储在堆栈上,而不是堆上

由于每个线程都将获得类的一个副本,因为变量是基本变量,那么每个线程是否都会在堆栈而不是堆上进行本地更新

@RestController
@RequestMapping(value = "test/v1.0/myputcall")
public class MyController {

    @Autowired
    MyServiceImpl myServiceImpl;

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> activate(@RequestBody UserDTO user) {
        
        //Controller calls the async activate method in singleton service class.
        myServiceImpl.activate(user.userType, user.userID);

    }

}


@Service
public class SwitchServiceImpl{

    private int retryCount = 0;
    private boolean updateRequired = false;

    @Async
    public void activate(String userType, String userId){

        if(userType=="prod"){
            updateRequired=true;
        }

        if(updateRequired){
            tryUpdateWithRetry();
        }

private tryUpdateWithRetry(){
            for(;count<3;retryCount++){
                //call some other app
                int status = UpdateUser.update(userId);
                if(status==0){
                    return;
                }
            }
        log.info("update attempted thrice, non zero return status.");
        }

    }

}    
@RestController
@请求映射(value=“test/v1.0/myputcall”)
公共类MyController{
@自动连线
MyServiceImpl MyServiceImpl;
@PutMapping(consumes=MediaType.APPLICATION\u JSON\u值)
公共响应属性激活(@RequestBody UserDTO user){
//控制器调用singleton服务类中的async activate方法。
myServiceImpl.activate(user.userType,user.userID);
}
}
@服务
公共类SwitchServiceImpl{
private int retryCount=0;
private boolean updateRequired=false;
@异步的
public void activate(字符串userType、字符串userId){
if(userType==“prod”){
updateRequired=true;
}
如果(需要更新){
tryUpdateWithRetry();
}
私有tryUpdateWithRetry(){

对于(;count,服务将在线程之间共享,其成员变量也将共享。如果使用volatile关键字,这将强制线程从主存而不是缓存中读/写值。但是,如果多个线程更新该值,这并不能防止脏读/写

如果线程之间不应该共享该值,则可以使用。每个线程将有一个独立的值副本。如果可能的话,还应该考虑在方法中使用局部变量。


如果需要安全地访问线程之间的值,可以使用或使用synchronized关键字或锁。

如何共享服务,每个线程将获得类的一个副本,因为变量是基本变量,每个线程不会在堆栈上而不是堆上本地更新吗?在Java中,类实例在堆上分配,并且所有这些实例都在堆上s成员,包括原语。