You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "ASF GitHub Bot (JIRA)" <ji...@apache.org> on 2018/01/30 18:22:00 UTC

[jira] [Commented] (KAFKA-6345) NetworkClient.inFlightRequestCount() is not thread safe, causing ConcurrentModificationExceptions when sensors are read

    [ https://issues.apache.org/jira/browse/KAFKA-6345?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16345558#comment-16345558 ] 

ASF GitHub Bot commented on KAFKA-6345:
---------------------------------------

becketqin closed pull request #4460: KAFKA-6345: Keep a separate count of in-flight requests to avoid ConcurrentModificationException.
URL: https://github.com/apache/kafka/pull/4460
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java b/clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java
index 3689a09a117..a062818e3b2 100644
--- a/clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java
+++ b/clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java
@@ -23,6 +23,8 @@
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
 
 /**
  * The set of requests which have been sent or are being sent but haven't yet received a response
@@ -31,6 +33,8 @@
 
     private final int maxInFlightRequestsPerConnection;
     private final Map<String, Deque<NetworkClient.InFlightRequest>> requests = new HashMap<>();
+    /** Thread safe total number of in flight requests. */
+    private final AtomicInteger inFlightRequestCount = new AtomicInteger(0);
 
     public InFlightRequests(int maxInFlightRequestsPerConnection) {
         this.maxInFlightRequestsPerConnection = maxInFlightRequestsPerConnection;
@@ -47,6 +51,7 @@ public void add(NetworkClient.InFlightRequest request) {
             this.requests.put(destination, reqs);
         }
         reqs.addFirst(request);
+        inFlightRequestCount.incrementAndGet();
     }
 
     /**
@@ -63,7 +68,9 @@ public void add(NetworkClient.InFlightRequest request) {
      * Get the oldest request (the one that will be completed next) for the given node
      */
     public NetworkClient.InFlightRequest completeNext(String node) {
-        return requestQueue(node).pollLast();
+        NetworkClient.InFlightRequest inFlightRequest = requestQueue(node).pollLast();
+        inFlightRequestCount.decrementAndGet();
+        return inFlightRequest;
     }
 
     /**
@@ -80,7 +87,9 @@ public void add(NetworkClient.InFlightRequest request) {
      * @return The request
      */
     public NetworkClient.InFlightRequest completeLastSent(String node) {
-        return requestQueue(node).pollFirst();
+        NetworkClient.InFlightRequest inFlightRequest = requestQueue(node).pollFirst();
+        inFlightRequestCount.decrementAndGet();
+        return inFlightRequest;
     }
 
     /**
@@ -114,13 +123,10 @@ public boolean isEmpty(String node) {
     }
 
     /**
-     * Count all in-flight requests for all nodes
+     * Count all in-flight requests for all nodes. This method is thread safe, but may lag the actual count.
      */
     public int count() {
-        int total = 0;
-        for (Deque<NetworkClient.InFlightRequest> deque : this.requests.values())
-            total += deque.size();
-        return total;
+        return inFlightRequestCount.get();
     }
 
     /**
@@ -141,8 +147,14 @@ public boolean isEmpty() {
      * @return All the in-flight requests for that node that have been removed
      */
     public Iterable<NetworkClient.InFlightRequest> clearAll(String node) {
-        Deque<NetworkClient.InFlightRequest> reqs = requests.remove(node);
-        return (reqs == null) ? Collections.<NetworkClient.InFlightRequest>emptyList() : reqs;
+        Deque<NetworkClient.InFlightRequest> reqs = requests.get(node);
+        if (reqs == null) {
+            return Collections.emptyList();
+        } else {
+            Deque<NetworkClient.InFlightRequest> clearedRequests = requests.remove(node);
+            inFlightRequestCount.getAndAdd(-clearedRequests.size());
+            return clearedRequests;
+        }
     }
 
     /**
diff --git a/clients/src/test/java/org/apache/kafka/clients/InFlightRequestsTest.java b/clients/src/test/java/org/apache/kafka/clients/InFlightRequestsTest.java
new file mode 100644
index 00000000000..e00ca086106
--- /dev/null
+++ b/clients/src/test/java/org/apache/kafka/clients/InFlightRequestsTest.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.clients;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class InFlightRequestsTest {
+
+    private InFlightRequests inFlightRequests;
+    @Before
+    public void setup() {
+        inFlightRequests = new InFlightRequests(12);
+        NetworkClient.InFlightRequest ifr =
+                new NetworkClient.InFlightRequest(null, 0, "dest", null, false, false, null, null, 0);
+        inFlightRequests.add(ifr);
+    }
+
+    @Test
+    public void checkIncrementAndDecrementOnLastSent() {
+        assertEquals(1, inFlightRequests.count());
+
+        inFlightRequests.completeLastSent("dest");
+        assertEquals(0, inFlightRequests.count());
+    }
+
+    @Test
+    public void checkDecrementOnClear() {
+        inFlightRequests.clearAll("dest");
+        assertEquals(0, inFlightRequests.count());
+    }
+
+    @Test
+    public void checkDecrementOnCompleteNext() {
+        inFlightRequests.completeNext("dest");
+        assertEquals(0, inFlightRequests.count());
+    }
+
+    @Test(expected = IllegalStateException.class)
+    public void throwExceptionOnNeverBeforeSeenNode() {
+        inFlightRequests.completeNext("not-added");
+    }
+}


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


> NetworkClient.inFlightRequestCount() is not thread safe, causing ConcurrentModificationExceptions when sensors are read
> -----------------------------------------------------------------------------------------------------------------------
>
>                 Key: KAFKA-6345
>                 URL: https://issues.apache.org/jira/browse/KAFKA-6345
>             Project: Kafka
>          Issue Type: Bug
>          Components: clients
>    Affects Versions: 1.0.0
>            Reporter: radai rosenblatt
>            Priority: Major
>
> example stack trace (code is ~0.10.2.*)
> {code}
> java.util.ConcurrentModificationException: java.util.ConcurrentModificationException
> 	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
> 	at java.util.HashMap$ValueIterator.next(HashMap.java:1458)
> 	at org.apache.kafka.clients.InFlightRequests.inFlightRequestCount(InFlightRequests.java:109)
> 	at org.apache.kafka.clients.NetworkClient.inFlightRequestCount(NetworkClient.java:382)
> 	at org.apache.kafka.clients.producer.internals.Sender$SenderMetrics$1.measure(Sender.java:480)
> 	at org.apache.kafka.common.metrics.KafkaMetric.value(KafkaMetric.java:61)
> 	at org.apache.kafka.common.metrics.KafkaMetric.value(KafkaMetric.java:52)
> 	at org.apache.kafka.common.metrics.JmxReporter$KafkaMbean.getAttribute(JmxReporter.java:183)
> 	at org.apache.kafka.common.metrics.JmxReporter$KafkaMbean.getAttributes(JmxReporter.java:193)
> 	at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttributes(DefaultMBeanServerInterceptor.java:709)
> 	at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttributes(JmxMBeanServer.java:705)
> {code}
> looking at latest trunk, the code is still vulnerable:
> # NetworkClient.inFlightRequestCount() eventually iterates over InFlightRequests.requests.values(), which is backed by a (non-thread-safe) HashMap
> # this will be called from the "requests-in-flight" sensor's measure() method (Sender.java line  ~765 in SenderMetrics ctr), which would be driven by some thread reading JMX values
> # HashMap in question would also be updated by some client io thread calling NetworkClient.doSend() - which calls into InFlightRequests.add())
> i guess the only upside is that this exception will always happen on the thread reading the JMX values and never on the actual client io thread ...



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)