gaozhangmin commented on pull request #14346:
URL: https://github.com/apache/pulsar/pull/14346#issuecomment-1044229473


   > Don't use `putIfAbsent`. Use `computeIfAbsent`.
   > 
   > For example,
   > 
   > ```java
   >     private static String newValue() {
   >         System.out.println("Call newValue");
   >         return "hello";
   >     }
   > 
   >     public static void main(String[] args) {
   >         final Map<String, String> map = new ConcurrentHashMap<>();
   >         System.out.println(map.putIfAbsent("A", newValue()));
   >         System.out.println(map.putIfAbsent("A", newValue()));
   >     }
   > ```
   > 
   > The output is:
   > 
   > ```
   > Call newValue
   > null
   > Call newValue
   > hello
   > ```
   > 
   > But if you use
   > 
   > ```java
   >         System.out.println(map.computeIfAbsent("A", __ -> newValue()));
   >         System.out.println(map.computeIfAbsent("A", __ -> newValue()));
   > ```
   > 
   > The output will be:
   > 
   > ```
   > Call newValue
   > hello
   > hello
   > ```
   > 
   > You can see `computeIfAbsent` avoids computing the value if the key 
already exists. Though the returned value is always non-null. So I suggested 
capturing an atomic boolean in the function of `computeIfAbsent` like:
   > 
   > ```java
   >         final AtomicBoolean computed = new AtomicBoolean(false);
   >         map.computeIfAbsent("A", __ -> {
   >             computed.set(true);
   >             return newValue();
   >         });
   > ```
   
   We need use putIfAbsent here , as previous logic, Only If the key is existed 
before , we register the entry.
   If We use computeIfAbsent, the return value will be previous value or 
computed value, We cannot judge if the key existed before. @BewareMyPower 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to