Merge pull request #9660 from martinvw/feature/BAEL-4213

[BAEL-4213] Why are local variables thread safe
This commit is contained in:
Jonathan Cook 2020-07-12 09:31:37 +02:00 committed by GitHub
commit 44c664a34d
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);
}
}