Advertisement
Guest User

Untitled

a guest
Apr 15th, 2016
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.concurrent.*;
  3.  
  4. public class Playground {
  5.  
  6.    private static class Task implements Runnable {
  7.       public static final int MAX_VALUE = 1_000_000;
  8.       public volatile int sink;
  9.  
  10.       private static final Random RND = new Random();
  11.  
  12.       private int value;
  13.       private ConcurrentMap<Task, Boolean> taskRegistry;
  14.  
  15.       public Task(int aValue, ConcurrentMap<Task, Boolean> aTaskregistry) {
  16.          value = aValue;
  17.          taskRegistry = aTaskregistry;
  18.       }
  19.  
  20.       @Override
  21.       public void run() {
  22.          Boolean alreadyProcessing = taskRegistry.putIfAbsent(this, true);
  23.          if (alreadyProcessing != null) {
  24.             System.out.printf("Task for value %d already found in registry\n", this.value);
  25.             return;
  26.          }
  27.          for (int i = MAX_VALUE; i < MAX_VALUE + 10_000; ++i) {
  28.             if (value == i) {
  29.                sink = 1;
  30.                break;
  31.             }
  32.          }
  33.          taskRegistry.remove(this);
  34.       }
  35.  
  36.       @Override
  37.       public boolean equals(Object obj) {
  38.          if (this == obj) {
  39.             return true;
  40.          }
  41.          if (!(obj instanceof Task)) {
  42.             return false;
  43.          }
  44.          Task otherTask = (Task) obj;
  45.          if (this.value == otherTask.value) {
  46.             return true;
  47.          }
  48.          return false;
  49.       }
  50.  
  51.       @Override
  52.       public int hashCode() {
  53.          return Integer.hashCode(value);
  54.       }
  55.  
  56.       public static Task newRandomTask(ConcurrentMap<Task, Boolean> taskRegistry) {
  57.          return new Task(RND.nextInt(Task.MAX_VALUE), taskRegistry);
  58.       }
  59.    }
  60.  
  61.    public static void main(String[] args) {
  62.       ExecutorService executor = Executors.newFixedThreadPool(4);
  63.       ConcurrentMap<Task, Boolean> concurrentTaskRegistry = new ConcurrentHashMap<>();
  64.       for (int i = 0; i < Task.MAX_VALUE; ++i) {
  65.          executor.execute(Task.newRandomTask(concurrentTaskRegistry));
  66.       }
  67.       executor.shutdown();
  68.    }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement