Jas*_*n S 5 java concurrency semaphore locking
假设我有一个ExecutorService(可以是一个线程池,因此涉及并发),它可以在不同的时间执行任务,定期或响应某些其他条件.要执行的任务如下:
我正试图想办法实现这个.它应该是这样的:
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)
哪里SomeObj是ReentrantLock(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)
您建议的锁实现很弱,因为有人很容易不当使用它。
下面是一个更有效的实现,与您的实现具有相同的不当使用弱点:
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)
| 归档时间: |
|
| 查看次数: |
1510 次 |
| 最近记录: |