一、初識computeIfAbsent
Java 8中的ConcurrentHashMap提供了一個能夠將計算與緩存相結合的方法:computeIfAbsent。使用computeIfAbsent方法能夠避免在多線程的情況下重複計算,提高程序的執行效率。
ConcurrentHashMap map = new ConcurrentHashMap(); map.computeIfAbsent("apple", key -> key.length()); System.out.println(map.get("apple")); //輸出5
二、computeIfAbsent的函數式編程風格
作為Java 8的新特性,computeIfAbsent方法的函數式編程風格大大提高了開發效率。我們可以使用lambda表達式來編寫計算邏輯,從而不需要再編寫大量的邏輯代碼。
ConcurrentHashMap map = new ConcurrentHashMap(); map.computeIfAbsent("apple", key -> { int length = key.length(); return length; }); System.out.println(map.get("apple")); //輸出5
三、computeIfAbsent方法避免多線程重複計算
在多線程的情況下,computeIfAbsent方法可以避免重複計算,能夠提高程序的執行效率。例如:
ConcurrentHashMap map = new ConcurrentHashMap(); ExecutorService executor = Executors.newFixedThreadPool(10); for(int i=0; i { map.computeIfAbsent("apple", key -> { int length = key.length(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } return length; }); }); } executor.shutdown(); while(!executor.isTerminated()) {} System.out.println(map.get("apple")); //輸出5
在上面的例子中,我們使用10個線程來向map中插入100000個元素,每個元素都要執行10ms的等待時間。當我們使用computeIfAbsent方法時,每個元素只需要進行一次計算,因為多個線程之間共享同一個map對象。如果使用傳統的方式,每個線程都會重複計算,造成大量的資源浪費。
四、computeIfAbsent的性能優化
對於一些耗時較長的操作,我們可以使用ConcurrentHashMap的compute方法來完成計算,從而提高程序的性能。
ConcurrentHashMap map = new ConcurrentHashMap(); map.compute("apple", (key, value) -> { if(value == null) { int length = key.length(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } return length; } else { return value; } }); System.out.println(map.get("apple")); //輸出5
在上面的例子中,我們使用了compute方法來進行元素的計算。如果元素存在,則直接返回值,否則進行計算並插入map中。使用compute方法能夠減少一些不必要的判斷和操作,提高程序的性能。
五、computeIfAbsent對於非ConcurrentHashMap的應用
雖然computeIfAbsent方法是由ConcurrentHashMap提供的,但是我們也可以使用它來對其他類的操作進行優化。
Map map = new HashMap(); map.computeIfAbsent("apple", key -> key.length()); System.out.println(map.get("apple")); //輸出5
雖然HashMap不是線程安全的容器,但是由於computeIfAbsent方法的特殊性質,我們依然可以使用它來對map中的元素進行計算和緩存。
原創文章,作者:CZPHH,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/334140.html