Skip to content

Commit bf7925e

Browse files
committed
[BAEL-4213] Why are local variables thread safe
Added two small example for article about thread-safety for local variables.
1 parent 0f44cc6 commit bf7925e

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.concurrent.localvariables;
2+
3+
public class LocalAndLambda {
4+
public static void main(String... args) {
5+
String text = "";
6+
// Un-commenting the next line will break compilation, because text is no longer effectively final
7+
// text = "675";
8+
new Thread(() -> System.out.println(text)).start();
9+
}
10+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.concurrent.localvariables;
2+
3+
import java.security.SecureRandom;
4+
5+
public class LocalVariables implements Runnable {
6+
private int field;
7+
8+
public static void main(String... args) {
9+
LocalVariables target = new LocalVariables();
10+
new Thread(target).start();
11+
new Thread(target).start();
12+
}
13+
14+
@Override
15+
public void run() {
16+
field = new SecureRandom().nextInt();
17+
int local = new SecureRandom().nextInt();
18+
System.out.println(field + " - " + local);
19+
}
20+
}

0 commit comments

Comments
 (0)