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++;
    }
}

 

相关文章:

  • 2022-02-01
  • 2021-06-11
  • 2021-10-16
  • 2021-05-16
  • 2021-04-03
  • 2022-01-29
猜你喜欢
  • 2021-05-16
  • 2022-12-23
  • 2022-01-02
  • 2022-01-22
  • 2021-09-06
  • 2021-04-09
相关资源
相似解决方案