java中lockprocess,如何确定对象是否被锁定(同步)以便不在Java中阻塞?

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

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).

Currently I do something like this:

synchronized(record)

{

performOperation(record);

}

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,

解决方案

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 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

}

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).

(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!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值