|
| 1 | +// lowlevel/SynchronizedComparison.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 blocks instead of entire methods |
| 6 | +// speeds up access. |
| 7 | +import java.util.*; |
| 8 | +import java.util.stream.*; |
| 9 | +import java.util.concurrent.*; |
| 10 | +import java.util.concurrent.atomic.*; |
| 11 | +import onjava.Nap; |
| 12 | + |
| 13 | +abstract class Guarded { |
| 14 | + AtomicLong callCount = new AtomicLong(); |
| 15 | + public abstract void method(); |
| 16 | + @Override |
| 17 | + public String toString() { |
| 18 | + return getClass().getSimpleName() + |
| 19 | + ": " + callCount.get(); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +class SynchronizedMethod extends Guarded { |
| 24 | + public synchronized void method() { |
| 25 | + new Nap(10); |
| 26 | + callCount.incrementAndGet(); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +class CriticalSection extends Guarded { |
| 31 | + public void method() { |
| 32 | + new Nap(10); |
| 33 | + synchronized(this) { |
| 34 | + callCount.incrementAndGet(); |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +class Caller implements Runnable { |
| 40 | + private Guarded g; |
| 41 | + public Caller(Guarded g) { this.g = g; } |
| 42 | + private AtomicBoolean stop = |
| 43 | + new AtomicBoolean(false); |
| 44 | + class Stop extends TimerTask { |
| 45 | + @Override |
| 46 | + public void run() { stop.set(true); } |
| 47 | + } |
| 48 | + @Override |
| 49 | + public void run() { |
| 50 | + new Timer().schedule(new Stop(), 2500); |
| 51 | + while(!stop.get()) |
| 52 | + g.method(); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +public class SynchronizedComparison { |
| 57 | + static void test(Guarded g) { |
| 58 | + List<CompletableFuture<Void>> callers = |
| 59 | + Stream.of( |
| 60 | + new Caller(g), |
| 61 | + new Caller(g), |
| 62 | + new Caller(g), |
| 63 | + new Caller(g)) |
| 64 | + .map(CompletableFuture::runAsync) |
| 65 | + .collect(Collectors.toList()); |
| 66 | + callers.forEach(CompletableFuture::join); |
| 67 | + System.out.println(g); |
| 68 | + } |
| 69 | + public static void main(String[] args) { |
| 70 | + test(new CriticalSection()); |
| 71 | + test(new SynchronizedMethod()); |
| 72 | + } |
| 73 | +} |
| 74 | +/* Output: |
| 75 | +CriticalSection: 972 |
| 76 | +SynchronizedMethod: 247 |
| 77 | +*/ |
0 commit comments