如何确定对象是否被锁定(同步)以便不在Java中阻塞? [英] How do determine if an object is locked (synchronized) so not to block in Java?

查看:796
本文介绍了如何确定对象是否被锁定(同步)以便不在Java中阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个进程A,它在内存中包含一组带有一组记录的表(recordA,recordB等等)

I have a process A that contains a table in memory with a set of records (recordA, recordB, etc...)

现在,这个进程可以启动许多影响记录的线程,有时我们可以有2个线程试图访问同一条记录 - 这种情况必须被拒绝。特别是如果一个记录被一个线程锁定,我希望另一个线程中止(我不想BLOCK或WAIT)。

Now, this process can launch many threads that affect the records, and sometimes we can have 2 threads trying to access the same record - this situation must be denied. Specifically if a record is LOCKED by one thread I want the other thread to abort (I do not want to BLOCK or WAIT).

目前我这样做:

synchronized(record)
{
performOperation(record);
}

但这导致我出现问题......因为Process1正在执行操作,如果Process2进入,则阻塞/等待同步语句,当Process1完成时,它执行操作。相反,我想要这样的东西:

But this is causing me problems ... because while Process1 is performing the operation, if Process2 comes in it blocks/waits on the synchronized statement and when Process1 is finished it performs the operation. Instead I want something like this:

if (record is locked)
   return;

synchronized(record)
{
performOperation(record);
}

有关如何实现这一目标的任何线索?
任何帮助将不胜感激。
谢谢,

Any clues on how this can be accomplished? Any help would be much appreciated. Thanks,

推荐答案

需要注意的一点是 instant 您收到此类信息,这是陈旧的。换句话说,你可能会被告知没有人拥有锁,但是当你试图获取它时,你会阻止,因为另一个线程取出了支票之间的锁定并试图获取它。

One thing to note is that the instant you receive such information, it's stale. In other words, you could be told that no-one has the lock, but then when you try to acquire it, you block because another thread took out the lock between the check and you trying to acquire it.

Brian指向 Lock 是正确的,但我认为你真正想要的是它的 tryLock 方法:

Brian is right to point at Lock, but I think what you really want is its tryLock method:

Lock lock = new ReentrantLock();
......
if (lock.tryLock())
{
    // Got the lock
    try
    {
        // Process record
    }
    finally
    {
        // Make sure to unlock so that we don't cause a deadlock
        lock.unlock();
    }
}
else
{
    // Someone else had the lock, abort
}

你也可以用一段时间等待 tryLock - 所以你可以尝试获取它十分之一秒,然后如果你不能得到它就中止(例如)。

You can also call tryLock with an amount of time to wait - so you could try to acquire it for a tenth of a second, then abort if you can't get it (for example).

(我认为Java API没有 - 我很遗憾 - 据我所知 - 为内置锁定提供相同的功能,因为 Monitor 类在.NET中。然后,有很多在线程方面我不喜欢其他两个平台 - 例如,每个对象都有一个监视器!)

(I think it's a pity that the Java API doesn't - as far as I'm aware - provide the same functionality for the "built-in" locking, as the Monitor class does in .NET. Then again, there are plenty of other things I dislike in both platforms when it comes to threading - every object potentially having a monitor, for example!)

这篇关于如何确定对象是否被锁定(同步)以便不在Java中阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆