java:executors + tasks + locks

Jas*_*n S 5 java concurrency semaphore locking

假设我有一个ExecutorService(可以是一个线程池,因此涉及并发),它可以在不同的时间执行任务,定期或响应某些其他条件.要执行的任务如下:

  • 如果此任务已在进行中,则不执行任何操作(并让以前运行的任务完成).
  • 如果此任务尚未进行,请运行算法X,这可能需要很长时间.

我正试图想办法实现这个.它应该是这样的:

Runnable task = new Runnable() {
   final SomeObj inProgress = new SomeObj();
   @Override public void run() {
       if (inProgress.acquire())
       {
          try
          {
             algorithmX();
          }
          finally
          {
             inProgress.release();
          }
       }
   }
}

// re-use this task object whenever scheduling the task with the executor
Run Code Online (Sandbox Code Playgroud)

哪里SomeObjReentrantLock(acquire = tryLock()和release = unlock())或者是AtomicBoolean等等,但我不知道哪个.我在这里需要一个ReentrantLock吗?(也许我想要一个非重入锁,以防止algorithmX()这个任务以递归方式运行!)或者AtomicBoolean会不够?


编辑:对于非重入锁定,这是否合适?

Runnable task = new Runnable() {
   boolean inProgress = false;
   final private Object lock = new Object();
   /** try to acquire lock: set inProgress to true, 
    *  return whether it was previously false
    */ 
   private boolean acquire() {
      synchronized(this.lock)
      {
         boolean result = !this.inProgress;
         this.inProgress = true;
         return result;
      }
   }
   /** release lock */
   private void release() {
      synchronized(this.lock)
      {
         this.inProgress = false;
      }
   }
   @Override public void run() {
       if (acquire())
       {
          // nobody else is running! let's do algorithmX()
          try
          {
             algorithmX();
          }
          finally
          {
             release();
          }
       }
       /* otherwise, we are already in the process of 
        * running algorithmX(), in this thread or in another,
        * so don't do anything, just return control to the caller.
        */
   }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*der 2

您建议的锁实现很弱,因为有人很容易不当使用它。

下面是一个更有效的实现,与您的实现具有相同的不当使用弱点:

   AtomicBoolean inProgress = new AtomicBoolean(false)
   /* Returns true if we acquired the lock */
   private boolean acquire() {
       return inProgress.compareAndSet(false, true);
   }
   /** Always release lock without determining if we in fact hold it */
   private void release() {
       inProgress.set(false);
   }
Run Code Online (Sandbox Code Playgroud)

  • @user359996,此实现在调用release时无条件释放锁。从技术上讲,这满足了“Lock”接口的要求,但检查调用线程的设计考虑(IMO)是一个重要的因素。 (2认同)