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<SubmitOrderFutureTask>(); 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 answer = unit.convert(1, TimeUnit.MICROSECONDS); 075 } else { 076 answer = unit.convert(1, unit); 077 } 078 return answer; 079 } 080 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 public Future<V> submit(Callable<V> task) { 105 if (task == null) { 106 throw new IllegalArgumentException("Task must be provided"); 107 } 108 SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task); 109 executor.execute(f); 110 return f; 111 } 112 113 public Future<V> submit(Runnable task, Object result) { 114 if (task == null) { 115 throw new IllegalArgumentException("Task must be provided"); 116 } 117 SubmitOrderFutureTask f = new SubmitOrderFutureTask(id.incrementAndGet(), task, null); 118 executor.execute(f); 119 return f; 120 } 121 122 public Future<V> take() throws InterruptedException { 123 index.incrementAndGet(); 124 return completionQueue.take(); 125 } 126 127 public Future<V> poll() { 128 index.incrementAndGet(); 129 Future<V> answer = completionQueue.poll(); 130 if (answer == null) { 131 // decrease counter if we didnt get any data 132 index.decrementAndGet(); 133 } 134 return answer; 135 } 136 137 public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException { 138 index.incrementAndGet(); 139 Future<V> answer = completionQueue.poll(timeout, unit); 140 if (answer == null) { 141 // decrease counter if we didnt get any data 142 index.decrementAndGet(); 143 } 144 return answer; 145 } 146 147 /** 148 * Marks the current task as timeout, which allows you to poll the next 149 * tasks which may already have been completed. 150 */ 151 public void timeoutTask() { 152 index.incrementAndGet(); 153 } 154 155}