2009-06-10 53 views
0

我运行多个任务幂等收集一批数据。我发现很多时候,由于几百个任务中的一些任务,计算延迟很大。加快掉队幂等任务

我想是看这些任务,并再次启动散兵游勇,如果他们显著延迟的一种方式。

是否有在Java这样一个标准库或成语?我目前使用的ExecutorService/ExecutorCompletionService对来完成这项工作。

回答

2

如果您有权访问表示此任务的Future对象,那么您可以检查isDone()cancel()(如果需要)。您必须轮询这些未来的对象并相应地重新提交。它也取决于你的基础Runnables适当地处理InterruptExceptions。

1

您可以创建一个类型的任务管理器中保存到每个任务的参考。这个任务管理器可以负责启动每个任务并管理ExecutorService。每项任务的第一个和最后一个操作是向经理注册任务的开始和结束。然后经理可以建立一个统计图片,这是执行每项任务所需时间的平均值。

任务管理器定期通过其运行寻找“离群”仍在运行和已经拍摄特定任务的平均时间漂移significanty任务列表扫描。然后它可以取消这些任务并重新启动它们。

以下是你可以做一个非常粗略的轮廓......

public class Task implements Runnable { 
    protected TaskManager manager_ = null; 
    protected String taskClass_ = null; 
    protected String taskId_ = null; 

    protected Task(TaskManager manager, String taskClass) { 
     manager_ = manager; 
     taskClass_ = taskClass; 
    } 

    /* 
     * Override this and perform specific task. 
     */ 
    protected void perform() { } 

    public void run() { 
     try { 
      manager_.taskStarted(this); 
      perform(); 
      manager_.taskCompleted(this); 
     catch(InterruptedException) { 
      manager_.taskAborted(this); 
     } 
     finally { 
     } 
    } 
} 


public class TaskManager { 
    ExecutorService service_ = null; 

    public TaskManager() { 
     service_ = new ExecutorService(); 
     // start the monitoring thread. 
     service_.execute(this); 
    } 

    public void runTask(Task t) { 
     service_.execute(t); 
    } 

    public void taskStarted(Task t) { 

     1. Note the time that this task (with unique id) has started. 
     2. Add time to a hash map. 
     3. Add task to list of executing tasks. 
    } 

    public void taskComplete(Task t) { 
     1. Find the task id in hash map 
     2. note how long it took to execute. 
     3. modify statistics of how long the task took against 
      the task Class Id. 
     4. Remove task from list of executing tasks. 
    } 

    public void taskAborted(Task t) { 
     // just remove the task from list of running tasks 
     // without altering the statistics. 
    } 
    public void run() { 
     1. Go though the list of executing tasks looking for 
      tasks whose current time - start time is outside the 
      time statistics for the task class id. 
     2. cancel the task and start again. 
    } 
}