Implementing Thread-Safe Counters with the thread-safe Atomic objects - Java Thread

Java examples for Thread:Thread Safe

Description

Implementing Thread-Safe Counters with the thread-safe Atomic objects

Demo Code

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

public class Main {

  public static void main(String[] args) {
    List<Order> orders = Collections.synchronizedList(new ArrayList<Order>());
    AtomicLong orderIdGenerator = new AtomicLong(0);
    for (int i = 0; i < 10; i++) {
      Thread orderCreationThread = new Thread(() -> {
        for (int j = 0; j < 10; j++) {
          long orderId = orderIdGenerator.incrementAndGet();
          Order order = new Order(Thread.currentThread().getName(), orderId);
          orders.add(order);//from w  w w  .j  a v a2s  . com
        }
      });
      orderCreationThread.setName("Order Creation Thread " + i);
      orderCreationThread.start();
    }
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Set<Long> orderIds = new HashSet<>();
    orders.stream().map((order) -> {
      if (orderIds.contains(order.getOrderId())) {
        System.out.println("reused");
      }
      return order;
    }).map((order) -> {
      orderIds.add(order.getOrderId());
      return order;
    }).forEach((order) -> {
      System.out.println("Order id:" + order.getOrderId());
    });
  }
}

class Order {
  String orderName;
  long orderId;

  Order(String orderName, long orderId) {
    this.orderName = orderName;
    this.orderId = orderId;
  }

  public String getOrderName() {
    return orderName;
  }

  public long getOrderId() {
    return orderId;
  }
}

Result


Related Tutorials