[BAEL-4213] Why are local variables thread safe

Added two small example for article about thread-safety for local variables.
This commit is contained in:
Martin van Wingerden 2020-07-07 14:57:47 +02:00
parent 5248012a8a
commit da6ee4cc12
2 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package com.baeldung.concurrent.localvariables;
public class LocalAndLambda {
public static void main(String... args) {
String text = "";
// Un-commenting the next line will break compilation, because text is no longer effectively final
// text = "675";
new Thread(() -> System.out.println(text)).start();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.localvariables;
import java.security.SecureRandom;
public class LocalVariables implements Runnable {
private int field;
public static void main(String... args) {
LocalVariables target = new LocalVariables();
new Thread(target).start();
new Thread(target).start();
}
@Override
public void run() {
field = new SecureRandom().nextInt();
int local = new SecureRandom().nextInt();
System.out.println(field + " - " + local);
}
}