Skip to content

Commit

Permalink
test: document SerialExecutor expected behavior
Browse files Browse the repository at this point in the history
Classes that depend on the SerialExecutor assume that the tasks are
executed and processed in the order of insertion. This test verifies
this.

Signed-off-by: Marc Nuri <[email protected]>
  • Loading branch information
manusa committed May 23, 2022
1 parent 2629db3 commit 2d73f03
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
* See {@link Executor} docs
*
* <br>
* Effectively creates a derived single thread executor
* Effectively creates a derived single thread executor, runnable tasks are executed in the order they are added.
* This is a replacement for Executors.newSingleThreadExecutor() that uses threads in a non-dedicated way
* <br>
* Added shutdown support
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
import org.junit.jupiter.api.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;

class SerialExecutorTest {
Expand Down Expand Up @@ -53,4 +56,31 @@ void clearInterrupt() {
assertFalse(interrupted.join()); // make sure the second is not interrrupted
}

@Test
void taskExecutedInOrderOfInsertion() throws InterruptedException {
final ExecutorService es = Executors.newSingleThreadExecutor();
try {
final StringBuffer sb = new StringBuffer();
final SerialExecutor se = new SerialExecutor(es);
final CountDownLatch latch = new CountDownLatch(1);
se.execute(() -> {
sb.append("1");
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
se.execute(() -> sb.append("2"));
se.execute(() -> sb.append("3"));
se.execute(() -> sb.append("4"));
se.execute(() -> sb.append("5"));
se.execute(latch::countDown);
assertThat(latch.await(500L, TimeUnit.MILLISECONDS)).isTrue();
assertThat(sb).hasToString("12345");
} finally {
es.shutdownNow();
}
}

}

0 comments on commit 2d73f03

Please sign in to comment.