001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.util.concurrent;
018
019import java.util.concurrent.Callable;
020import java.util.concurrent.CompletionService;
021import java.util.concurrent.DelayQueue;
022import java.util.concurrent.Delayed;
023import java.util.concurrent.Executor;
024import java.util.concurrent.Future;
025import java.util.concurrent.FutureTask;
026import java.util.concurrent.TimeUnit;
027import java.util.concurrent.atomic.AtomicInteger;
028
029/**
030 * A {@link java.util.concurrent.CompletionService} that orders the completed tasks
031 * in the same order as they where submitted.
032 */
033public class SubmitOrderedCompletionService<V> implements CompletionService<V> {
034    
035    private final Executor executor;
036
037    // the idea to order the completed task in the same order as they where submitted is to leverage
038    // the delay queue. With the delay queue we can control the order by the getDelay and compareTo methods
039    // where we can order the tasks in the same order as they where submitted.
040    private final DelayQueue<SubmitOrderFutureTask> completionQueue = new DelayQueue<>();
041
042    // id is the unique id that determines the order in which tasks was submitted (incrementing)
043    private final AtomicInteger id = new AtomicInteger();
044    // index is the index of the next id that should expire and thus be ready to take from the delayed queue
045    private final AtomicInteger index = new AtomicInteger();
046
047    private class SubmitOrderFutureTask extends FutureTask<V> implements Delayed {
048
049        // the id this task was assigned
050        private final long id;
051
052        SubmitOrderFutureTask(long id, Callable<V> voidCallable) {
053            super(voidCallable);
054            this.id = id;
055        }
056
057        SubmitOrderFutureTask(long id, Runnable runnable, V result) {
058            super(runnable, result);
059            this.id = id;
060        }
061
062        @Override
063        public long getDelay(TimeUnit unit) {
064            // if the answer is 0 then this task is ready to be taken
065            long answer = id - index.get();
066            if (answer <= 0) {
067                return answer;
068            }
069            // okay this task is not ready yet, and we don't really know when it would be
070            // so we have to return a delay value of one time unit
071            if (TimeUnit.NANOSECONDS == unit) {
072                // okay this is too fast so use a little more delay to avoid CPU burning cycles
073                answer = unit.convert(1, TimeUnit.MICROSECONDS);
074            } else {
075                answer = unit.convert(1, unit);
076            }
077            return answer;
078        }
079
080        @Override
081        @SuppressWarnings("unchecked")
082        public int compareTo(Delayed o) {
083            SubmitOrderFutureTask other = (SubmitOrderFutureTask) o;
084            return (int) (this.id - other.id);
085        }
086
087        @Override
088        protected void done() {
089            // when we are done add to the completion queue
090            completionQueue.add(this);
091        }
092
093        @Override
094        public String toString() {
095            // output using zero-based index
096            return "SubmitOrderedFutureTask[" + (id - 1) + "]";
097        }
098    }
099
100    public SubmitOrderedCompletionService(Executor executor) {
101        this.executor = executor;
102    }
103
104    @Override
105    public Future<V> submit(Callable<V> task) {
106        if (task == null) {
107            throw new IllegalArgumentException("Task must be provided");
108        }
109        SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task);
110        executor.execute(f);
111        return f;
112    }
113
114    @Override
115    public Future<V> submit(Runnable task, Object result) {
116        if (task == null) {
117            throw new IllegalArgumentException("Task must be provided");
118        }
119        SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task, null);
120        executor.execute(f);
121        return f;
122    }
123
124    @Override
125    public Future<V> take() throws InterruptedException {
126        index.incrementAndGet();
127        return completionQueue.take();
128    }
129
130    @Override
131    public Future<V> poll() {
132        index.incrementAndGet();
133        Future<V> answer = completionQueue.poll();
134        if (answer == null) {
135            // decrease counter if we didnt get any data
136            index.decrementAndGet();
137        }
138        return answer;
139    }
140
141    @Override
142    public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException {
143        index.incrementAndGet();
144        Future<V> answer = completionQueue.poll(timeout, unit);
145        if (answer == null) {
146            // decrease counter if we didnt get any data
147            index.decrementAndGet();
148        }
149        return answer;
150    }
151
152    /**
153     * Marks the current task as timeout, which allows you to poll the next
154     * tasks which may already have been completed.
155     */
156    public void timeoutTask() {
157        index.incrementAndGet();
158    }
159
160}