Java Reference
In-Depth Information
10-9. Implementing Thread-Safe Coun-
ters
Problem
You need a counter that is thread-safe so that it can be incremented from within differ-
ent execution threads.
Solution
By using the inherently thread-safe Atomic objects, it is possible to create a counter
that guarantees thread safety and has an optimized synchronization strategy. In the fol-
lowing code, an Order object is created, and it requires a unique order ID that is gen-
erated using the AtomicLong incrementAndGet() method:
AtomicLong orderIdGenerator = new AtomicLong(0);
for (int i =0;i < 10;i++) {
Thread orderCreationThread = new Thread(() ->
{
for (int i1 = 0; i1 < 10; i1++) {
createOrder(Thread.currentThread().getName());
}
});
orderCreationThread.setName("Order Creation
Thread "+i);
orderCreationThread.start();
}
//////////////////////////////////////////////////////
private void createOrder(String name) {
long orderId = orderIdGenerator.incrementAndGet();
Order order = new Order(name, orderId);
orders.add(order);
}
Search WWH ::




Custom Search