Skip to content

Instantly share code, notes, and snippets.

@xlucasdemelo
Created May 26, 2020 23:05
Show Gist options
  • Save xlucasdemelo/a5cfd5d7df9923d6a5a52592c1c0285a to your computer and use it in GitHub Desktop.
Save xlucasdemelo/a5cfd5d7df9923d6a5a52592c1c0285a to your computer and use it in GitHub Desktop.
@Test
void threadPoolBulkhead() throws InterruptedException {
//Only 5 Threads will be the hability to execute a code
ThreadPoolBulkhead threadPoolBulkhead = ThreadPoolBulkhead.of("threads", ThreadPoolBulkheadConfig.custom()
.coreThreadPoolSize(5)
.maxThreadPoolSize(5)
.build());
//Decorating the execution of the method and the configuration of the threadPool
Supplier<CompletionStage<Void>> withBulkhead = ThreadPoolBulkhead.decorateRunnable(threadPoolBulkhead, this::takeBook);
//Creating a new ExecutorService
ExecutorService service = Executors.newFixedThreadPool(NUMBER_OF_PEOPLE);
//Wrapping the execution of the bulkhead inside a task
Runnable task = () -> {
log.info("Try to get a book");
Try.ofSupplier(withBulkhead);
};
//Creating N threads to execute the task
List<Callable<Object>> tasks = Stream.continually(task)
.map(Executors::callable)
.take(NUMBER_OF_BOOKS).toJavaList();
//Running all the threads
service.invokeAll(tasks, 500, TimeUnit.MILLISECONDS);
}
@Test
void semaphore() throws InterruptedException {
Bulkhead bulkhead = Bulkhead.of("semaphore", BulkheadConfig.custom()
.maxConcurrentCalls(NUMBER_OF_BOOKS)
.build());
Runnable withBulkhead = Bulkhead.decorateRunnable(bulkhead, this::takeBook);
this.captureEvents(bulkhead.getEventPublisher());
everybodyInTheLibrary(withBulkhead);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment