[JCIP笔记](五)JDK并发包

这一节来讲一讲java.util.concurrent这个包里的一些重要的线程安全有关类。

synchronized容器

synchronized容器就是把自己的内部状态封装起来,通过把每一个public方法设置成同步来控制对共享变量的访问的容器。主要包括Vector, Hashtable,以及Collections.synchronizedxxx()方法提供的wrapper。

synchronized容器的问题-client locking

首先,synchronzied容器虽然是线程安全的,但是要访问容器内部数据的线程只能先拿到容器的内置锁才能访问,实际上相当于串行访问,CPU利用率和效率都不高。
另外还有一个值得注意的地方,就是用户代码使用synchronized容器时,如果需要做一些复合操作,比如put-if-absent,仍然要显式加锁(称为client locking),否则会产生race condition。
比如以下操作:

1 public Object getLast(Vector list){ 2   int last = list.size() - 1; //1 3   return list.get(last); //2 4 } 5 public void removeLast(Vector list){ 6   int last = list.size() - 1; //3 7   list.remove(last); //4 8 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgzsxf.html