| 27 | } |
| 28 | |
| 29 | private static void runAtomicIntegerTest(final boolean increment) { |
| 30 | final AtomicInteger result = new AtomicInteger(); |
| 31 | final AtomicInteger threadDoneCount = new AtomicInteger(); |
| 32 | // only using an AtomicBoolean here so I don't need two variables to do the synchronize/wait/notify |
| 33 | final AtomicBoolean threadsStart = new AtomicBoolean(false); |
| 34 | |
| 35 | Runnable operationRunnable = new Runnable() { |
| 36 | @Override |
| 37 | public void run() { |
| 38 | boolean flip = true; |
| 39 | for (int i = 0; i < iterationsPerThread; i++) { |
| 40 | if (flip) { |
| 41 | if (increment) { |
| 42 | result.incrementAndGet(); |
| 43 | } else { |
| 44 | result.decrementAndGet(); |
| 45 | } |
| 46 | flip = false; |
| 47 | } else { |
| 48 | if (increment) { |
| 49 | result.getAndIncrement(); |
| 50 | } else { |
| 51 | result.getAndDecrement(); |
| 52 | } |
| 53 | flip = true; |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | for (int i = 0; i < threadCount; i++) { |
| 60 | new Thread(new DelayedRunnable(threadsStart, |
| 61 | operationRunnable, |
| 62 | threadDoneCount)).start(); |
| 63 | } |
| 64 | |
| 65 | synchronized (threadsStart) { |
| 66 | threadsStart.set(true); |
| 67 | |
| 68 | threadsStart.notifyAll(); |
| 69 | } |
| 70 | |
| 71 | try { |
| 72 | blockTillThreadsDone(threadDoneCount); |
| 73 | } catch (InterruptedException e) { |
| 74 | // let thread exit |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | int expectedResult = threadCount * iterationsPerThread; |
| 79 | if (! increment) { |
| 80 | expectedResult *= -1; |
| 81 | } |
| 82 | int resultValue = result.get(); |
| 83 | if (resultValue != expectedResult) { |
| 84 | throw new IllegalStateException(resultValue + " != " + expectedResult); |
| 85 | } |
| 86 | } |