当我们尝试synchronized一个集合时,coverity扫描时会有提示Bad choice of lock object,那么为什么呢?
参考如下代码:
public class Test
{
public static void main(String[] args) throws Exception
{
Integer in = new Integer(12329);
Thread1 thread1 = new Thread1(in); //如果锁对象是上面是的map,则可以修改成功
Thread2 thread2 = new Thread2(in);
new Thread(thread1).start();
new Thread(thread2).start();
}
}
class Thread1 implements Runnable
{
Integer in;
public Thread1(Integer in)
{
this.in = in;
}
@Override
public void run()
{
synchronized (in)
{
try
{
System.out.println("thread1 start running...");
in.wait(6000l);
in = 32; // 这样会报错java.lang.IllegalMonitorStateException
System.out.println(in);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread2 implements Runnable
{
Integer in;
public Thread2(Integer in)
{
this.in = in;
}
@Override
public void run()
{
in = 10;
System.out.println("put finish...");
}
}
使用Integer对象报错的原因就是在锁住了Integer对象了,但是又去尝试修改这个对象。
当我们synchronized里使用一个集合对象,如Map时,参考如下代码:
public class Test
{
public static void main(String[] args) throws Exception
{
Map<String, String> map = new HashMap<String, String>();
map.put("1000", "6");
Thread1 thread1 = new Thread1(map);
Thread2 thread2 = new Thread2(map);
new Thread(thread1).start();
new Thread(thread2).start();
}
}
class Thread1 implements Runnable
{
Map<String, String> map;
public Thread1(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
synchronized (map)
{
try
{
System.out.println("thread1 start running...");
map.wait(6000l);
for (Map.Entry<String,String> entry: map.entrySet())
{
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread2 implements Runnable
{
Map<String, String> map;
public Thread2(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (int i=0 ; i < 5; i ++)
{
String key = String.valueOf(i);
String value = String.valueOf(i);
map.put(key, value);
}
System.out.println("put finish...");
}
}
使用Map的时候,可以发现,虽然synchronized了这个map,但是另一个线程可以修改map。为什么呢?
当我们使用集合时,synchronized会锁住集合的地址,如同final修饰集合或数组时,不可修改的是引用,但是集合的内容是可以修改。coverity扫描代码时,就会尽量避免这种情况,不让我们使用这种锁方式。