ExecutionTask implements ITask { @Override public void execute() throws TaskExecutionException { taskDispatcher.notifyThreadStart(); try { while (taskDispatcher.getExecutionTask() == this) { if (Thread.interrupted()) { Thread.currentThread().interrupt(); return; } ITask task = taskDispatcher.getTaskQueue().tryTake(); if (null == task) { return; } taskDispatcher.notifyTaskTaken(); taskDispatcher.getThreadPool().tryExecute(this); task.execute(); } taskDispatcher.getThreadPool().tryExecute(taskDispatcher.getExecutionTask()); } finally { taskDispatcher.notifyThreadStop(); } } ExecutionTask(final TaskDispatcher taskDispatcher); @Override void execute();  }
@Test(timeout = 100L) public void Should_exit_When_thereIsNoTask() throws Exception { ExecutionTask executionTask = new ExecutionTask(dispatcherMock); when(dispatcherMock.getExecutionTask()).thenReturn(executionTask); when(queueMock.tryTake()).thenReturn(null); executionTask.execute(); }
@Test(timeout = 100L) public void Should_exit_When_threadIsInterrupted() throws Exception { ExecutionTask executionTask = new ExecutionTask(dispatcherMock); when(dispatcherMock.getExecutionTask()).thenReturn(executionTask); Thread.currentThread().interrupt(); executionTask.execute(); verify(queueMock, never()).tryTake(); assertTrue(Thread.interrupted()); }
@Test(timeout = 100L) public void Should_exit_When_currentExecutionTaskChanges() throws Exception { ExecutionTask executionTask = new ExecutionTask(dispatcherMock); ITask nextExecTsk = mock(ExecutionTask.class); when(dispatcherMock.getExecutionTask()).thenReturn(nextExecTsk); executionTask.execute(); verify(queueMock, never()).tryTake(); verify(threadPoolMock).tryExecute(same(nextExecTsk)); }
@Test(timeout = 100L) public void Should_takeAndExecuteTasks() throws Exception { ITask taskMock = mock(ITask.class); when(queueMock.tryTake()) .thenReturn(taskMock) .thenReturn(null); ExecutionTask executionTask = new ExecutionTask(dispatcherMock); when(dispatcherMock.getExecutionTask()).thenReturn(executionTask); executionTask.execute(); verify(taskMock).execute(); }
@Test(timeout = 100L) public void Should_executeItselfOnNewThreadIfCanGetOne() throws Exception { ITask taskMock = mock(ITask.class); ExecutionTask executionTask = new ExecutionTask(dispatcherMock); when(dispatcherMock.getExecutionTask()).thenReturn(executionTask); when(queueMock.tryTake()) .thenReturn(taskMock) .thenReturn(null); when(threadPoolMock.tryExecute(same(executionTask))) .thenReturn(true) .thenReturn(false); executionTask.execute(); verify(taskMock).execute(); verify(threadPoolMock).tryExecute(same(executionTask)); }