Last active
June 5, 2024 22:09
-
-
Save LeoAndo/60aefc39403472c2f9658cf15dbe4b73 to your computer and use it in GitHub Desktop.
フィールドの修飾子volatileのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VolatileSample { | |
private static volatile int count = 0; // メインメモリの変数に対して読み書きする | |
// private static int count = 0; // 各スレッドの対応するキャッシュした変数に対して読み書きする | |
public static void main(String[] args) { | |
new MultiThread1().start(); | |
new MultiThread2().start(); | |
} | |
// Thread-0 | |
private static class MultiThread1 extends Thread { | |
public void run() { | |
while (count < 3) { | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.printf("%s: before count = %d\n", getName(), count); | |
count++; // カウントアップする. | |
System.out.printf("%s: after count = %d\n", getName(), count); | |
} | |
System.out.println("MultiThread1(Thread-0) finish"); | |
} | |
} | |
// Thread-1 | |
private static class MultiThread2 extends Thread { | |
public void run() { | |
int beforeCount = count; // 元の値を退避する. | |
while (count < 3) { | |
if (beforeCount != count) { // カウンター変数に更新があったら、標準出力する. | |
System.out.printf("%s: before count = %d, after count = %d\n", getName(), beforeCount, count); | |
beforeCount = count; | |
} | |
} | |
System.out.println("MultiThread2(Thread-1) finish"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果
volatileあり
volatileなし
フィールドの修飾子: volatile
volatileはフィールド変数用の修飾子の一つで、複数スレッドで共有する変数をスレッドごとに変数のキャッシュコピーをせず、メインメモリの変数に対して読み書きするために必要な修飾子。volatile修飾子は、変数の可視性は保証されますが、スレッド・セーフは保証されない。
デフォルトでは、スレッドは値へのアクセスを高速化する為に、各スレッドは対応するキャッシュに独自の変数コピーを持つ。マルチスレッド処理では同じフィールドの値を別の領域へキャッシュすることになるので、JVMによるキャッシュのタイミングによってはそれぞれの領域の値が違ってしまう可能性がある。