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 public long getDelay(TimeUnit unit) { 063 // if the answer is 0 then this task is ready to be taken 064 long answer = id - index.get(); 065 if (answer <= 0) { 066 return answer; 067 } 068 // okay this task is not ready yet, and we don't really know when it would be 069 // so we have to return a delay value of one time unit 070 if (TimeUnit.NANOSECONDS == unit) { 071 // okay this is too fast so use a little more delay to avoid CPU burning cycles 072 answer = unit.convert(1, TimeUnit.MICROSECONDS); 073 } else { 074 answer = unit.convert(1, unit); 075 } 076 return answer; 077 } 078 079 @SuppressWarnings("unchecked") 080 public int compareTo(Delayed o) { 081 SubmitOrderFutureTask other = (SubmitOrderFutureTask) o; 082 return (int) (this.id - other.id); 083 } 084 085 @Override 086 protected void done() { 087 // when we are done add to the completion queue 088 completionQueue.add(this); 089 } 090 091 @Override 092 public String toString() { 093 // output using zero-based index 094 return "SubmitOrderedFutureTask[" + (id - 1) + "]"; 095 } 096 } 097 098 public SubmitOrderedCompletionService(Executor executor) { 099 this.executor = executor; 100 } 101 102 public Future<V> submit(Callable<V> task) { 103 if (task == null) { 104 throw new IllegalArgumentException("Task must be provided"); 105 } 106 SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task); 107 executor.execute(f); 108 return f; 109 } 110 111 public Future<V> submit(Runnable task, Object result) { 112 if (task == null) { 113 throw new IllegalArgumentException("Task must be provided"); 114 } 115 SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task, null); 116 executor.execute(f); 117 return f; 118 } 119 120 public Future<V> take() throws InterruptedException { 121 index.incrementAndGet(); 122 return completionQueue.take(); 123 } 124 125 public Future<V> poll() { 126 index.incrementAndGet(); 127 Future<V> answer = completionQueue.poll(); 128 if (answer == null) { 129 // decrease counter if we didnt get any data 130 index.decrementAndGet(); 131 } 132 return answer; 133 } 134 135 public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException { 136 index.incrementAndGet(); 137 Future<V> answer = completionQueue.poll(timeout, unit); 138 if (answer == null) { 139 // decrease counter if we didnt get any data 140 index.decrementAndGet(); 141 } 142 return answer; 143 } 144 145 /** 146 * Marks the current task as timeout, which allows you to poll the next 147 * tasks which may already have been completed. 148 */ 149 public void timeoutTask() { 150 index.incrementAndGet(); 151 } 152 153}