You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by si...@apache.org on 2019/03/08 11:07:02 UTC

[pulsar] branch master updated: [pulsar-broker] Optimize redelivery message reading (#3732)

This is an automated email from the ASF dual-hosted git repository.

sijie pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/master by this push:
     new 4ce8b32  [pulsar-broker] Optimize redelivery message reading (#3732)
4ce8b32 is described below

commit 4ce8b32f8425c7af559acf766038048655199444
Author: Rajan Dhabalia <rd...@apache.org>
AuthorDate: Fri Mar 8 03:06:56 2019 -0800

    [pulsar-broker] Optimize redelivery message reading (#3732)
    
    ### Motivation
    It address #3731.
    
    ### Modification
    - Introduce `ConcurrentSortedLongPairSet` that helps broker to avoid random read across multiple managed-ledgers. It still uses `ConcurrentLongPairSet` to avoid object allocation for message-ids.
    - introduce `<T> Set<T> items(int numberOfItems, BiFunction<Long, Long, T> longPairConverter)` method  in `LongPairSet` to avoid creating temporary [LongPair](https://github.com/apache/pulsar/blob/master/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java#L291) objects.
    - this change will not impact to normal usecase where topic doesn't have backlog and doesn't have many active managed-ledgers.
    
    ### Note
    I have done performance testing on `GrowablePriorityLongPairQueue` which I had introduced sometime back but its insert/remove is super slow and CPU intensive so, we can't use it in this scenario.
---
 .../PersistentDispatcherMultipleConsumers.java     |  16 +-
 .../pulsar/client/api/ConsumerRedeliveryTest.java  | 125 +++++++++++
 .../util/collections/ConcurrentLongPairSet.java    |  21 +-
 .../collections/ConcurrentSortedLongPairSet.java   | 206 +++++++++++++++++
 .../common/util/collections/LongPairSet.java       | 144 ++++++++++++
 .../ConcurrentSortedLongPairSetTest.java           | 244 +++++++++++++++++++++
 .../GrowablePriorityLongPairQueueTest.java         |   4 +-
 7 files changed, 743 insertions(+), 17 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
index e1ff3ea..02c3ea8 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentDispatcherMultipleConsumers.java
@@ -18,7 +18,6 @@
  */
 package org.apache.pulsar.broker.service.persistent;
 
-import static java.util.stream.Collectors.toSet;
 import static org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES;
 import static org.apache.pulsar.broker.service.persistent.PersistentTopic.MESSAGE_RATE_BACKOFF_MS;
 
@@ -53,7 +52,8 @@ import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType;
 import org.apache.pulsar.common.naming.TopicName;
 import org.apache.pulsar.common.policies.data.Policies;
 import org.apache.pulsar.common.util.Codec;
-import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet;
+import org.apache.pulsar.common.util.collections.ConcurrentSortedLongPairSet;
+import org.apache.pulsar.common.util.collections.LongPairSet;
 import org.apache.pulsar.utils.CopyOnWriteArrayList;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -72,7 +72,7 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
     private final ManagedCursor cursor;
 
     private CompletableFuture<Void> closeFuture = null;
-    private ConcurrentLongPairSet messagesToReplay;
+    LongPairSet messagesToReplay = new ConcurrentSortedLongPairSet(128, 2);
     private final RedeliveryTracker redeliveryTracker;
 
     private boolean havePendingRead = false;
@@ -102,7 +102,6 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
         this.cursor = cursor;
         this.name = topic.getName() + " / " + Codec.decode(cursor.getName());
         this.topic = topic;
-        this.messagesToReplay = new ConcurrentLongPairSet(512, 2);
         this.redeliveryTracker = this.serviceConfig.isSubscriptionRedeliveryTrackerEnabled()
                 ? new InMemoryRedeliveryTracker()
                 : RedeliveryTrackerDisabled.REDELIVERY_TRACKER_DISABLED;
@@ -288,8 +287,8 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
                     return;
                 }
 
-                Set<PositionImpl> messagesToReplayNow = messagesToReplay.items(messagesToRead).stream()
-                        .map(pair -> new PositionImpl(pair.first, pair.second)).collect(toSet());
+                Set<PositionImpl> messagesToReplayNow = messagesToReplay.items(messagesToRead,
+                        (ledgerId, entryId) -> new PositionImpl(ledgerId, entryId));
 
                 if (log.isDebugEnabled()) {
                     log.debug("[{}] Schedule replay of {} messages for {} consumers", name, messagesToReplayNow.size(),
@@ -329,6 +328,7 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
         }
     }
 
+
     @Override
     public boolean isConsumerConnected() {
         return !consumerList.isEmpty();
@@ -503,6 +503,7 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
             havePendingReplayRead = false;
             if (exception instanceof ManagedLedgerException.InvalidReplayPositionException) {
                 PositionImpl markDeletePosition = (PositionImpl) cursor.getMarkDeletedPosition();
+
                 messagesToReplay.removeIf((ledgerId, entryId) -> {
                     return ComparisonChain.start().compare(ledgerId, markDeletePosition.getLedgerId())
                             .compare(entryId, markDeletePosition.getEntryId()).result() <= 0;
@@ -555,7 +556,8 @@ public class PersistentDispatcherMultipleConsumers  extends AbstractDispatcherMu
             messagesToReplay.add(ledgerId, entryId);
         });
         if (log.isDebugEnabled()) {
-            log.debug("[{}-{}] Redelivering unacknowledged messages for consumer {}", name, consumer, messagesToReplay);
+            log.debug("[{}-{}] Redelivering unacknowledged messages for consumer {}", name, consumer,
+                    messagesToReplay);
         }
         readMoreEntries();
     }
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ConsumerRedeliveryTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ConsumerRedeliveryTest.java
new file mode 100644
index 0000000..fc05d98
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ConsumerRedeliveryTest.java
@@ -0,0 +1,125 @@
+/**
+ * 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.pulsar.client.api;
+
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.pulsar.client.impl.ConsumerImpl;
+import org.apache.pulsar.client.impl.MessageIdImpl;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.Sets;
+
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.assertEquals;
+
+public class ConsumerRedeliveryTest extends ProducerConsumerBase {
+    @BeforeClass
+    @Override
+    protected void setup() throws Exception {
+        super.internalSetup();
+        super.producerBaseSetup();
+    }
+
+    @AfterClass
+    @Override
+    protected void cleanup() throws Exception {
+        super.internalCleanup();
+    }
+
+    /**
+     * It verifies that redelivered messages are sorted based on the ledger-ids.
+     * <pre>
+     * 1. client publishes 100 messages across 50 ledgers
+     * 2. broker deliveres 100 messages to consumer
+     * 3. consumer ack every alternative message and doesn't ack 50 messsages
+     * 4. broker sorts replay messages based on ledger and redelivers messages ledger by ledger
+     * </pre>
+     * @throws Exception
+     */
+    @Test
+    public void testOrderedRedelivery() throws Exception {
+        String topic = "persistent://my-property/my-ns/redelivery";
+
+        conf.setManagedLedgerMaxEntriesPerLedger(2);
+        conf.setManagedLedgerMinLedgerRolloverTimeMinutes(0);
+        
+        ProducerBuilder<byte[]> producerBuilder = pulsarClient.newProducer().topic(topic)
+                .producerName("my-producer-name");
+        Producer<byte[]> producer = producerBuilder.create();
+        ConsumerBuilder<byte[]> consumerBuilder = pulsarClient.newConsumer().topic(topic).subscriptionName("s1")
+                .subscriptionType(SubscriptionType.Shared);
+        ConsumerImpl<byte[]> consumer1 = (ConsumerImpl<byte[]>) consumerBuilder.subscribe();
+
+        final int totalMsgs = 100;
+
+        for (int i = 0; i < totalMsgs; i++) {
+            String message = "my-message-" + i;
+            producer.send(message.getBytes());
+        }
+
+
+        int consumedCount = 0;
+        Set<MessageId> messageIds = Sets.newHashSet();
+        for (int i = 0; i < totalMsgs; i++) {
+            Message<byte[]> message = consumer1.receive(5, TimeUnit.SECONDS);
+            if (message != null && (consumedCount % 2) == 0) {
+                consumer1.acknowledge(message);
+            } else {
+                messageIds.add(message.getMessageId());
+            }
+            consumedCount += 1;
+        }
+        assertEquals(totalMsgs, consumedCount);
+
+        // redeliver all unack messages
+        consumer1.redeliverUnacknowledgedMessages(messageIds);
+
+        MessageIdImpl lastMsgId = null;
+        for (int i = 0; i < totalMsgs / 2; i++) {
+            Message<byte[]> message = consumer1.receive(5, TimeUnit.SECONDS);
+            MessageIdImpl msgId = (MessageIdImpl) message.getMessageId();
+            if (lastMsgId != null) {
+                assertTrue(lastMsgId.getLedgerId() <= msgId.getLedgerId());
+            }
+            lastMsgId = msgId;
+        }
+
+        // close consumer so, this consumer's unack messages will be redelivered to new consumer
+        consumer1.close();
+
+        Consumer<byte[]> consumer2 = consumerBuilder.subscribe();
+        lastMsgId = null;
+        for (int i = 0; i < totalMsgs / 2; i++) {
+            Message<byte[]> message = consumer2.receive(5, TimeUnit.SECONDS);
+            MessageIdImpl msgId = (MessageIdImpl) message.getMessageId();
+            if (lastMsgId != null) {
+                assertTrue(lastMsgId.getLedgerId() <= msgId.getLedgerId());
+            }
+            lastMsgId = msgId;
+        }
+
+        producer.close();
+        consumer2.close();
+    }
+
+}
diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSet.java b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSet.java
index 4634b40..e10e00f 100644
--- a/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSet.java
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSet.java
@@ -26,6 +26,9 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.StampedLock;
+import java.util.function.BiFunction;
+
+import org.apache.pulsar.common.util.collections.LongPairSet.LongPairFunction;
 
 /**
  * Concurrent hash set where values are composed of pairs of longs.
@@ -38,7 +41,7 @@ import java.util.concurrent.locks.StampedLock;
  * <p>
  * Values <strong>MUST</strong> be >= 0.
  */
-public class ConcurrentLongPairSet {
+public class ConcurrentLongPairSet implements LongPairSet {
 
     private static final long EmptyItem = -1L;
     private static final long DeletedItem = -2L;
@@ -54,10 +57,6 @@ public class ConcurrentLongPairSet {
         void accept(LongPair item);
     }
 
-    public interface LongPairPredicate {
-        boolean test(long v1, long v2);
-    }
-
     public static interface LongPairConsumer {
         void accept(long v1, long v2);
     }
@@ -190,11 +189,16 @@ public class ConcurrentLongPairSet {
      * @return a new list of keys with max provided numberOfItems (makes a copy)
      */
     public Set<LongPair> items(int numberOfItems) {
-        Set<LongPair> items = new HashSet<>();
+        return items(numberOfItems, (item1, item2) -> new LongPair(item1, item2));
+    }
+
+    @Override
+    public <T> Set<T> items(int numberOfItems, LongPairFunction<T> longPairConverter) {
+        Set<T> items = new HashSet<>();
         for (Section s : sections) {
             s.forEach((item1, item2) -> {
                 if (items.size() < numberOfItems) {
-                    items.add(new LongPair(item1, item2));
+                    items.add(longPairConverter.apply(item1, item2));
                 }
             });
             if (items.size() >= numberOfItems) {
@@ -203,7 +207,7 @@ public class ConcurrentLongPairSet {
         }
         return items;
     }
-
+    
     // A section is a portion of the hash map that is covered by a single
     @SuppressWarnings("serial")
     private static final class Section extends StampedLock {
@@ -552,4 +556,5 @@ public class ConcurrentLongPairSet {
         sb.append('}');
         return sb.toString();
     }
+
 }
diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSet.java b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSet.java
new file mode 100644
index 0000000..12c595c
--- /dev/null
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSet.java
@@ -0,0 +1,206 @@
+/**
+ * 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.pulsar.common.util.collections;
+
+import java.util.NavigableMap;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPair;
+import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPairConsumer;
+
+/**
+ * Sorted concurrent {@link LongPairSet} which is not fully accurate in sorting.
+ * 
+ * {@link ConcurrentSortedLongPairSet} creates separate {@link ConcurrentLongPairSet} for unique first-key of
+ * inserted item. So, it can iterate over all items by sorting on item's first key. However, item's second key will not
+ * be sorted. eg:
+ * 
+ * <pre>
+ *  insert: (1,2), (1,4), (2,1), (1,5), (2,6)
+ *  while iterating set will first read all the entries for items whose first-key=1 and then first-key=2.
+ *  output: (1,4), (1,5), (1,2), (2,6), (2,1)
+ * </pre>
+ * 
+ * This map can be expensive and not recommended if set has to store large number of unique item.first's key because set
+ * has to create that many {@link ConcurrentLongPairSet} objects
+ *
+ */
+public class ConcurrentSortedLongPairSet implements LongPairSet {
+
+    protected final NavigableMap<Long, ConcurrentLongPairSet> longPairSets = new ConcurrentSkipListMap<>();
+    private int expectedItems;
+    private int concurrencyLevel;
+    /**
+     * If {@link #longPairSets} adds and removes the item-set frequently then it allocates and removes
+     * {@link ConcurrentLongPairSet} for the same item multiple times which can lead to gc-puases. To avoid such
+     * situation, avoid removing empty LogPairSet until it reaches max limit.
+     */
+    private int maxAllowedSetOnRemove;
+    private static final int DEFAULT_MAX_ALLOWED_SET_ON_REMOVE = 10;
+
+    public ConcurrentSortedLongPairSet() {
+        this(16, 1, DEFAULT_MAX_ALLOWED_SET_ON_REMOVE);
+    }
+
+    public ConcurrentSortedLongPairSet(int expectedItems) {
+        this(expectedItems, 1, DEFAULT_MAX_ALLOWED_SET_ON_REMOVE);
+    }
+
+    public ConcurrentSortedLongPairSet(int expectedItems, int concurrencyLevel) {
+        this(expectedItems, concurrencyLevel, DEFAULT_MAX_ALLOWED_SET_ON_REMOVE);
+    }
+
+    public ConcurrentSortedLongPairSet(int expectedItems, int concurrencyLevel, int maxAllowedSetOnRemove) {
+        this.expectedItems = expectedItems;
+        this.concurrencyLevel = concurrencyLevel;
+        this.maxAllowedSetOnRemove = maxAllowedSetOnRemove;
+    }
+
+    @Override
+    public boolean add(long item1, long item2) {
+        ConcurrentLongPairSet messagesToReplay = longPairSets.computeIfAbsent(item1,
+                (key) -> new ConcurrentLongPairSet(expectedItems, concurrencyLevel));
+        return messagesToReplay.add(item1, item2);
+    }
+
+    @Override
+    public boolean remove(long item1, long item2) {
+        ConcurrentLongPairSet messagesToReplay = longPairSets.get(item1);
+        if (messagesToReplay != null) {
+            boolean removed = messagesToReplay.remove(item1, item2);
+            if (messagesToReplay.isEmpty() && longPairSets.size() > maxAllowedSetOnRemove) {
+                longPairSets.remove(item1, messagesToReplay);
+            }
+            return removed;
+        }
+        return false;
+    }
+
+    @Override
+    public int removeIf(LongPairPredicate filter) {
+        AtomicInteger removedValues = new AtomicInteger(0);
+        longPairSets.forEach((item1, longPairSet) -> {
+            removedValues.addAndGet(longPairSet.removeIf(filter));
+            if (longPairSet.isEmpty() && longPairSets.size() > maxAllowedSetOnRemove) {
+                longPairSets.remove(item1, longPairSet);
+            }
+        });
+        return removedValues.get();
+    }
+
+    @Override
+    public Set<LongPair> items() {
+        return items((int) this.size());
+    }
+
+    @Override
+    public void forEach(LongPairConsumer processor) {
+        for (Long item1 : longPairSets.navigableKeySet()) {
+            ConcurrentLongPairSet messagesToReplay = longPairSets.get(item1);
+            messagesToReplay.forEach((i1, i2) -> {
+                processor.accept(i1, i2);
+            });
+        }
+    }
+
+    @Override
+    public Set<LongPair> items(int numberOfItems) {
+        return items(numberOfItems, (item1, item2) -> new LongPair(item1, item2));
+    }
+
+    @Override
+    public <T> Set<T> items(int numberOfItems, LongPairFunction<T> longPairConverter) {
+        Set<T> items = new TreeSet<>();
+        AtomicInteger count = new AtomicInteger(0);
+        for (Long item1 : longPairSets.navigableKeySet()) {
+            if (count.get() >= numberOfItems) {// already found set of positions
+                break;
+            }
+            ConcurrentLongPairSet messagesToReplay = longPairSets.get(item1);
+            messagesToReplay.forEach((i1, i2) -> {
+                if (count.get() < numberOfItems) {
+                    items.add(longPairConverter.apply(i1, i2));
+                    count.incrementAndGet();
+                }
+            });
+        }
+        return items;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append('{');
+        final AtomicBoolean first = new AtomicBoolean(true);
+        longPairSets.forEach((key, longPairSet) -> {
+            longPairSet.forEach((item1, item2) -> {
+                if (!first.getAndSet(false)) {
+                    sb.append(", ");
+                }
+                sb.append('[');
+                sb.append(item1);
+                sb.append(':');
+                sb.append(item2);
+                sb.append(']');
+            });
+        });
+        sb.append('}');
+        return sb.toString();
+    }
+
+    @Override
+    public boolean isEmpty() {
+        AtomicBoolean isEmpty = new AtomicBoolean(true);
+        longPairSets.forEach((item1, longPairSet) -> {
+            if (isEmpty.get() && !longPairSet.isEmpty()) {
+                isEmpty.set(false);
+            }
+        });
+        return isEmpty.get();
+    }
+
+    @Override
+    public void clear() {
+        longPairSets.clear();
+    }
+
+    @Override
+    public long size() {
+        AtomicLong size = new AtomicLong(0);
+        longPairSets.forEach((item1, longPairSet) -> {
+            size.getAndAdd(longPairSet.size());
+        });
+        return size.get();
+    }
+
+    @Override
+    public boolean contains(long item1, long item2) {
+        ConcurrentLongPairSet longPairSet = longPairSets.get(item1);
+        if (longPairSet != null) {
+            return longPairSet.contains(item1, item2);
+        }
+        return false;
+    }
+
+}
\ No newline at end of file
diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/LongPairSet.java b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/LongPairSet.java
new file mode 100644
index 0000000..15f55e3
--- /dev/null
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/util/collections/LongPairSet.java
@@ -0,0 +1,144 @@
+/**
+ * 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.pulsar.common.util.collections;
+
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPair;
+import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPairConsumer;
+
+/**
+ * Hash set where values are composed of pairs of longs.
+ *
+ */
+public interface LongPairSet {
+
+    /**
+     * Adds composite value of item1 and item2 to set.
+     * 
+     * @param item1
+     * @param item2
+     * @return
+     */
+    boolean add(long item1, long item2);
+
+    /**
+     * Removes composite value of item1 and item2 from set.
+     * 
+     * @param item1
+     * @param item2
+     * @return
+     */
+    boolean remove(long item1, long item2);
+
+    /**
+     * Removes composite value of item1 and item2 from set if provided predicate {@link LongPairPredicate} matches.
+     * 
+     * @param filter
+     * @return
+     */
+    int removeIf(LongPairPredicate filter);
+
+    /**
+     * execute {@link LongPairConsumer} processor for each entry in the set
+     * 
+     * @param processor
+     */
+    void forEach(LongPairConsumer processor);
+
+    /**
+     * @return a new list of all keys (makes a copy)
+     */
+    Set<LongPair> items();
+
+    /**
+     * @return a new list of keys with max provided numberOfItems (makes a copy)
+     */
+    Set<LongPair> items(int numberOfItems);
+
+    /**
+     * @return a new list of keys with max provided numberOfItems
+     * 
+     * @param messagesToRead
+     * @param longPairConverter
+     *            converts (long,long) pair to <T> object
+     * 
+     * @return
+     */
+    <T> Set<T> items(int numberOfItems, LongPairFunction<T> longPairConverter);
+
+    /**
+     * Check if set is empty.
+     * 
+     * @return
+     */
+    boolean isEmpty();
+
+    /**
+     * Removes all items from set.
+     */
+    void clear();
+
+    public interface LongPairPredicate {
+        boolean test(long v1, long v2);
+    }
+
+    /**
+     * Returns size of the set.
+     * 
+     * @return
+     */
+    long size();
+
+    /**
+     * Checks if given (item1,item2) composite value exists into set.
+     * 
+     * @param item1
+     * @param item2
+     * @return
+     */
+    boolean contains(long item1, long item2);
+    
+    
+    /**
+     * Represents a function that accepts two long arguments and produces a result. This is the two-arity specialization
+     * of {@link Function}.
+     *
+     * @param <T>
+     *            the type of the result of the function
+     *
+     */
+    @FunctionalInterface
+    public interface LongPairFunction<T> {
+
+        /**
+         * Applies this function to the given arguments.
+         *
+         * @param item1
+         *            the first function argument
+         * @param item2
+         *            the second function argument
+         * @return the function result
+         */
+        T apply(long item1, long item2);
+    }
+}
diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java
new file mode 100644
index 0000000..65b26c4
--- /dev/null
+++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java
@@ -0,0 +1,244 @@
+/**
+ * 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.pulsar.common.util.collections;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPair;
+import org.apache.pulsar.common.util.collections.LongPairSet.LongPairPredicate;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.Lists;
+
+public class ConcurrentSortedLongPairSetTest {
+
+    @Test
+    public void simpleInsertions() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        assertTrue(set.isEmpty());
+        assertTrue(set.add(1, 1));
+        assertFalse(set.isEmpty());
+
+        assertTrue(set.add(2, 2));
+        assertTrue(set.add(3, 3));
+
+        assertEquals(set.size(), 3);
+
+        assertTrue(set.contains(1, 1));
+        assertEquals(set.size(), 3);
+
+        assertTrue(set.remove(1, 1));
+        assertEquals(set.size(), 2);
+        assertFalse(set.contains(1, 1));
+        assertFalse(set.contains(5, 5));
+        assertEquals(set.size(), 2);
+
+        assertTrue(set.add(1, 1));
+        assertEquals(set.size(), 3);
+        assertFalse(set.add(1, 1));
+        assertEquals(set.size(), 3);
+    }
+
+    @Test
+    public void testRemove() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        assertTrue(set.isEmpty());
+        assertTrue(set.add(1, 1));
+        assertFalse(set.isEmpty());
+
+        assertFalse(set.remove(1, 0));
+        assertFalse(set.isEmpty());
+        assertTrue(set.remove(1, 1));
+        assertTrue(set.isEmpty());
+    }
+
+    @Test
+    public void concurrentInsertions() throws Throwable {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+        ExecutorService executor = Executors.newCachedThreadPool();
+
+        final int nThreads = 16;
+        final int N = 100_000;
+
+        List<Future<?>> futures = new ArrayList<>();
+        for (int i = 0; i < nThreads; i++) {
+            final int threadIdx = i;
+
+            futures.add(executor.submit(() -> {
+                Random random = new Random();
+
+                for (int j = 0; j < N; j++) {
+                    long key = random.nextLong();
+                    // Ensure keys are unique
+                    key -= key % (threadIdx + 1);
+                    key = Math.abs(key);
+                    set.add(key, key);
+                }
+            }));
+        }
+
+        for (Future<?> future : futures) {
+            future.get();
+        }
+
+        assertEquals(set.size(), N * nThreads);
+
+        executor.shutdown();
+    }
+
+    @Test
+    public void testIteration() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        for (int i = 0; i < 10; i++) {
+            for (int j = 0; j < 10; j++) {
+                set.add(i, j);
+            }
+        }
+
+        for (int i = 0; i < 10; i++) {
+            final int firstKey = i;
+            Set<LongPair> longSetResult = set.items(10);
+            assertEquals(longSetResult.size(), 10);
+            longSetResult.forEach(longPair -> {
+                assertEquals(firstKey, longPair.first);
+            });
+            set.removeIf((item1, item2) -> item1 == firstKey);
+        }
+
+    }
+
+    @Test
+    public void testRemoval() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        set.add(0, 0);
+        set.add(1, 1);
+        set.add(3, 3);
+        set.add(6, 6);
+        set.add(7, 7);
+
+        List<LongPair> values = new ArrayList<>(set.items());
+        values.sort(null);
+        assertEquals(values, Lists.newArrayList(new LongPair(0, 0), new LongPair(1, 1), new LongPair(3, 3),
+                new LongPair(6, 6), new LongPair(7, 7)));
+
+        set.forEach((first, second) -> {
+            if (first < 5) {
+                set.remove(first, second);
+            }
+        });
+        assertEquals(set.size(), values.size() - 3);
+        values = new ArrayList<>(set.items());
+        values.sort(null);
+        assertEquals(values, Lists.newArrayList(new LongPair(6, 6), new LongPair(7, 7)));
+    }
+
+    @Test
+    public void testIfRemoval() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16, 1, 1);
+
+        set.add(0, 0);
+        set.add(1, 1);
+        set.add(3, 3);
+        set.add(6, 6);
+        set.add(7, 7);
+
+        List<LongPair> values = new ArrayList<>(set.items());
+        values.sort(null);
+        assertEquals(values, Lists.newArrayList(new LongPair(0, 0), new LongPair(1, 1), new LongPair(3, 3),
+                new LongPair(6, 6), new LongPair(7, 7)));
+
+        int removeItems = set.removeIf((first, second) -> first < 5);
+
+        assertEquals(3, removeItems);
+        assertEquals(set.size(), values.size() - 3);
+        values = new ArrayList<>(set.items());
+        values.sort(null);
+        assertEquals(values, Lists.newArrayList(new LongPair(6, 6), new LongPair(7, 7)));
+    }
+
+    @Test
+    public void testItems() {
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        int n = 100;
+        int limit = 10;
+        for (int i = 0; i < n; i++) {
+            set.add(i, i);
+        }
+
+        Set<LongPair> items = set.items();
+        Set<LongPair> limitItems = set.items(limit);
+        assertEquals(items.size(), n);
+        assertEquals(limitItems.size(), limit);
+
+        int totalRemovedItems = set.removeIf((first, second) -> limitItems.contains((new LongPair(first, second))));
+        assertEquals(limitItems.size(), totalRemovedItems);
+        assertEquals(set.size(), n - limit);
+    }
+
+    @Test
+    public void testEqualsObjects() {
+
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        long t1 = 1;
+        long t2 = 2;
+        long t1_b = 1;
+        assertEquals(t1, t1_b);
+        assertFalse(t1 == t2);
+        assertFalse(t1_b == t2);
+
+        set.add(t1, t1);
+        assertTrue(set.contains(t1, t1));
+        assertTrue(set.contains(t1_b, t1_b));
+        assertFalse(set.contains(t2, t2));
+
+        assertTrue(set.remove(t1_b, t1_b));
+        assertFalse(set.contains(t1, t1));
+        assertFalse(set.contains(t1_b, t1_b));
+    }
+
+    @Test
+    public void testToString() {
+
+        LongPairSet set = new ConcurrentSortedLongPairSet(16);
+
+        set.add(0, 0);
+        set.add(1, 1);
+        set.add(3, 3);
+        final String toString = "{[0:0], [1:1], [3:3]}";
+        System.out.println(set.toString());
+        assertEquals(set.toString(), toString);
+    }
+
+}
diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java
index a8b1853..cab0a56 100644
--- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java
+++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java
@@ -382,5 +382,5 @@ public class GrowablePriorityLongPairQueueTest {
         assertFalse(queue.exists(7, 1));
 
     }
-    
-}
+
+}
\ No newline at end of file