Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9f26a34

Browse files
Update Multithreading.md
1 parent b564371 commit 9f26a34

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

‎Java/Multithreading.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,28 @@ Achiving concurrency by using synchronized blocks or synchronized keyword can ca
6666
#### **3. Volatile variables**
6767
When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared.
6868

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+
6991
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.
7092

7193
#### **4. Sharing Objects**

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /