kafka-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ij...@apache.org
Subject [kafka] branch 2.0 updated: MINOR: Avoid coarse lock in Pool#getAndMaybePut (#5258)
Date Sat, 23 Jun 2018 23:34:22 GMT
This is an automated email from the ASF dual-hosted git repository.

ijuma pushed a commit to branch 2.0
in repository https://gitbox.apache.org/repos/asf/kafka.git


The following commit(s) were added to refs/heads/2.0 by this push:
     new a186551  MINOR: Avoid coarse lock in Pool#getAndMaybePut (#5258)
a186551 is described below

commit a186551ed590c3f5b3e7e2034837eb080525cd92
Author: Colin Patrick McCabe <colin@cmccabe.xyz>
AuthorDate: Sat Jun 23 16:33:04 2018 -0700

    MINOR: Avoid coarse lock in Pool#getAndMaybePut (#5258)
    
    Use `ConcurrentHashMap#computeIfAbsent` which relies on
    per key locks.
    
    Reviewers: Ismael Juma <ismael@juma.me.uk>
---
 core/src/main/scala/kafka/utils/Pool.scala | 20 ++++----------------
 1 file changed, 4 insertions(+), 16 deletions(-)

diff --git a/core/src/main/scala/kafka/utils/Pool.scala b/core/src/main/scala/kafka/utils/Pool.scala
index 742d3dc..5dd6194 100644
--- a/core/src/main/scala/kafka/utils/Pool.scala
+++ b/core/src/main/scala/kafka/utils/Pool.scala
@@ -27,7 +27,6 @@ import collection.JavaConverters._
 class Pool[K,V](valueFactory: Option[K => V] = None) extends Iterable[(K, V)] {
 
   private val pool: ConcurrentMap[K, V] = new ConcurrentHashMap[K, V]
-  private val createLock = new Object
   
   def put(k: K, v: V): V = pool.put(k, v)
   
@@ -57,21 +56,10 @@ class Pool[K,V](valueFactory: Option[K => V] = None) extends Iterable[(K,
V)] {
     * @param createValue Factory function.
     * @return The final value associated with the key.
     */
-  def getAndMaybePut(key: K, createValue: => V): V = {
-    val current = pool.get(key)
-    if (current == null) {
-      createLock synchronized {
-        val current = pool.get(key)
-        if (current == null) {
-          val value = createValue
-          pool.put(key, value)
-          value
-        }
-        else current
-      }
-    }
-    else current
-  }
+  def getAndMaybePut(key: K, createValue: => V): V =
+    pool.computeIfAbsent(key, new java.util.function.Function[K, V] {
+      override def apply(k: K): V = createValue
+    })
 
   def contains(id: K): Boolean = pool.containsKey(id)
   


Mime
View raw message