【发布时间】:2015-08-18 19:52:08
【问题描述】:
这是我的类,它连续执行依赖Runnables。它的作用是所有Runnable 都并行执行,但在完成后等待队列中的head Runnable 首先完成。头部完成后,第二项完成,依此类推。
此代码的问题在于它会导致某种死锁。当执行许多任务时,它会停止执行。暂停调试器时,显示所有线程都在等待wait() 语句。
/**
* Executes all tasks in parallel, with completion handler called only when other tasks of same key are complete.
* For a given key, the order in which {@link #execute(Object, int, java.util.concurrent.Callable, Runnable, Runnable)} was called will be the order in which completion runnable will be called.
*/
public class DependentExecutor {
private final Executor executor;
private final Map<Object, Queue<DependentTask>> allTasks = new ArrayMap<>();
private final boolean enableDependency;
public DependentExecutor(boolean enableDependency, Executor executor) {
this.executor = executor;
this.enableDependency = enableDependency;
}
/**
* You should return true from the task on successful completion.
* If task returns false, then completion runnable wont be executed.
* <p/>
* This method will return false if tha task with this uniqueId already exists. Otherwise true is returned.
*
* @param key A non null key using which task dependency is decided. Tasks with same key are dependent.
* @param uniqueId If there is a task with this uniqueId already present, this task will be rejected
* @param task Optional. A long pending task to be performed or null if only completion is to be dependant.
* @param completionCallback A non null callback which will be serially executed for tasks with same key
* @param errorCallback If task returns false, then this callback will be invoked immediately (no dependency)
*/
public boolean execute(Object key, int uniqueId, Callable<Boolean> task, Runnable completionCallback, Runnable errorCallback) {
DependentTask queuedTask;
synchronized (allTasks) {
Queue<DependentTask> queue = allTasks.get(key);
for (Map.Entry<Object, Queue<DependentTask>> objectQueueEntry : allTasks.entrySet()) {
synchronized (objectQueueEntry.getValue()) {
Iterator<DependentTask> iterator = objectQueueEntry.getValue().iterator();
while (iterator.hasNext()) {
DependentTask dependentTask = iterator.next();
if (dependentTask.getUniqueId() == uniqueId) {
// no 2 tasks can have same uniqueID
return false;
}
}
}
}
if (queue == null && task == null) {
// this means we have no pending dependency as well as no task to perform. So only callback.
completionCallback.run();
return true;
} else if (queue == null) {
queue = new LinkedList<DependentTask>();
allTasks.put(key, queue);
}
if (!enableDependency) {
key = Math.random();
}
queuedTask = new DependentTask(key, uniqueId, queue, task, completionCallback, errorCallback);
queue.add(queuedTask);
}
executor.execute(queuedTask);
return true;
}
class DependentTask implements Runnable {
private final Queue<DependentTask> dependencyQueue;
private final Callable<Boolean> task;
private final Object key;
private final Runnable completionCallback;
private final Runnable errorCallback;
private final int uniqueId;
public DependentTask(Object key, int uniqueId, Queue<DependentTask> dependencyQueue, Callable<Boolean> task, Runnable completionCallback, Runnable errorCallback) {
this.uniqueId = uniqueId;
this.task = task;
this.dependencyQueue = dependencyQueue;
this.key = key;
this.completionCallback = completionCallback;
this.errorCallback = errorCallback;
}
public int getUniqueId() {
return uniqueId;
}
@Override
public void run() {
Boolean result = false;
try {
if (task != null) {
result = task.call();
} else {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (result) {
synchronized (dependencyQueue) {
while (dependencyQueue.peek() != this) {
try {
dependencyQueue.wait(); // deadlock !!
} catch (InterruptedException e) {
}
}
}
completionCallback.run(); // by now we are the first element in the linked list. Lets call completion.
} else {
errorCallback.run(); // by now we are the first element in the linked list. Lets call error callback.
}
synchronized (dependencyQueue) {
dependencyQueue.remove(); //remove thyself
dependencyQueue.notifyAll();
}
// clean up of main map
synchronized (allTasks) {
if (dependencyQueue.isEmpty()) {
allTasks.remove(key);
}
}
}
}
}
}
【问题讨论】:
-
我没有看到你在该队列中添加任何东西。什么时候发生?
-
你能提供一个主要的方法来演示它的用法吗?
-
复杂、深度嵌套和大量
synchronized。你确定这不能用docs.oracle.com/javase/8/docs/api/java/util/concurrent/… 更容易地解决吗?
标签: java multithreading deadlock wait notify