|
| 1 | +package com.baeldung.concurrent.busywaiting; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertNotEquals; |
| 5 | +import static org.junit.jupiter.api.Assertions.fail; |
| 6 | + |
| 7 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 8 | + |
| 9 | +import org.junit.jupiter.api.Test; |
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | + |
| 13 | +public class BusyWaitingManualTest { |
| 14 | + |
| 15 | + private static final Logger logger = LoggerFactory.getLogger(BusyWaitingManualTest.class); |
| 16 | + |
| 17 | + @Test |
| 18 | + void givenWorkerThread_whenBusyWaiting_thenAssertExecutedMultipleTimes() { |
| 19 | + AtomicBoolean taskDone = new AtomicBoolean(false); |
| 20 | + long counter = 0; |
| 21 | + |
| 22 | + Thread worker = new Thread(() -> { |
| 23 | + simulateThreadWork(); |
| 24 | + taskDone.set(true); |
| 25 | + }); |
| 26 | + |
| 27 | + worker.start(); |
| 28 | + |
| 29 | + while (!taskDone.get()) { |
| 30 | + counter++; |
| 31 | + } |
| 32 | + |
| 33 | + logger.info("Counter: {}", counter); |
| 34 | + assertNotEquals(1, counter); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + void givenWorkerThread_whenUsingWaitNotify_thenWaitEfficientlyOnce() { |
| 39 | + AtomicBoolean taskDone = new AtomicBoolean(false); |
| 40 | + final Object monitor = new Object(); |
| 41 | + long counter = 0; |
| 42 | + |
| 43 | + Thread worker = new Thread(() -> { |
| 44 | + simulateThreadWork(); |
| 45 | + synchronized (monitor) { |
| 46 | + taskDone.set(true); |
| 47 | + monitor.notify(); |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + worker.start(); |
| 52 | + |
| 53 | + synchronized (monitor) { |
| 54 | + while (!taskDone.get()) { |
| 55 | + counter++; |
| 56 | + try { |
| 57 | + monitor.wait(); |
| 58 | + } catch (InterruptedException e) { |
| 59 | + Thread.currentThread() |
| 60 | + .interrupt(); |
| 61 | + fail("Test case failed due to thread interruption!"); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + assertEquals(1, counter); |
| 67 | + } |
| 68 | + |
| 69 | + private void simulateThreadWork() { |
| 70 | + try { |
| 71 | + Thread.sleep(500); |
| 72 | + } catch (InterruptedException e) { |
| 73 | + Thread.currentThread() |
| 74 | + .interrupt(); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments