1616
1717package org .springframework .kafka .listener ;
1818
19+ import java .time .Duration ;
1920import java .util .Map ;
2021import java .util .Objects ;
2122import java .util .function .Supplier ;
2223
24+ import org .apache .kafka .clients .consumer .Consumer ;
2325import org .apache .kafka .clients .consumer .OffsetAndMetadata ;
2426import org .jspecify .annotations .Nullable ;
2527
3436 * @author Francois Rosiere
3537 * @author Antonio Tomac
3638 * @author Wang Zhiyang
39+ * @author Sanghyeok An
3740 * @since 2.0
3841 *
3942 */
@@ -147,6 +150,36 @@ public static void conditionalSleep(Supplier<Boolean> shouldSleepCondition, long
147150 while (System .currentTimeMillis () < timeout );
148151 }
149152
153+ /**
154+ * Sleep for the desired timeout, as long as shouldSleepCondition supplies true.
155+ * @param shouldSleepCondition to.
156+ * @param interval the timeout.
157+ * @param consumer the kafka consumer to call poll().
158+ * @throws InterruptedException if the thread is interrupted.
159+ */
160+ public static void conditionalSleepWithPoll (Supplier <Boolean > shouldSleepCondition ,
161+ long interval ,
162+ Consumer <?, ?> consumer ) throws InterruptedException {
163+ boolean isFirst = true ;
164+ long timeout = System .currentTimeMillis () + interval ;
165+ long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL ;
166+ do {
167+ Thread .sleep (sleepInterval );
168+ if (!shouldSleepCondition .get ()) {
169+ break ;
170+ }
171+
172+ if (isFirst ) {
173+ isFirst = false ;
174+ }
175+ else {
176+ // To prevent consumer group rebalancing during retry backoff.
177+ consumer .poll (Duration .ZERO );
178+ }
179+ }
180+ while (System .currentTimeMillis () < timeout );
181+ }
182+
150183 /**
151184 * Create a new {@link OffsetAndMetadata} using the given container and offset.
152185 * @param container a container.
@@ -165,4 +198,3 @@ public static OffsetAndMetadata createOffsetAndMetadata(@Nullable MessageListene
165198 return new OffsetAndMetadata (offset );
166199 }
167200}
168-
0 commit comments