Java併發編程 - 不可變對象

5d3faa730001683619201080.jpg (1920×1080)

不可變對象(參考String類的實現)可採用的方式

1、將類聲明爲final(不能被繼承)

 2、將所有的成員聲明爲私有的(不能直接訪問)

3、對變量不提供set方法,將所有可變的成員聲明爲final(只能賦值一次)

4、通過構造器初始化所有成員,進行深度拷貝

5、在get方法中不直接返回對象的本身,而是返回對象的拷貝

5c7a2b1e0001683619201080.jpg (1920×1080)

5ab86608000189ea19201080.jpg (1920×1080)

 

案例

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));
    }
}

輸出

5e95595e0001f3bf19201080.jpg (1920×1080)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章