Source Code : Use AtomicLong to generate ID

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Use AtomicLong to generate ID

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 Test {

  public static void main(String[] args) {
    final AtomicLong orderIdGenerator = new AtomicLong(0);
    final List<Item> orders = Collections
        .synchronizedList(new ArrayList<Item>());

    for (int i = 0; i < 10; i++) {
      Thread orderCreationThread = new Thread(new Runnable() {
        public void run() {
          for (int i = 0; i < 10; i++) {
            long orderId = orderIdGenerator.incrementAndGet();
            Item order = new Item(Thread.currentThread().getName(), orderId);
            orders.add(order);
          }
        }
      });
      orderCreationThread.setName("Order Creation Thread " + i);
      orderCreationThread.start();
    }
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Set<Long> orderIds = new HashSet<Long>();
    for (Item order : orders) {
      orderIds.add(order.getID());
      System.out.println("Order id:" + order.getID());
    }
  }
}

class Item {
  String itemName;
  long id;

  Item(String n, long id) {
    this.itemName = n;
    this.id = id;
  }

  public String getItemName() {
    return itemName;
  }

  public long getID() {
    return id;
  }
}

 

Thank with us