    001    package com.hammurapi.reasoning.impl;
    002
    003    import java.util.ArrayList;
    004    import java.util.List;
    005    import java.util.concurrent.Callable;
    006    import java.util.concurrent.atomic.AtomicInteger;
    007
    008    import com.hammurapi.util.concurrent.NonBlockingNotifyingFutureTask;
    009    import com.hammurapi.util.concurrent.TaskCounter;
    010
    011    public class NonBlockingPriorityNotifyingFutureTask<V, A> extends NonBlockingNotifyingFutureTask<V> implements Comparable<NonBlockingPriorityNotifyingFutureTask<V, A>> {
    012
    013            private static final AtomicInteger counter = new AtomicInteger();
    014
    015            private List<InferenceToken<Object>> inferenceTokens = new ArrayList<InferenceToken<Object>>();
    016            private int priority;
    017            private int serno;
    018
    019            @SuppressWarnings("unchecked")
    020            public NonBlockingPriorityNotifyingFutureTask(Callable<V> callable, TaskCounter taskCounter, A[] args, int priority) throws InterruptedException {
    021                    super(callable, taskCounter);
    022                    this.priority = priority;
    023                    for (A arg: args) {
    024                            if (arg instanceof InferenceToken<?>) {
    025                                    ((InferenceToken<?>) arg).taskCreated(priority);
    026                                    inferenceTokens .add((InferenceToken<Object>) arg);
    027                            }
    028                    }
    029                    serno = counter.incrementAndGet();
    030            }
    031
    032            @Override
    033            public void run() {
    034                    try {
    035                            super.run();
    036                    } finally {
    037                            for (InferenceToken<Object> it: inferenceTokens) {
    038                                    it.taskFinished(priority);
    039                            }
    040                    }
    041            }
    042
    043            @Override
    044            public int compareTo(NonBlockingPriorityNotifyingFutureTask<V, A> o) {
    045                    int priorityDifference = o.priority - priority;
    046                    if (priorityDifference!=0) {
    047                            return priorityDifference;
    048                    }
    049                    return serno - o.serno;
    050            }
    051
    052
    053    }