Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.concurrent.*;
- public class Playground {
- private static class Task implements Runnable {
- public static final int MAX_VALUE = 1_000_000;
- public volatile int sink;
- private static final Random RND = new Random();
- private int value;
- private ConcurrentMap<Task, Boolean> taskRegistry;
- public Task(int aValue, ConcurrentMap<Task, Boolean> aTaskregistry) {
- value = aValue;
- taskRegistry = aTaskregistry;
- }
- @Override
- public void run() {
- Boolean alreadyProcessing = taskRegistry.putIfAbsent(this, true);
- if (alreadyProcessing != null) {
- System.out.printf("Task for value %d already found in registry\n", this.value);
- return;
- }
- for (int i = MAX_VALUE; i < MAX_VALUE + 10_000; ++i) {
- if (value == i) {
- sink = 1;
- break;
- }
- }
- taskRegistry.remove(this);
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof Task)) {
- return false;
- }
- Task otherTask = (Task) obj;
- if (this.value == otherTask.value) {
- return true;
- }
- return false;
- }
- @Override
- public int hashCode() {
- return Integer.hashCode(value);
- }
- public static Task newRandomTask(ConcurrentMap<Task, Boolean> taskRegistry) {
- return new Task(RND.nextInt(Task.MAX_VALUE), taskRegistry);
- }
- }
- public static void main(String[] args) {
- ExecutorService executor = Executors.newFixedThreadPool(4);
- ConcurrentMap<Task, Boolean> concurrentTaskRegistry = new ConcurrentHashMap<>();
- for (int i = 0; i < Task.MAX_VALUE; ++i) {
- executor.execute(Task.newRandomTask(concurrentTaskRegistry));
- }
- executor.shutdown();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement