由线程共享的ReentrantLock似乎不尊重锁定

时间:2013-12-24 19:26:54

标签: java multithreading locking reentrantlock

我有一个我在线程之间共享的ReentrantLock对象,但是我能够通过不同的线程锁定同一个对象。这似乎不对,因为它们是不同的线程。这是截断/简化的输出:

11:04:47,136 [http-bio-8080-exec-9] INFO  CamTask  - ABOUT TO LOCK..... java.util.concurrent.locks.ReentrantLock@4462cf1d[Unlocked] -- 0
11:04:47,136 [http-bio-8080-exec-9] INFO  CamTask  - GOT LOCK java.util.concurrent.locks.ReentrantLock@4462cf1d[Locked by thread http-bio-8080-exec-9] -- 1
// ...     //
11:04:48,244 [Camel thread #1] INFO  MyProcessor  - ABOUT TO LOCK... java.util.concurrent.locks.ReentrantLock@4462cf1d[Unlocked] -- 0
11:04:48,245 [Camel thread #1] INFO  MyProcessor  - GOT LOCK java.util.concurrent.locks.ReentrantLock@4462cf1d[Locked by thread Camel thread #1] -- 1
// ...     //
11:04:48,280 [Camel thread #1] INFO  MyProcessor  - ABOUT TO UNLOCK.. java.util.concurrent.locks.ReentrantLock@4462cf1d[Locked by thread Camel thread #1] -- 1
11:04:48,280 [Camel thread #1] INFO  MyProcessor  - UNLOCKED. java.util.concurrent.locks.ReentrantLock@4462cf1d[Unlocked] -- 0
// ...     //
11:04:48,284 [http-bio-8080-exec-9] INFO  CamTask  - ABOUT TO UNLOCK..... java.util.concurrent.locks.ReentrantLock@4462cf1d[Locked by thread http-bio-8080-exec-9] -- 1
11:04:48,284 [http-bio-8080-exec-9] INFO  CamTask  - UNLOCKED. java.util.concurrent.locks.ReentrantLock@4462cf1d[Unlocked] -- 0

我的日志记录结构如下:

log.info("ABOUT TO LOCK.. "+lock+" -- "+lock.getHoldCount());
lock.lock();
log.info("GOT LOCK "+lock+" -- "+lock.getHoldCount());

如你所见:

  1. [http-bio-8080-exec-9]锁定(按预期锁定后保持计数为0然后为1)
  2. [Camel thread#1]锁定(为什么这可能是因为[http-bio-8080-exec-9]没有被解锁?
  3. MyProcessor作为消息到达队列的结果被调用。 lock对象在其构造函数中传递给MyProcessor。当我在上面的日志中打印出锁定对象时,您可以看到它是相同的对象(具有相同的引用ID)。

    有什么想法吗?

    谢谢!

1 个答案:

答案 0 :(得分:0)

感谢大家的评论。根据异步日志记录和日志记录顺序的建议,我添加了一些睡眠来查找。添加睡眠后,锁定会按预期等待,所以我认为日志记录只是乱序。