@Test(timeout = 10000) public void shutdownShouldNotLeadToThreadInitialization() throws InterruptedException { DaemonThreadFactory factory = new DaemonThreadFactory("42"); util.setThreadFactory(factory); util.shutdownBackgroundExecutor(); assertEquals(0, factory.getCreatedThreads()); }
@Test(timeout = 10000) public void shouldCorrectlyStopBackgroundExecutor() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Thread[] executorThread = new Thread[1]; Runnable task = () -> { executorThread[0] = Thread.currentThread(); latch.countDown(); }; Executor executor = util.getBackgroundExecutor(); util.execute(executor, task); latch.await(); util.shutdownBackgroundExecutor(); executorThread[0].join(); }
@Test(timeout = 10000) public void shouldApplyThreadFactory() throws InterruptedException { ThreadFactory factory = new DaemonThreadFactory("42"); util.setThreadFactory(factory); Executor executor = util.getBackgroundExecutor(); CountDownLatch latch = new CountDownLatch(1); AtomicReference<String> threadName = new AtomicReference<>(); executor.execute( () -> { threadName.set(Thread.currentThread().getName()); latch.countDown(); }); latch.await(); assertEquals("42", threadName.get()); }
@Test(timeout = 10000) public void shouldExecuteTaskInCurrentThreadWhenExecutorThrowException() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Executor executor = task -> { throw new RejectedExecutionException(); }; Runnable task = latch::countDown; util.execute(executor, task); latch.await(); }
@Test(timeout = 10000) public void shouldExecuteTaskInCurrentThreadExactlyOnceWhenExecutorThrowException() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); AtomicInteger executionCount = new AtomicInteger(); Executor executor = task -> { task.run(); throw new RejectedExecutionException(); }; Runnable task = () -> { executionCount.incrementAndGet(); latch.countDown(); }; util.execute(executor, task); latch.await(); assertEquals(1, executionCount.get()); }
@Test(timeout = 10000) public void shouldAlwaysReturnSameInstanceOfBackgroundExecutor() throws InterruptedException { assertSame(util.getBackgroundExecutor(), util.getBackgroundExecutor()); }
@Test(expected = IllegalStateException.class) public void shouldDisallowReplaceThreadFactoryWhenExecutorAlreadyCreated() { util.getBackgroundExecutor(); util.setThreadFactory(new DaemonThreadFactory("")); }