Skip to content

Commit dde82f6

Browse files
authored
Fix bug in Recycler with racing calls to recycle (#11037)
Motivation: It is possible for two separate threads to race on recycling an object. If this happens, the object might be added to a WeakOrderQueue when it shouldn't be. The end result of this is that an object could be acquired multiple times, without a recycle in between. Effectively, it ends up in circulation twice. Modification: We fix this by making the update to the lastRecycledId field of the handle, an atomic state transition. Only the thread that "wins" the race and succeeds in their state transition will be allowed to recycle the object. The others will bail out on their recycling. We use weakCompareAndSet because we only need the atomicity guarantee, and the program order within each thread is sufficient. Also, spurious failures just means we won't recycle that particular object, which is fine. Result: Objects no longer risk circulating twice due to a recycle race. This fixes #10986
1 parent a60825c commit dde82f6

2 files changed

Lines changed: 132 additions & 5 deletions

File tree

‎common/src/main/java/io/netty/util/Recycler.java‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import java.util.Map;
2828
import java.util.WeakHashMap;
2929
import java.util.concurrent.atomic.AtomicInteger;
30+
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
3031

3132
import static io.netty.util.internal.MathUtil.safeFindNextPositivePowerOfTwo;
3233
import static java.lang.Math.max;
@@ -209,8 +210,16 @@ final int threadLocalSize() {
209210

210211
public interface Handle<T> extends ObjectPool.Handle<T> { }
211212

213+
@SuppressWarnings("unchecked")
212214
private static final class DefaultHandle<T> implements Handle<T> {
213-
int lastRecycledId;
215+
private static final AtomicIntegerFieldUpdater<DefaultHandle<?>> LAST_RECYCLED_ID_UPDATER;
216+
static {
217+
AtomicIntegerFieldUpdater<?> updater = AtomicIntegerFieldUpdater.newUpdater(
218+
DefaultHandle.class, "lastRecycledId");
219+
LAST_RECYCLED_ID_UPDATER = (AtomicIntegerFieldUpdater<DefaultHandle<?>>) updater;
220+
}
221+
222+
volatile int lastRecycledId;
214223
int recycleId;
215224

216225
boolean hasBeenRecycled;
@@ -235,6 +244,12 @@ public void recycle(Object object) {
235244

236245
stack.push(this);
237246
}
247+
248+
public boolean compareAndSetLastRecycledId(int expectLastRecycledId, int updateLastRecycledId) {
249+
// Use "weak…" because we do not need synchronize-with ordering, only atomicity.
250+
// Also, spurious failures are fine, since no code should rely on recycling for correctness.
251+
return LAST_RECYCLED_ID_UPDATER.weakCompareAndSet(this, expectLastRecycledId, updateLastRecycledId);
252+
}
238253
}
239254

240255
private static final FastThreadLocal<Map<Stack<?>, WeakOrderQueue>> DELAYED_RECYCLED =
@@ -371,11 +386,15 @@ void setNext(WeakOrderQueue next) {
371386

372387
void reclaimAllSpaceAndUnlink() {
373388
head.reclaimAllSpaceAndUnlink();
374-
this.next = null;
389+
next = null;
375390
}
376391

377392
void add(DefaultHandle<?> handle) {
378-
handle.lastRecycledId = id;
393+
if (!handle.compareAndSetLastRecycledId(0, id)) {
394+
// Separate threads could be racing to add the handle to each their own WeakOrderQueue.
395+
// We only add the handle to the queue if we win the race and observe that lastRecycledId is zero.
396+
return;
397+
}
379398

380399
// While we also enforce the recycling ratio when we transfer objects from the WeakOrderQueue to the Stack
381400
// we better should enforce it as well early. Missing to do so may let the WeakOrderQueue grow very fast
@@ -649,10 +668,10 @@ void push(DefaultHandle<?> item) {
649668
}
650669

651670
private void pushNow(DefaultHandle<?> item) {
652-
if ((item.recycleId | item.lastRecycledId) != 0) {
671+
if (item.recycleId != 0 || !item.compareAndSetLastRecycledId(0, OWN_THREAD_ID)) {
653672
throw new IllegalStateException("recycled already");
654673
}
655-
item.recycleId = item.lastRecycledId = OWN_THREAD_ID;
674+
item.recycleId = OWN_THREAD_ID;
656675

657676
int size = this.size;
658677
if (size >= maxCapacity || dropHandle(item)) {

‎common/src/test/java/io/netty/util/RecyclerTest.java‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import org.junit.Test;
1919

2020
import java.util.Random;
21+
import java.util.concurrent.CountDownLatch;
2122
import java.util.concurrent.atomic.AtomicBoolean;
2223
import java.util.concurrent.atomic.AtomicInteger;
2324
import java.util.concurrent.atomic.AtomicReference;
@@ -114,12 +115,119 @@ public void run() {
114115
});
115116
thread2.start();
116117
thread2.join();
118+
HandledObject a = recycler.get();
119+
HandledObject b = recycler.get();
120+
assertNotSame(a, b);
117121
IllegalStateException exception = exceptionStore.get();
118122
if (exception != null) {
119123
throw exception;
120124
}
121125
}
122126

127+
@Test
128+
public void testMultipleRecycleAtDifferentThreadRacing() throws InterruptedException {
129+
Recycler<HandledObject> recycler = newRecycler(1024);
130+
final HandledObject object = recycler.get();
131+
final AtomicReference<IllegalStateException> exceptionStore = new AtomicReference<IllegalStateException>();
132+
133+
final CountDownLatch countDownLatch = new CountDownLatch(2);
134+
final Thread thread1 = new Thread(new Runnable() {
135+
@Override
136+
public void run() {
137+
try {
138+
object.recycle();
139+
} catch (IllegalStateException e) {
140+
Exception x = exceptionStore.getAndSet(e);
141+
if (x != null) {
142+
e.addSuppressed(x);
143+
}
144+
} finally {
145+
countDownLatch.countDown();
146+
}
147+
}
148+
});
149+
thread1.start();
150+
151+
final Thread thread2 = new Thread(new Runnable() {
152+
@Override
153+
public void run() {
154+
try {
155+
object.recycle();
156+
} catch (IllegalStateException e) {
157+
Exception x = exceptionStore.getAndSet(e);
158+
if (x != null) {
159+
e.addSuppressed(x);
160+
}
161+
} finally {
162+
countDownLatch.countDown();
163+
}
164+
}
165+
});
166+
thread2.start();
167+
168+
try {
169+
countDownLatch.await();
170+
HandledObject a = recycler.get();
171+
HandledObject b = recycler.get();
172+
assertNotSame(a, b);
173+
IllegalStateException exception = exceptionStore.get();
174+
if (exception != null) {
175+
assertEquals("recycled already", exception.getMessage());
176+
assertEquals(0, exception.getSuppressed().length);
177+
}
178+
} finally {
179+
thread1.join(1000);
180+
thread2.join(1000);
181+
}
182+
}
183+
184+
@Test
185+
public void testMultipleRecycleRacing() throws InterruptedException {
186+
Recycler<HandledObject> recycler = newRecycler(1024);
187+
final HandledObject object = recycler.get();
188+
final AtomicReference<IllegalStateException> exceptionStore = new AtomicReference<IllegalStateException>();
189+
190+
final CountDownLatch countDownLatch = new CountDownLatch(1);
191+
final Thread thread1 = new Thread(new Runnable() {
192+
@Override
193+
public void run() {
194+
try {
195+
object.recycle();
196+
} catch (IllegalStateException e) {
197+
Exception x = exceptionStore.getAndSet(e);
198+
if (x != null) {
199+
e.addSuppressed(x);
200+
}
201+
} finally {
202+
countDownLatch.countDown();
203+
}
204+
}
205+
});
206+
thread1.start();
207+
208+
try {
209+
object.recycle();
210+
} catch (IllegalStateException e) {
211+
Exception x = exceptionStore.getAndSet(e);
212+
if (x != null) {
213+
e.addSuppressed(x);
214+
}
215+
}
216+
217+
try {
218+
countDownLatch.await();
219+
HandledObject a = recycler.get();
220+
HandledObject b = recycler.get();
221+
assertNotSame(a, b);
222+
IllegalStateException exception = exceptionStore.get();
223+
if (exception != null) {
224+
throw exception;
225+
}
226+
} finally {
227+
thread1.join(1000);
228+
}
229+
}
230+
123231
@Test
124232
public void testRecycle() {
125233
Recycler<HandledObject> recycler = newRecycler(1024);

0 commit comments

Comments
 (0)