zoukankan      html  css  js  c++  java
  • 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++;
        }
    }
  • 相关阅读:
    图片 音频 视频上传
    asp.net导出execl和图片
    asp.net网页播放MP4 出错
    js 定时器
    js的Math和正则
    js字符串,Arry数组,join连接,push,shift,sort
    js的argument参数
    js函数对象
    js简单语法,循环
    position的relative
  • 原文地址:https://www.cnblogs.com/milton/p/4225346.html
Copyright © 2011-2022 走看看