Java ConcurrentSkipListMap class

Description

Java ConcurrentSkipListMap class


import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

class Task implements Runnable {
  private ConcurrentSkipListMap<String, String> map;
  private String id;
  public Task(ConcurrentSkipListMap<String, String> map, String id) {
    this.id = id;
    this.map = map;
  }//w ww  . ja v a  2  s  .c  om

  @Override
  public void run() {
    for (int i = 0; i < 1000; i++) {
      String contact = id+ String.valueOf(i + 1000);
      map.put(id, contact);
    }
  }
}
public class Main {
  public static void main(String[] args) {
    ConcurrentSkipListMap<String, String> map;
    map = new ConcurrentSkipListMap<>();
    Thread[] threads = new Thread[25];

    for (int i = 0; i < threads.length; i++) {
      Task task = new Task(map, String.valueOf(i));
      threads[i] = new Thread(task);
      threads[i].start();
    }

    for (int i = 0; i < threads.length; i++) {
      try {
        threads[i].join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.printf("Main: Size of the map: %d\n", map.size());

    Map.Entry<String, String> element = map.firstEntry();
    String contact = element.getValue();
    System.out.println("First Entry: "+ contact);
    element = map.lastEntry();
    contact = element.getValue();
    System.out.println("Main: Last Entry: "+ contact);
    ConcurrentNavigableMap<String, String> submap = map.subMap("1", "12");
    do {
      element = submap.pollFirstEntry();
      if (element != null) {
        contact = element.getValue();
        System.out.println(contact);
      }
    } while (element != null);
  }
}



PreviousNext

Related