我正在审查一段代码(使用 FindBugs )。
public class MyClass{
...
private BlockedQueue q = new LinkedBlockingQueue<MyData>(1000);
private static final batchSize = 1000;
public boolean testMethod(){
boolean done = false;
synchronized(q){
if(q.size == batchSize){
q.notify();
done = true;
}
}
return done;
}
当我在这段代码上运行 FindBugs 时,它提示 -
This method performs synchronization an object that is an instance of a class from the java.util.concurrent package (or its subclasses). Instances of these classes have there own concurrency control mechanisms that are distinct from and incompatible with the use of the keyword synchronized.
如果我注释掉同步代码段synchronized(q){
,它会提示 -
This method calls Object.notify() or Object.notifyAll() without obviously holding a lock on the object. Calling notify() or notifyAll() without a lock held will result in an IllegalMonitorStateException being thrown
我将如何实现此方法以使其通过 FindBugs 验证?对于并发类的情况,上述实现是否适合通知?
谢谢。
最佳答案
notify()
与 wait()
一起使用,不应该与 java.util.concurrent
的类一起使用。
BlockingQueue 使用内部机制在没有空间容纳更多元素时阻塞 put()
,或者在没有可使用的元素时阻塞 poll()
。你不必关心这个。
关于java - 在 BlockedQueue 上同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579356/