Collections.synchronizedCollection(Collection<T> c)--如何保证线程安全
来源:互联网 发布:mac lrc歌词制作软件 编辑:程序博客网 时间:2024/06/14 22:19
1.调用静态方法
public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
return new SynchronizedCollection<>(c);
}
2.初始化静态内部类SynchronizedCollection
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 3053995032091335093L;
final Collection<E> c; // Backing Collection
final Object mutex; // Object on which to synchronize
SynchronizedCollection(Collection<E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
mutex = this;
}
SynchronizedCollection(Collection<E> c, Object mutex) {
this.c = c;
this.mutex = mutex;
}
public int size() {
synchronized (mutex) {return c.size();}
}
public boolean isEmpty() {
synchronized (mutex) {return c.isEmpty();}
}
public boolean contains(Object o) {
synchronized (mutex) {return c.contains(o);}
}
......
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
public boolean add(E e) {
synchronized (mutex) {return c.add(e);}
}
public boolean remove(Object o) {
synchronized (mutex) {return c.remove(o);}
}
......
}
备注:内部类重写集合的所有方法,通过获得mutex的锁保证线程安全
唯一没有synchronized 代码块的是遍历方法,需要用户自己同步Must be manually synched by user!
细节:所有同步都是在方法内部,如果在所有方法上同步,只要该对象调用其中一个方法,就会拿到当前对象的锁,
该对象调用其他的方法只能阻塞,等待其释放锁,而在方法内部添加代码块可以有效避免此问题。
- Collections.synchronizedCollection(Collection<T> c)--如何保证线程安全
- 用Collections.synchronizedCollection创建线程安全的集合、列表...
- Collections.synchronizedCollection
- 如何保证线程安全?
- 什么是线程安全?如何保证线程安全?
- 如何保证Java线程安全
- 如何保证ArrayList线程安全
- java如何保证线程安全
- 如何使用concurrent保证线程安全
- 关于ThreadLocal如何保证数据线程安全
- 多线程中如何去保证线程安全
- 线程安全的理解和如何保证线程安全
- Servelt是否线程安全以及如何保证线程安全
- java基础—如何创建线程?如何保证线程安全?
- Collections Collections.synchronizedCollection 集合的同步控制
- iOS 保证线程安全
- 线程安全Collections.synchronizedList
- 线程安全Collections.synchronizedList
- js
- docker exec 报错 Unsupported: Exec is not supported by the lxc driver
- 文章标题
- 查看监听端口的进程
- ArcGIS教程:将标题和总览图页添加到地图册
- Collections.synchronizedCollection(Collection<T> c)--如何保证线程安全
- Climbing Stairs
- 请求筛选模块被配置为拒绝包含的查询字符串过长的请求。
- 19、LVS+keepalived
- App Store审核条款(2016.06.21更新)
- C++ 高级数据类型(三)—— 指针
- CDockablePane使用心得
- php实现畅言留言板和网易跟帖样式
- Openstack Mitaka