【Java】Java线程安全策略
线程安全策略
不可变对象需要满足的条件
- 对象创建以后其状态就不能修改。
- 对象的所有域都是fina类型。
- 对象是正确创建的(在对象创建期间,this引用没有逸出)
final
- 修饰类
- 修饰方法
- 修饰变量
//线程不安全package com.rumenz.task.single;
import com.google.common.collect.Maps;
import java.util.Map;
public class ImmutableExample1 {
private final static Integer a=1;
private final static Integer b=2;
//指向的引用不能被修改,但是map里面的值可以修改
private final static Map<Integer,Integer> map= Maps.newHashMap();
static {
map.put(1, 1);
}
public static void main(String[] args) {
//a=10; 编译期报错
//b=20; 编译期报错
map.put(2, 2); //线程不安全
}
}
Collections
//线程安全package com.rumenz.task.single;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
public class ImmutableExample1 {
private final static Integer a=1;
private final static Integer b=2;
//指向的引用不能被修改,但是map里面的值可以修改
private static Map<Integer,Integer> map= Maps.newHashMap();
static {
map.put(1, 1);
//处理后map是不可以被修改的
map= Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
//允许操作,但是操作会报错
map.put(2, 2);
}
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at com.rumenz.task.single.ImmutableExample1.main(ImmutableExample1.java:31)
Collections.unmodifiableMap
源码
public class Collections {public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
return new UnmodifiableMap<>(m);
}
private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
throw new UnsupportedOperationException();
}
}
}
Guava
<dependency><groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
//线程安全public class ImmutableExample3 {
private final static ImmutableList<Integer> list = ImmutableList.of(1, 2, 3);
private final static List<Integer> lists = ImmutableList.of(1, 2, 3);
private final static ImmutableSet set = ImmutableSet.copyOf(list);
private final static ImmutableMap<Integer, Integer> map = ImmutableMap.of(1, 2, 3, 4);
private final static ImmutableMap<Integer, Integer> map2 = ImmutableMap.<Integer, Integer>builder()
.put(1, 2).put(3, 4).put(5, 6).build();
public static void main(String[] args) {
System.out.println(map2.get(3));
}
}
以上是 【Java】Java线程安全策略 的全部内容, 来源链接: utcz.com/a/94135.html