---
title: "Java并发编程: Volatile不能保证数据同步"
author: "iaspecwang"
date: "2013-08-24T08:17:28Z"
tags: []
categories: ["企业架构"]
slug: "java-volatile"
draft: false
lastmod: "2013-08-24T08:17:28Z"
id: 1929701
url: "https://iaspecwang.iteye.com/blog/1929701"
---

在本篇博文中,将给出一个实例去验证volatile修饰的变量并不能保证其数据同步. 

Java内存模型规定了所有变量都存储在主内存中，每条线程都有自己的工作内存，线程的工作内存保存了被该线程使用到变量的主内存副本拷贝，线程对变量的所有操作(读取,赋值等)都必须在工作内存中进行，而不能直接读写主内存中的变量。不同线程也不能直接访问对方工作内存中的变量，线程间变量值的传递均需要通过主内存来完成，线程，主内存，工作内存三者的交互关系如图所示。 

![](http://dl2.iteye.com/upload/attachment/0087/8530/c2a30d16-0eaa-30bf-9105-e19a8db4bc37.gif) 

当一个变量定义成volatile之后, 保证了此变量对所有线程的**可见性**,也就是说当一条线程修改了这个变量的值,新的值对于其它线程来说是可以立即得知的.此时,该变量的读写操作直接在主内存中完成. 

Volatile 变量具有 synchronized 的**可见性特性**，**但是不具备原子特性**。   
Volatile variables share the visibility features of synchronized, but none of the atomicity features. 

**虽然增量操作（x++）看上去类似一个单独操作，实际上它是一个由读取－修改－写入操作序列组成的组合操作，必须以原子方式执行，而 volatile 不能提供必须的原子特性。**   
While the increment operation (x++) may look like a single operation, it is really a compound read-modify-write sequence of operations that must execute atomically -- and volatile does not provide the necessary atomicity. 

在多线程并发的环境下, 各个线程的读/写操作可能有重叠现象, 在这个时候, volatile并不能保证数据同步. 

下面将给出一个实例: 

**实例** ==&gt; 500个线程一起运行,每个线程对1到100求和1000次操作,然后将一个volatile共享变量值加1. 当500个线程都完成操作之后, 期望的值是500,因为每个线程执行完毕之后都会对这个volatile变量加1. 

一直循环执行这个程序,直到出现volatile变量的值小于500为止,也就是出现数据不同步. 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. public class NonSafeThread implements Runnable {
02. /\** 共享资源, 每个线程执行完之后加 1 \*/
03. private volatile int volatileCount = 0;
04. public void run() {
05. /*
06. * 每个线程调用sum100()方法，1000次
07. \*/
08. for (int i = 1; i &lt;= 1000; i++) {
09. sum100();
10. }
11. /*
12. * 计算完毕之后， volatileCount 加 1
13. \*/
14. increase();
15. }
16. private void increase()
17. {
18. volatileCount++;
19. }
20. /\**
21. * 对 1 到 100 求和
22. \*/
23. private int sum100() {
24. int result = 0;
25. for (int i = 1; i &lt;= 100; i++) {
26. result += i;
27. }
28. return result;
29. }
30. /\**
31. * @return the volatileCount
32. \*/
33. public int getVolatileCount() {
34. return volatileCount;
35. }
36. }

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. /\**
02. * @author Eric
03. \*
04. * @version 1.0
05. \*/
06. public class NonSafeThreadTest {
07. public static void main(String\[] args) {
08. /\** 记录循环次数 \*/
09. int loopCount = 0;
10. /\** 以main函数主线程创建一个是线程组 \*/
11. ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
12. for (;;) {
13. loopCount++;
14. /*
15. * 启动500个线程，初始化的线程会添加到当前线程组中
16. \*/
17. NonSafeThread nonSafeThread = new NonSafeThread();
18. startThreads(nonSafeThread);
19. /*
20. * 如果线程组中除了主线程之外，还有其它线程，则休眠5毫秒，然后再判断线程组中 剩余的线程数，直到只剩下主线程一个为止。
21. \*/
22. while (!isOnlyMainThreadLeft(threadGroup)) {
23. sleep(5);
24. }
25. /*
26. * 500个线程运行完毕，那么此时的volatile变量volatileCount的值应该500， 因为每个线程将其值加1。
27. \*
28. * 验证是否出现线程不安全的情况。
29. \*/
30. validate(loopCount, nonSafeThread.getVolatileCount(), 500);
31. }
32. }
33. /\**
34. * 启动500个线程
35. \*/
36. private static void startThreads(NonSafeThread nonSafeThread) {
37. for (int i = 0; i &lt; 500; i++) {
38. new Thread(nonSafeThread).start();
39. }
40. }
41. /\**
42. * 验证是否出现线程不安全的情况。 如果是，则打印出线程不安全的信息。
43. \*/
44. private static void validate(int loopCount, int actualValue,
45. int expectedValue) {
46. if (!isVolatileCountExpected(actualValue, expectedValue)) {
47. printNonSafeMessage(loopCount, actualValue, expectedValue);
48. /*
49. * 正常退出程序。
50. \*/
51. System.exit(0);
52. }
53. }
54. /\**
55. * 在控制台打印出现线程不安全时的信息。
56. \*/
57. private static void printNonSafeMessage(int loopCount, int actualValue,
58. int expectedValue) {
59. System.out.println(String.format(
60. "第%d次循环，出现线程不安全的情况，volatile的值不正确,期望值是%d, 但是500个线程运行的情况下是%d",
61. loopCount, expectedValue, actualValue));
62. }
63. /\**
64. * 判断实际中的volatile值与期望值是否一致。
65. \*/
66. private static boolean isVolatileCountExpected(int actualValue,
67. int expectedValue) {
68. return actualValue == expectedValue;
69. }
70. /\**
71. * 让线程休眠millis毫秒
72. \*/
73. private static void sleep(long millis) {
74. try {
75. Thread.sleep(millis);
76. } catch (InterruptedException e) {
77. // TODO Auto-generated catch block
78. e.printStackTrace();
79. }
80. }
81. /\**
82. * 判断一个线程组是否只剩下主线程了。
83. \*
84. * 如果是则返回true，如果不是则放回false.
85. \*/
86. private static boolean isOnlyMainThreadLeft(ThreadGroup tg) {
87. return tg.activeCount() == 1;
88. }
89. }

**某次运行,输出的结果如下:**   
第83次循环，出现线程不安全的情况，volatile的值不正确,期望值是500, 但是500个线程运行的情况下是499 

在这种情况下,可以通过 Lcak和synchronized来保证数据的同步. 

如:   
1\. 使用Lock,修改NonSafeThread类的run方法的内容: 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. public void run() {
02. lock.lock();
03. try {
04. /*
05. * 每个线程调用sum100()方法，1000次
06. \*/
07. for (int i = 1; i &lt;= 1000; i++) {
08. sum100();
09. }
10. /*
11. * 计算完毕之后， volatileCount 加 1
12. \*/
13. increase();
14. } finally {
15. lock.unlock();
16. }
17. }

2\. 使用synchronized 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. public void run() {
02. synchronized ("") {
03. /*
04. * 每个线程调用sum100()方法，1000次
05. \*/
06. for (int i = 1; i &lt;= 1000; i++) {
07. sum100();
08. }
09. /*
10. * 计算完毕之后， volatileCount 加 1
11. \*/
12. increase();
13. }
14. }

如果用Lock或者synchronized修改了NonSafeThread类, 如果再想跑这个程序的话,需要控制一下NonSafeThreadTest中for循环中执行的次数,比如1000次 (我运行程序的时候,一般都在100次以内打印出数据不安全的结果),以免导致程序在Lock或者synchronized修改后一直执行下去.