不可变对象(参考String类的实现)可采用的方式
1、将类声明为final(不能被继承)
2、将所有的成员声明为私有的(不能直接访问)
3、对变量不提供set方法,将所有可变的成员声明为final(只能赋值一次)
4、通过构造器初始化所有成员,进行深度拷贝
5、在get方法中不直接返回对象的本身,而是返回对象的拷贝
案例
package com.mmall.concurrency.example.immutable; import com.google.common.collect.Maps; import com.mmall.concurrency.annoations.ThreadSafe; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.Map; @Slf4j @ThreadSafe 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.get(1)); } }
package com.mmall.concurrency.example.immutable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.mmall.concurrency.annoations.ThreadSafe; @ThreadSafe public class ImmutableExample3 { private final static ImmutableList<Integer> list = 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)); } }
输出