Java语言中的volatile变量

Java中的两种内置同步机制: synchronized 和 volatile 变量, volatile修饰的变量, 在使用时会强制检查最新值. 有synchronized的值可见性, 但是没有其操作原子性. 因为其轻量的原因, 在一些考虑性能的地方, 可以使用volatile, 但是使用时要非常小心.

常用的场景是: 少写多读, 并且写入口唯一的情况.

http://www.ibm.com/developerworks/java/library/j-jtp06197/index.html

Using a volatile variable for multiple publications of independent observations

public class UserManager {
    public volatile String lastUser;

    public boolean authenticate(String user, String password) {
        boolean valid = passwordIsValid(user, password);
        if (valid) {
            User u = new User();
            activeUsers.add(u);
            lastUser = user;
        }
        return valid;
    }
}
@ThreadSafe
public class CheesyCounter {
    // Employs the cheap read-write lock trick
    // All mutative operations MUST be done with the 'this' lock held
    @GuardedBy("this") private volatile int value;

    public int getValue() { return value; }

    public synchronized int increment() {
        return value++;
    }
}
原文地址:https://www.cnblogs.com/milton/p/4225346.html