Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. class Scratch1 {
  2. int counter = 0;
  3. Scratch1() throws ExecutionException, InterruptedException {
  4. counter += 5;
  5. counter += 5;
  6. // Does this cause to flush possibly cached value written by main thread even if it locks
  7. // on totally unrelated object and the write doesnt happen inside the sync block?
  8. synchronized (String.class) {}
  9. Executors.newCachedThreadPool().submit(() -> {
  10. for (int i = 0; i < 1000; i++) {
  11. counter += 5;
  12. }
  13. synchronized (Integer.class) {}
  14. }).get();
  15. System.out.println(counter);
  16. }
  17. }
  18.  
  19. class Scratch2 {
  20. int counter = 0;
  21. Scratch2() throws ExecutionException, InterruptedException {
  22. // Or is this only possible working way how flush written data.
  23. synchronized (String.class) {
  24. counter += 5;
  25. counter += 5;
  26. }
  27. Executors.newCachedThreadPool().submit(() -> {
  28. synchronized (Integer.class) {
  29. for (int i = 0; i < 1000; i++) {
  30. counter += 5;
  31. }
  32. }
  33. }).get();
  34. System.out.println(counter);
  35. }
  36. }
  37.  
  38. class Scratch3 {
  39. volatile int counter = 0;
  40. Scratch3() throws ExecutionException, InterruptedException {
  41. counter += 5;
  42. counter += 5;
  43. Executors.newCachedThreadPool().submit(() -> {
  44. for (int i = 0; i < 1000; i++) {
  45. counter += 5;
  46. }
  47. }).get();
  48. System.out.println(counter);
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement