java - 在 BlockedQueue 上同步

标签 java multithreading concurrency findbugs synchronized

我正在审查一段代码(使用 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/

相关文章:

java - 使用 Java Redis 客户端连接到 Amazon ElastiCache (Lettuce)

java - Swing - 更改 LayoutManager : two components per line

node.js - 在 PostgreSQL 中重新启动失败的事务

java : "If user does not input X, Y, Z, do this"

java - UTF-8 编码问题特殊字符如 'É' 未正确复制

java - 如何实现单个函数以在 AsyncTask 之后返回数据,或者如果之前已缓存则同步返回数据?

c# - 并行化/多线程单例对象方法调用

java - 线程上可运行对象的受监督调用

java - 如何同步处理Java "jobs"?

python - 检查现有进程是否存在 - 如果存在,则与其通信,否则创建一个新进程