java高并發中不可變對象是什么,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
有一種對象一旦發布了,那么他就是安全對象,這就是不可變對象。
不可變對象需要滿足的條件:
對象創建以后其狀態就不能修改
對象所有的域都是final類型
對象是正確創建的(在對象創建期間,this引用沒有逸出)
修飾類:不能被繼承。final類中的成員變量可以根據需要設置為final,要注意的是final類中的所有成員方法都會被隱式的指定為final方法。
修飾方法:1. 鎖定方法不被繼承類修改;2. 效率
修飾變量:基本數據類型變量在初始化之后就不能修改了,引用類型變量在初始化之后便不能指向另外一個對象
下面舉例說明final修飾變量:
@Slf4j
@NotThreadSafe
public class ImmutableExample1 {
private final static Integer a = 1;
private final static String b = "2";
private final static Map<Integer, Integer> map = new HashMap<>();
static {
map.put(1, 2);
map.put(2, 3);
}
public static void main(String[] args) {
// a = 2;
// b = "3";
// map = new HashMap<>();
map.put(1, 3);
log.info("{}", map.get(1));
}
}map引用變量不可以指定新的引用,但卻可以修改里面的值。
這樣就會引發線程安全方面的問題。
除了final定義不可變對象,是否還有其他手段定義不可變對象?當然可以
Collections.unmodifiableXX: Collection、List、Set、Map......
Guava:ImmutableXXX:Collection、List、Set、Map
@Slf4j
@ThreadSafe
public class ImmutableExample2 {
private static Map<Integer, Integer> map = new HashMap<>();
static {
map.put(1, 2);
map.put(2, 3);
map = Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
map.put(1, 3);
map.put(3,4);
log.info("{}", map.get(3));
}
}這樣運行就會報錯:
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1457) at com.vincent.example.immutable.ImmutableExample2.main(ImmutableExample2.java:24)
也就是說用Collections.unmodifiableMap聲明一個變量,他的內容就不可以修改了。數據不會被污染。
@ThreadSafe
public class ImmutableExample3 {
private final static ImmutableList<Integer> list = ImmutableList.of(1,2,3);
private final static ImmutableSet<Integer> 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).build();
public static void main(String[] args) {
map2.put(4,5);
}
}根據變量實際情況變成最好變成不可變對象,如果可以盡量把對象變成不可變對象,這樣在多線程情況下就不會出現線程安全問題了。
看完上述內容,你們掌握java高并發中不可變對象是什么的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。