Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Scratch1 {
- int counter = 0;
- Scratch1() throws ExecutionException, InterruptedException {
- counter += 5;
- counter += 5;
- // Does this cause to flush possibly cached value written by main thread even if it locks
- // on totally unrelated object and the write doesnt happen inside the sync block?
- synchronized (String.class) {}
- Executors.newCachedThreadPool().submit(() -> {
- for (int i = 0; i < 1000; i++) {
- counter += 5;
- }
- synchronized (Integer.class) {}
- }).get();
- System.out.println(counter);
- }
- }
- class Scratch2 {
- int counter = 0;
- Scratch2() throws ExecutionException, InterruptedException {
- // Or is this only possible working way how flush written data.
- synchronized (String.class) {
- counter += 5;
- counter += 5;
- }
- Executors.newCachedThreadPool().submit(() -> {
- synchronized (Integer.class) {
- for (int i = 0; i < 1000; i++) {
- counter += 5;
- }
- }
- }).get();
- System.out.println(counter);
- }
- }
- class Scratch3 {
- volatile int counter = 0;
- Scratch3() throws ExecutionException, InterruptedException {
- counter += 5;
- counter += 5;
- Executors.newCachedThreadPool().submit(() -> {
- for (int i = 0; i < 1000; i++) {
- counter += 5;
- }
- }).get();
- System.out.println(counter);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement