查看文章 |
作者:hexiong 版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明。 http://hi.baidu.com/hexiong/blog/item/ef575aaf2a074bfafbed503a.html 一、关于volatile标识符在同步中的应用 最近看到有人在Java中大量使用volatile变量类型修改饰符,即在简单类型(boolean, int, byte, char等)之前添加这个标识符,从而简化同步代码。比如: private boolean stopRequest = false; 可替代形式为: private volatile boolean stopRequest = false; 不过,我查了一下volatile的原始用法: A use operation by T on V is permitted only if the previous operation by T on V was load, and a load operation by T on V is permitted only if the next operation by T on V is use. The use operation is said to be "associated" with the read operation that corresponds to the load. A store operation by T on V is permitted only if the previous operation by T on V was assign, and an assign operation by T on V is permitted only if the next operation by T on V is store. The assign operation is said to be "associated" with the write operation that corresponds to the store. Let action A be a use or assign by thread T on variable V, let action F be the load or store associated with A, and let action P be the read or write of V that corresponds to F. Similarly, let action B be a use or assign by thread T on variable W, let action G be the load or store associated with B, and let action Q be the read or write of W that corresponds to G. If A precedes B, then P must precede Q. (Less formally: operations on the master copies of volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.) 大意是每次进入volatile变量相关的操作代码块时,都会load一遍它最新的改变(无论它的值有没有改变),这种特性特别适合于多线程的情形。
private static SingletonClass _instance = null; 直接替换为: private static SingletonClass _instance = null; 这样同步的效率是非常低的。须知每次调用getInsance都会要进行同步,对这个类进行加锁。须知: private static SingletonClass _instance = new SingletonClass(); 它的缺点是只要加载了SingletonClass,则一定会执行new操作,但是如果用户想调用该类的一些其它static方法,不需要这个类的唯一对象,则new操作显得多余。其实这个方法与Scott Merys在effective c++里提出的在函数体里声明static A a; return &a是很类似的效果。 class SingletonDelegate 再细查一下,有几篇文章倒是挺好的,一并列在这里: |

