什么“不一致同步"方法? [英] What "inconsistent synchronization" means?

查看:44
本文介绍了什么“不一致同步"方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Java 1.6 类:

This is my Java 1.6 class:

public class Foo {
  private ArrayList<String> names;
  public void scan() {
    if (names == null) {
      synchronized (this) {
        this.names = new ArrayList<String>();
        // fill the array with data
      }
    }
  }
}

Findbugs 说:

Findbugs says:

Inconsistent synchronization of com.XXX.Foo.names; locked 40% of time

这是什么意思,我做错了什么?当两个或多个客户端同时调用 Foo.scan() 时,我试图避免出现问题.

What does it mean and what I'm doing wrong? I'm trying to avoid problems when two or more clients call Foo.scan() at the same time.

推荐答案

这是因为您只在设置 names 变量时同步,而不是在读取它时同步.因此,在读取和写入之间,另一个线程可以执行,您将创建两个 ArrayList 并用数据填充它们,创建的第一个将被 GC 处理.

It's beacuse you are only synchronizing when you set the names variable and not when you read it. So between the read and the write another thread could execute and you'd create two ArrayLists and fill them with data, the first one created would get GC'ed.

您需要在读取和写入周围放置同步块或在方法中添加同步修饰符.

You need to put the synchronized block around the read and the write or add the synchronized modifier to the method.

public class Foo {
  private ArrayList<String> names;
    public void scan() {
      synchronized (this)
        if (names == null) {
           this.names = new ArrayList<String>();
           // fill the array with data
         }
       }
     }
  }

这篇关于什么“不一致同步"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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