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 *
033 * @version 
034 */
035public class SubmitOrderedCompletionService<V> implements CompletionService<V> {
036    
037    private final Executor executor;
038
039    // the idea to order the completed task in the same order as they where submitted is to leverage
040    // the delay queue. With the delay queue we can control the order by the getDelay and compareTo methods
041    // where we can order the tasks in the same order as they where submitted.
042    private final DelayQueue<SubmitOrderFutureTask> completionQueue = new DelayQueue<>();
043
044    // id is the unique id that determines the order in which tasks was submitted (incrementing)
045    private final AtomicInteger id = new AtomicInteger();
046    // index is the index of the next id that should expire and thus be ready to take from the delayed queue
047    private final AtomicInteger index = new AtomicInteger();
048
049    private class SubmitOrderFutureTask extends FutureTask<V> implements Delayed {
050
051        // the id this task was assigned
052        private final long id;
053
054        SubmitOrderFutureTask(long id, Callable<V> voidCallable) {
055            super(voidCallable);
056            this.id = id;
057        }
058
059        SubmitOrderFutureTask(long id, Runnable runnable, V result) {
060            super(runnable, result);
061            this.id = id;
062        }
063
064        public long getDelay(TimeUnit unit) {
065            // if the answer is 0 then this task is ready to be taken
066            long answer = id - index.get();
067            if (answer <= 0) {
068                return answer;
069            }
070            // okay this task is not ready yet, and we don't really know when it would be
071            // so we have to return a delay value of one time unit
072            if (TimeUnit.NANOSECONDS == unit) {
073                // okay this is too fast so use a little more delay to avoid CPU burning cycles
074                // To avoid aligh with java 11 impl of
075                // "java.util.concurrent.locks.AbstractQueuedSynchronizer.SPIN_FOR_TIMEOUT_THRESHOLD", otherwise
076                // no sleep with very high CPU usage
077                answer = 1001L;
078            } else {
079                answer = unit.convert(1, unit);
080            }
081            return answer;
082        }
083
084        @SuppressWarnings("unchecked")
085        public int compareTo(Delayed o) {
086            SubmitOrderFutureTask other = (SubmitOrderFutureTask) o;
087            return (int) (this.id - other.id);
088        }
089
090        @Override
091        protected void done() {
092            // when we are done add to the completion queue
093            completionQueue.add(this);
094        }
095
096        @Override
097        public String toString() {
098            // output using zero-based index
099            return "SubmitOrderedFutureTask[" + (id - 1) + "]";
100        }
101    }
102
103    public SubmitOrderedCompletionService(Executor executor) {
104        this.executor = executor;
105    }
106
107    public Future<V> submit(Callable<V> task) {
108        if (task == null) {
109            throw new IllegalArgumentException("Task must be provided");
110        }
111        SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task);
112        executor.execute(f);
113        return f;
114    }
115
116    public Future<V> submit(Runnable task, Object result) {
117        if (task == null) {
118            throw new IllegalArgumentException("Task must be provided");
119        }
120        SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task, null);
121        executor.execute(f);
122        return f;
123    }
124
125    public Future<V> take() throws InterruptedException {
126        index.incrementAndGet();
127        return completionQueue.take();
128    }
129
130    public Future<V> poll() {
131        index.incrementAndGet();
132        Future<V> answer = completionQueue.poll();
133        if (answer == null) {
134            // decrease counter if we didnt get any data
135            index.decrementAndGet();
136        }
137        return answer;
138    }
139
140    public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException {
141        index.incrementAndGet();
142        Future<V> answer = completionQueue.poll(timeout, unit);
143        if (answer == null) {
144            // decrease counter if we didnt get any data
145            index.decrementAndGet();
146        }
147        return answer;
148    }
149
150    /**
151     * Marks the current task as timeout, which allows you to poll the next
152     * tasks which may already have been completed.
153     */
154    public void timeoutTask() {
155        index.incrementAndGet();
156    }
157
158}