java - 如果在单个方法中递增,static int 线程安全吗?

标签 java multithreading thread-safety

我想使用下面的代码跟踪 getVariableAndLogAccess(RequestInfo requestInfo)。如果只有这两种方法访问变量,是否线程安全? 使其线程安全的标准方法是什么?

public class MyAccessLog(){

    private int recordIndex = 0;
    private int variableWithAccessTracking = 42; 
    private final Map<Integer, RequestInfo> requestsLog = new HashMap<>();
    public int getVariableAndLogAccess(RequestInfo requestInfo){
        Integer myID = recordIndex++;
        int variableValue = variableWithAccessTracking;
        requestInfo.saveValue(variableValue);
        requestLog.put(myID, requestInfo);
        return variableValue;
     }
     public void setValueAndLog(RequestInfo requestInfo, int newValue){
        Integer myID = recordIndex++;
        variableWithAccessTracking = variableValue;
        requestInfo.saveValue(variableValue);
        requestLog.put(myID, requestInfo);
     }

/*other methods*/
}

最佳答案

Will it be thread safe if only these two methods access variable?

没有。

例如,如果两个线程调用 setValueAndLog,它们可能会以相同的 myID 值结束。

What is the standard way to make it thread safe?

你应该用 AtomicInteger 替换你的 int , 使用 lock , 或 syncrhonized block 以防止并发修改。

根据经验,使用原子变量(例如前面提到的 AtomicInteger)比使用锁要好,因为锁涉及操作系统。调用操作系统就像请律师 - 对于您可以自己解决的事情,最好避免两者。

注意如果使用锁或者同步块(synchronized block),setter和getter都需要使用同一个锁。否则,当 setter 仍在更新变量时,getter 可能会被访问​​,从而导致并发错误。

关于java - 如果在单个方法中递增,static int 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116566/

相关文章:

c# - 跨线程操作无效(How to access WinForm elements from another module events?)

c# - 系统.InvalidOperationException : Collection was modified

php - PHP-FPM线程安全吗

java - Eclipse Juno Android 错误,styles.xml 错误

java - SAR(系统 Activity 报告器)报告的字节数超出预期

java - 当用户点击红叉时如何显示确认消息? Java图形用户界面

python - 如何使用 OpenCV 捕获多个摄像头流?

java - android中的main或UI线程在哪里准备弯针?

java - 执行 UTF-8 Base64 编码/解码 Java 后出现奇怪的字符

objective-c - block 在异步线程上执行两次