From b7011ebe5df19cf26b71cbcc39250b4094262116 Mon Sep 17 00:00:00 2001 From: Lucio Paiva Date: Wed, 12 Jul 2023 18:56:01 +0100 Subject: [PATCH] Fix NPE when manually flushing a batch When manually flushing a batch with a set size, we could potentially run into a NPE if the command queue is empty when flush() is called. --- .../io/lettuce/core/dynamic/SimpleBatcher.java | 8 ++++---- .../RedisCommandsBatchingIntegrationTests.java | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/lettuce/core/dynamic/SimpleBatcher.java b/src/main/java/io/lettuce/core/dynamic/SimpleBatcher.java index 3f2edf951b..e131d8db4c 100644 --- a/src/main/java/io/lettuce/core/dynamic/SimpleBatcher.java +++ b/src/main/java/io/lettuce/core/dynamic/SimpleBatcher.java @@ -35,6 +35,7 @@ * * * @author Mark Paluch + * @author Lucio Paiva */ class SimpleBatcher implements Batcher { @@ -148,12 +149,12 @@ private List> prepareForceFlush() { List> batch = new ArrayList<>(Math.max(batchSize, 10)); - do { + while (!queue.isEmpty()) { + RedisCommand poll = queue.poll(); - assert poll != null; batch.add(poll); - } while (!queue.isEmpty()); + } return batch; } @@ -166,7 +167,6 @@ private List> prepareDefaultFlush(int consu RedisCommand poll = queue.poll(); - assert poll != null; batch.add(poll); } diff --git a/src/test/java/io/lettuce/core/dynamic/RedisCommandsBatchingIntegrationTests.java b/src/test/java/io/lettuce/core/dynamic/RedisCommandsBatchingIntegrationTests.java index ea9e60c299..adbfa5cac3 100644 --- a/src/test/java/io/lettuce/core/dynamic/RedisCommandsBatchingIntegrationTests.java +++ b/src/test/java/io/lettuce/core/dynamic/RedisCommandsBatchingIntegrationTests.java @@ -42,6 +42,7 @@ /** * @author Mark Paluch + * @author Lucio Paiva */ @ExtendWith(LettuceExtension.class) class RedisCommandsBatchingIntegrationTests extends TestSupport { @@ -99,6 +100,16 @@ void selectiveBatchingShouldHandleErrors() { } } + @Test + void shouldNotCrashWhenFlushCalledWithEmptyQueue() { + + RedisCommandFactory factory = new RedisCommandFactory(redis.getStatefulConnection()); + + SelectiveBatchingWithSize api = factory.getCommands(SelectiveBatchingWithSize.class); + + api.flush(); + } + @Test void shouldExecuteBatchingSynchronously() { @@ -215,4 +226,9 @@ static interface SelectiveBatching extends Commands, BatchExecutor { } + @BatchSize(5) + interface SelectiveBatchingWithSize extends Commands, BatchExecutor { + + } + }