|
| 1 | +// lowlevel/SyncOnObject.java |
| 2 | +// (c)2017 MindView LLC: see Copyright.txt |
| 3 | +// We make no guarantees that this code is fit for any purpose. |
| 4 | +// Visit http://OnJava8.com for more book information. |
| 5 | +// Synchronizing on another object |
| 6 | +import java.util.*; |
| 7 | +import java.util.stream.*; |
| 8 | +import java.util.concurrent.*; |
| 9 | +import onjava.Nap; |
| 10 | + |
| 11 | +class DualSynch { |
| 12 | + ConcurrentLinkedQueue<String> trace = |
| 13 | + new ConcurrentLinkedQueue<>(); |
| 14 | + public synchronized void f(boolean nap) { |
| 15 | + for(int i = 0; i < 5; i++) { |
| 16 | + trace.add(String.format("f() " + i)); |
| 17 | + if(nap) new Nap(10); |
| 18 | + } |
| 19 | + } |
| 20 | + private Object syncObject = new Object(); |
| 21 | + public void g(boolean nap) { |
| 22 | + synchronized(syncObject) { |
| 23 | + for(int i = 0; i < 5; i++) { |
| 24 | + trace.add(String.format("g() " + i)); |
| 25 | + if(nap) new Nap(10); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +public class SyncOnObject { |
| 32 | + static void test(boolean fNap, boolean gNap) { |
| 33 | + DualSynch ds = new DualSynch(); |
| 34 | + List<CompletableFuture<Void>> cfs = |
| 35 | + Arrays.stream(new Runnable[] { |
| 36 | + () -> ds.f(fNap), () -> ds.g(gNap) }) |
| 37 | + .map(CompletableFuture::runAsync) |
| 38 | + .collect(Collectors.toList()); |
| 39 | + cfs.forEach(CompletableFuture::join); |
| 40 | + ds.trace.forEach(System.out::println); |
| 41 | + } |
| 42 | + public static void main(String[] args) { |
| 43 | + test(true, false); |
| 44 | + System.out.println("****"); |
| 45 | + test(false, true); |
| 46 | + } |
| 47 | +} |
| 48 | +/* Output: |
| 49 | +f() 0 |
| 50 | +g() 0 |
| 51 | +g() 1 |
| 52 | +g() 2 |
| 53 | +g() 3 |
| 54 | +g() 4 |
| 55 | +f() 1 |
| 56 | +f() 2 |
| 57 | +f() 3 |
| 58 | +f() 4 |
| 59 | +**** |
| 60 | +f() 0 |
| 61 | +g() 0 |
| 62 | +f() 1 |
| 63 | +f() 2 |
| 64 | +f() 3 |
| 65 | +f() 4 |
| 66 | +g() 1 |
| 67 | +g() 2 |
| 68 | +g() 3 |
| 69 | +g() 4 |
| 70 | +*/ |
0 commit comments