static and volatile
来源:互联网 发布:船舶数据库 编辑:程序博客网 时间:2024/05/22 17:49
http://stackoverflow.com/questions/2423622/volatile-vs-static-in-java
Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However threads may have locally cached values of it.
Declaring a variable as volatile, there will be one variable for each Object. So on the surface it seems there is no difference from a normal variable, and totally different fromstatic. However, even with Object fields, a thread may cache a variable value locally.
This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.
Even if you access a static values through multiple thread each thread can have it's local cached copy! To avoid this you can declare the variable asstatic volatile and this will force the thread to read each time the global value.
However, volatile is not a substitute for proper synchronisation! For instance:
private static volatile int counter = 0; private void concurrentMethodWrong() { counter = counter + 5; //do something counter = counter - 5; }
Executing concurrentMethodWrong concurrently many times may lead to a final value of counter different from zero! To solve the problem, you've to implement a lock:
private static final Object counterLock = new Object(); private static volatile int counter = 0; private void concurrentMethodRight() { synchronized (counterLock) { counter = counter + 5; } //do something synchronized (counterLock) { counter = counter - 5; } }
Or use the AtomicInteger class.
- static and volatile
- static and volatile
- Difference Between Static and Volatile
- Dynamic/Static/Reinterpret/Const and Volatile Cast
- volatile static
- Dynamic/Static/Reinterpret/Const and Volatile Cast (English)
- const,static,extern,volatile
- 关键字static,const,volatile
- restrict volatile static关键字
- const,volatile,enum,static
- auto,register,static,volatile
- const ,static 和 volatile
- static,inline,volatile
- volatile和static
- static,const,volatile
- static volatile的应用
- static extern volatile
- volatile和static
- 将椭圆形图像归一化为圆形图像
- ARM异常向量表中LDR指令、LDR伪指令的来龙去脉
- 2694:逆波兰表达式
- vs项目上传svn保留
- Linux Windows文本文件转换
- static and volatile
- 滑动窗口机制
- 类占用内存情况解析
- HTTP请求方法
- mysql数据库备份及恢复命令mysqldump,source的用法
- codeforces 283A - Cows and Sequence 简单数据结构模拟
- Linux(Android NDK)如何避免僵死进程
- poj2828(线段树应用)
- Android 文件读写操作归纳