Skip to content

Instantly share code, notes, and snippets.

@dev-aritra
Last active May 9, 2021 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev-aritra/0313192aa426acb7e81a7cdb31ba93ac to your computer and use it in GitHub Desktop.
Save dev-aritra/0313192aa426acb7e81a7cdb31ba93ac to your computer and use it in GitHub Desktop.
@Test
void shouldCreateOrder() throws InterruptedException {
Product iPhone12 = new Product("iPhone12", 1);
productRepository.saveAndFlush(iPhone12); // Insert product with count 1 into DB
ExecutorService threadPool = Executors.newFixedThreadPool(10); // Create a threadpool with 10 threads
List<Callable<Optional<Order>>> orderRequests = getOrderRequests(iPhone12.getId(), 20); // Create 20 tasks for placing 20 orders
List<Future<Optional<Order>>> results = threadPool.invokeAll(orderRequests); // Place those 20 orders simulteanously
long successCount = results.stream() // Calculate how many orders got placed successfully
.filter(Future::isDone)
.map(result -> {
try {
return result.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return Optional.empty();
}
})
.filter(Optional::isPresent)
.count();
assertEquals(1, successCount); // Assert that only one order was successfull since we had only one item
}
private List<Callable<Optional<Order>>> getOrderRequests(Long productId, int count) {
return LongStream.range(0, count) // Generate tasks for placing orders
.mapToObj(index -> {
Callable<Optional<Order>> task = () -> orderService.placeOrder(productId, index); // Single task for placing order
return task;
}).collect(Collectors.toList());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment