You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Java/Multithreading.md
+22Lines changed: 22 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -66,6 +66,28 @@ Achiving concurrency by using synchronized blocks or synchronized keyword can ca
66
66
#### **3. Volatile variables**
67
67
When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared.
68
68
69
+
- In java, the volatile keyword gurantees global ordering on reads and writes to a variable.
70
+
- Volatile keyword establishes a happens-before relationship.
71
+
- also useful for 64-bit types like long and double since they are written in two operations.
72
+
- common example: use for a flag to terminate a thread. ex-
73
+
74
+
```
75
+
class MyVolatile extends Thread {
76
+
private volatile boolean flag = false;
77
+
78
+
public void run() {
79
+
while(!flag) {
80
+
//do something
81
+
}
82
+
}
83
+
84
+
public void end () {
85
+
flag = true;
86
+
//interrupt here
87
+
}
88
+
}
89
+
```
90
+
69
91
use only when you need to simplify synchronization implementation, avoid when verifying correctness would require subtle reasoning. most common use - completion, interruption or status flag.
0 commit comments