简体   繁体   English

在非同步静态方法中修改静态变量,是否存在线程安全的危险?

[英]Modifying a static variable in non-synchronized static method, is there a danger to thread safety?

I have a class with a static method modifying a static variable as follows, does this method needs to be synchonized for thread safe operations ? 我有一个类使用静态方法修改静态变量,如下所示,此方法是否需要同步以进行线程安全操作?

public final class IdManager {

    private static int noOfIdsInReserveCurrently = 100;   
    private static final AtomicInteger allotedUserIdsCount; 

    public static int getNewId(){
         noOfIdsInReserveCurrently--;
         ....
         return allotedUserIdsCount.incrementAndGet();
    }
}

Should this method have been synchronized? 该方法是否已同步?

Well it's certainly not safe as it is. 嗯,它肯定不安全。 Two threads could both read the value, but decrement their local copy, then both write. 两个线程都可以读取值,但是减少它们的本地副本,然后写入。 Badness. 不良。

You could synchronize it (and all other aspects to the variable) - but it would be better to use AtomicInteger which is designed for exactly this sort of thing. 可以将它(以及所有其他方面与变量同步) - 但最好使用专为此类设计而设计的AtomicInteger That's fine if the only shared state you're modifying is that one value; 如果您正在修改的唯一共享状态是一个值,那就没关系; if you're trying to modify more shared state atomically (eg some "next ID" counter as well as the number of outstanding IDs) then you would need to either thing really, really carefully about the various interleavings, or use a synchronized block instead. 如果你想修改原子多个共享状态(例如,一些“下一个ID”计数器以及优秀的ID数),那么你就需要要么东西真的,真的仔细了解各种的交错, 使用synchronized块,而不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM