三种线程不安全现象描述(escaped state以及hidden mutable state)

hidden mutable state和escaped state是两种线程不安全问题:两者原因不同,前者主要是由于类成员变量中含有其他对象的引用,而这个引用是immutable的;后者是成员方法的返回结果类型需要注意,否者都会引起线程安全问题

1、关于hidden mutable state问题:

注意成员变量如果是另一个对象的引用情况

这个问题简而言之就是说一个类的成员变量有可能是暗含状态的,就是说成员是一个对象的引用哪个对象是有状态的,虽然这个引用可能定义为final不可变的但依然不是线程安全的!

首先说明一个类的实例  如何被多线程程序执行?

 1 public class DateFormatTest {
 2 
 3 //这里说明成员变量的初始化会在构造函数之前进行!!
 4 
 5 private final DateFormat format =new SimpleDateFormat("yyyyMMdd");
 6 
 7  
 8 
 9   public Date convert(String source) throws ParseException{
10 
11     Date d = format.parse(source);
12 
13     return d;
14 
15   }
16 
17 }// 成员变量是immutable,又不提供方法改变这个成员,这个对象是immutable?no,因为成员变量DateFormat的问题
18 
19 //定义一个对象然后被多线程共用
20 
21 final DateFormatTest t = new DateFormatTest();
22 
23 Callable<Date> task = new Callable<Date>(){
24 
25     public Date call() throws Exception {
26 
27         return t.convert("20100811");
28 
29     }
30 
31 };
32 
33 //lets try 2 threads only
34 
35 ExecutorService exec = Executors.newFixedThreadPool(2);
36 
37 List<Future<Date>> results =new ArrayList<Future<Date>>();
38 
39  
40 
41 //perform 5 date conversions
42 
43 for(int i = 0 ; i < 5 ; i++){
44 
45    results.add(exec.submit(task));
46 
47 }
48 
49 exec.shutdown();
50 
51  
52 
53 //look at the results
54 
55 for(Future<Date> result : results){
56 
57     System.out.println(result.get());
58 
59 }

1.1、说明下这个类

This code is not thread safe because SimpleDateFormat.format is not.Is this object immutable? Good question! We have done our best to make all fields not modifiable, we don't use any setter or any methods that let us suggest that the state of the object will change. Actually, internally SimpleDateFormat changes its state, and that's what makes it non-thread safe. Since something changed in the object graph, I would say that it's not immutable, even if it looks like it...

1.2、hidden mutable state问题

SimpleDateFormat 这个类的实例对象中保存有 intermediate results,所以如果一个实例对象被多个线程执行就可能会混淆彼此的执行结果。----该类有成员变量

class SimpleDateFormat{

private Calendar  calendar;

….

public void parse(){

calendar.clear();//清空

calendar.add(..);//填充

}

 

}

SimpleDateFormat stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.

Looking at the source code reveals that there is a Calendar instance field, which is used by operations on DateFormat / SimpleDateFormat

For example parse(..) calls calendar.clear() initially and then calendar.add(..). If another thread invokes parse(..) before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with (被填充)intermediate results of the calculation.

One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal - some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.

1.3、解决办法可以做thread local

Another approach is to use a ThreadLocal variable to hold the DateFormat object, which means that each thread will have its own copy and doesn't need to wait for other threads to release it. This is generally more efficient than synchronising sa in the previous approach.

public class DateFormatTest {

  private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){

    @Override

    protected DateFormat initialValue() {

        return new SimpleDateFormat("yyyyMMdd");

    }

  };

 

  public Date convert(String source) throws ParseException{

    Date d = df.get().parse(source);

    return d;

  }

}


2、关于escaped state问题:

注意函数的返回结果!!!

 1 public class Tournament {
 2 
 3 private List<Player> players = new LinkedList<Player>();
 4 
 5 public synchronized void addPlayer(Player p) {
 6 
 7 players.add(p);
 8 
 9 }
10 
11 public synchronized Iterator<Player> getPlayerIterator() {
12 
13 return players.iterator();
14 
15 }
16 
17 }

比如该类成员的所有操作都是synchronize方法做的,成员是可变的,但是也不是线程安全的!

要考虑每个方法返回的结果是否依旧可以操纵这个对象的可变状态!

问题在于:函数getPlayerIterator() 的返回结果iterator still references the mutable state contained within players—if another thread calls addPlayer() while the iterator is in use

3、类成员是一个对象,并且在该类的 synchronized方法中去掉用这个对象的方法会有隐患

如果成员方法中已经获得了锁,然后调用成员变量的方法有可能再次申请锁就会出现取得锁又申请锁,这个时候用copyonwrite数据结构

 1 class Downloader extends Thread {
 2 private InputStream in;
 3 private OutputStream out;
 4 
 5 //该类中有一个成员变量是其他对象的引用
 6 private ArrayList<ProgressListener> listeners;
 7 
 8 public synchronized void addListener(ProgressListener listener) {
 9 listeners.add(listener);
10 }
11 public synchronized void removeListener(ProgressListener listener) {
12 listeners.remove(listener);
13 }
14 
15 //这里存在隐患,因为一个synchronized方法(表示得到了一把锁),然后调用另一个对象的方法,当时你不知道这个方法中是否会再次用到锁,这里就会有隐患
16 
17 private synchronized void updateProgress(int n) {
18 for (ProgressListener listener: listeners)
19 ➤ listener.onProgress(n);
20 }
21 
22  
23 
24 。。。。。。
25 
26 }

解决方法就是得到锁的时候避免调用另一个可能获取锁的方法,做次拷贝好了!!!

修改成员方法如下:去掉成员方法的synchronized关键字,然后作clone

1 private void updateProgress(int n) {
2 ArrayList<ProgressListener> listenersCopy;
3 synchronized(this) {
4 ➤ listenersCopy = (ArrayList<ProgressListener>)listeners.clone();
5 }
6 for (ProgressListener listener: listenersCopy)
7 listener.onProgress(n);
8 }

其实java已经提供了所谓的copyonwrite集合,来应付这中情形,在做iterator集合的时候并不copy而是在修改的时候才做copy

CopyOnWrite容器即写时复制的容器。通俗的理解是当我们往一个容器添加元素的时候,不直接往当前容器添加,而是先将当前容器进行Copy,复制出一个新的容器,然后新的容器里添加元素,添加完元素之后,再将原容器的引用指向新的容器。这样做的好处是我们可以对CopyOnWrite容器进行并发的读,而不需要加锁,因为当前容器不会添加任何元素。所以CopyOnWrite容器也是一种读写分离的思想,读和写不同的容器。

http://coolshell.cn/articles/11175.html

我当记事本用的
原文地址:https://www.cnblogs.com/amazement/p/4866325.html