不可变对象
不可变对象需要满足的条件:1.对象创建后其状态就不能修改
2.对象所有域都是final类型
3.对象是正确创建的(在对象创建期间,this引用没有溢出)
除了final之外不可变对象的java实现
Collections.unmodifiableXXX:Collection,List,Set,Map...
Guava:ImmutableXXX:Collection,List,Set,Map...
例子:
package concurrency.example.immutable; import com.google.common.collect.Maps; import concurrency.annotations.NotThreadSafe; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.Map; /* *Created by William on 2018/4/29 0029 * final修饰变量 */ @Slf4j @NotThreadSafe public class ImmutableExample2 { private static Map<Integer, Integer> map = Maps.newHashMap(); static { map.put(1, 2); map.put(3, 4); map.put(5, 6); map = Collections.unmodifiableMap(map); } public static void main(String[] args) { map.put(1, 3); log.info("map:{}", map.get(1)); } }
使用
map = Collections.unmodifiableMap(map);
后执行会put操作会抛出异常
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1457) at concurrency.example.immutable.ImmutableExample2.main(ImmutableExample2.java:27)