|
| 1 | +package com.lmax.disruptor; |
| 2 | + |
| 3 | +import static org.hamcrest.CoreMatchers.is; |
| 4 | +import static org.junit.Assert.assertThat; |
| 5 | + |
| 6 | +import java.util.concurrent.Executor; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.atomic.AtomicLong; |
| 9 | + |
| 10 | +import org.junit.Test; |
| 11 | + |
| 12 | +import com.lmax.disruptor.util.DaemonThreadFactory; |
| 13 | + |
| 14 | + |
| 15 | +public class WorkerPoolTest |
| 16 | +{ |
| 17 | + @SuppressWarnings("unchecked") |
| 18 | + @Test |
| 19 | + public void shouldProcessEachMessageByOnlyOneWorker() throws Exception |
| 20 | + { |
| 21 | + Executor executor = Executors.newCachedThreadPool(DaemonThreadFactory.INSTANCE); |
| 22 | + WorkerPool<AtomicLong> pool = new WorkerPool<AtomicLong>(new AtomicLongEventFactory(), new FatalExceptionHandler(), |
| 23 | + new AtomicLongWorkHandler(), new AtomicLongWorkHandler()); |
| 24 | + |
| 25 | + RingBuffer<AtomicLong> ringBuffer = pool.start(executor); |
| 26 | + |
| 27 | + ringBuffer.next(); |
| 28 | + ringBuffer.next(); |
| 29 | + ringBuffer.publish(0); |
| 30 | + ringBuffer.publish(1); |
| 31 | + |
| 32 | + Thread.sleep(500); |
| 33 | + |
| 34 | + assertThat(ringBuffer.get(0).get(), is(1L)); |
| 35 | + assertThat(ringBuffer.get(1).get(), is(1L)); |
| 36 | + } |
| 37 | + |
| 38 | + @SuppressWarnings("unchecked") |
| 39 | + @Test |
| 40 | + public void shouldProcessOnlyOnceItHasBeenPublished() throws Exception |
| 41 | + { |
| 42 | + Executor executor = Executors.newCachedThreadPool(DaemonThreadFactory.INSTANCE); |
| 43 | + WorkerPool<AtomicLong> pool = new WorkerPool<AtomicLong>(new AtomicLongEventFactory(), new FatalExceptionHandler(), |
| 44 | + new AtomicLongWorkHandler(), new AtomicLongWorkHandler()); |
| 45 | + |
| 46 | + RingBuffer<AtomicLong> ringBuffer = pool.start(executor); |
| 47 | + |
| 48 | + ringBuffer.next(); |
| 49 | + ringBuffer.next(); |
| 50 | + |
| 51 | + Thread.sleep(1000); |
| 52 | + |
| 53 | + assertThat(ringBuffer.get(0).get(), is(0L)); |
| 54 | + assertThat(ringBuffer.get(1).get(), is(0L)); |
| 55 | + } |
| 56 | + |
| 57 | + private static class AtomicLongWorkHandler implements WorkHandler<AtomicLong> |
| 58 | + { |
| 59 | + @Override |
| 60 | + public void onEvent(AtomicLong event) throws Exception |
| 61 | + { |
| 62 | + event.incrementAndGet(); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + private static class AtomicLongEventFactory implements EventFactory<AtomicLong> |
| 68 | + { |
| 69 | + @Override |
| 70 | + public AtomicLong newInstance() |
| 71 | + { |
| 72 | + return new AtomicLong(0); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments