Skip to content

Commit 217646d

Browse files
committed
Race condition in TarantoolClientImpl
- Avoid a possible race between reading, writing and reconnecting threads when a reconnection process is started. It might have happened that the lagged thread (reading or writing) could reset the state to RECONNECT after the reconnecting thread has already started and set the state to 0. As a result, all next attempts to reconnect will never happen. Now the reconnect thread holds on the state as long as it is required. - Avoid another possible race between reading and writing threads when they are started during the reconnection process. It might have happened that one of the threads crashed when it was starting and another slightly lagged thread set up its flag. It could have led that the reconnecting thread saw RECONNECT + R/W state instead of pure RECONNECT. Again, this case broke down all next reconnection attempts. Now reading and writing threads take into account whether RECONNECT state is already set or not. - Replace LockSupport with ReentrantLock.Condition for a thread to be suspended and woken up. Our cluster tests and standalone demo app show that LockSupport is not a safe memory barrier as it could be. The reconnect thread relies on a visibility guarantee between park-unpark invocations which, actually, sometimes doesn't work. Also, according to java-docs LockSupport is more like an internal component to build high-level blocking primitives. It is not recommended using this class directly. It was replaced by ReentrantLock.Condition primitive based on LockSupport but which has proper LockSupport usage inside. Fixes: #142 Affects: #34, #136
1 parent 06755d5 commit 217646d

File tree

2 files changed

+146
-52
lines changed

2 files changed

+146
-52
lines changed

Diff for: src/main/java/org/tarantool/TarantoolClientImpl.java

+143-48
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import java.util.concurrent.atomic.AtomicInteger;
2323
import java.util.concurrent.atomic.AtomicReference;
2424
import java.util.concurrent.locks.Condition;
25-
import java.util.concurrent.locks.LockSupport;
2625
import java.util.concurrent.locks.ReentrantLock;
2726

2827

@@ -63,17 +62,19 @@ public class TarantoolClientImpl extends TarantoolBase<Future<?>> implements Tar
6362
*/
6463
protected TarantoolClientStats stats;
6564
protected StateHelper state = new StateHelper(StateHelper.RECONNECT);
66-
protected Thread reader;
67-
protected Thread writer;
65+
protected volatile Thread reader;
66+
protected volatile Thread writer;
6867

6968
protected Thread connector = new Thread(new Runnable() {
7069
@Override
7170
public void run() {
7271
while (!Thread.currentThread().isInterrupted()) {
73-
if (state.compareAndSet(StateHelper.RECONNECT, 0)) {
74-
reconnect(0, thumbstone);
72+
reconnect(0, thumbstone);
73+
try {
74+
state.awaitReconnection();
75+
} catch (InterruptedException e) {
76+
Thread.currentThread().interrupt();
7577
}
76-
LockSupport.park(state);
7778
}
7879
}
7980
});
@@ -139,16 +140,13 @@ protected void reconnect(int retry, Throwable lastError) {
139140
protected void connect(final SocketChannel channel) throws Exception {
140141
try {
141142
TarantoolGreeting greeting = ProtoUtils.connect(channel,
142-
config.username, config.password);
143+
config.username, config.password);
143144
this.serverVersion = greeting.getServerVersion();
144145
} catch (IOException e) {
145-
try {
146-
channel.close();
147-
} catch (IOException ignored) {
148-
}
149-
146+
closeChannel(channel);
150147
throw new CommunicationException("Couldn't connect to tarantool", e);
151148
}
149+
152150
channel.configureBlocking(false);
153151
this.channel = channel;
154152
this.readChannel = new ReadableViaSelectorChannel(channel);
@@ -174,8 +172,16 @@ public void run() {
174172
readThread();
175173
} finally {
176174
state.release(StateHelper.READING);
177-
if (state.compareAndSet(0, StateHelper.RECONNECT))
178-
LockSupport.unpark(connector);
175+
// there're two cases when a read thread is here
176+
// 1. it's a new generation thread inside/outside
177+
// a reconnection process (currentThread == reader)
178+
// 2. It's an old generation thread inside
179+
// a reconnection process (currentThread != reader)
180+
// Skip the old gen. attempt to reconnect
181+
if (state.getState() == StateHelper.UNINITIALIZED
182+
&& Thread.currentThread() == reader) {
183+
state.trySignalForReconnection();
184+
}
179185
}
180186
}
181187
}
@@ -189,13 +195,28 @@ public void run() {
189195
writeThread();
190196
} finally {
191197
state.release(StateHelper.WRITING);
192-
if (state.compareAndSet(0, StateHelper.RECONNECT))
193-
LockSupport.unpark(connector);
198+
// there're two cases when a write thread is here
199+
// 1. it's a new generation thread inside/outside
200+
// a reconnection process (currentThread == writer)
201+
// 2. It's an old generation thread inside
202+
// a reconnection process (currentThread != writer)
203+
// Skip the old gen. attempt to reconnect
204+
if (state.getState() == StateHelper.UNINITIALIZED
205+
&& Thread.currentThread() == writer) {
206+
state.trySignalForReconnection();
207+
}
194208
}
195209
}
196210
}
197211
});
198212

213+
// reconnection preparation is done
214+
// before reconnection state will be released
215+
// reader/writer threads have been replaced by new ones
216+
// it's required to be sure that old r/w threads
217+
// won't affect new r/w threads.
218+
state.release(StateHelper.RECONNECT);
219+
199220
configureThreads(threadName);
200221
reader.start();
201222
writer.start();
@@ -337,25 +358,21 @@ private boolean directWrite(ByteBuffer buffer) throws InterruptedException, IOEx
337358
}
338359

339360
protected void readThread() {
340-
try {
341-
while (!Thread.currentThread().isInterrupted()) {
342-
try {
343-
TarantoolPacket packet = ProtoUtils.readPacket(readChannel);
361+
while (!Thread.currentThread().isInterrupted()) {
362+
try {
363+
TarantoolPacket packet = ProtoUtils.readPacket(readChannel);
344364

345-
Map<Integer, Object> headers = packet.getHeaders();
365+
Map<Integer, Object> headers = packet.getHeaders();
346366

347-
Long syncId = (Long) headers.get(Key.SYNC.getId());
348-
TarantoolOp<?> future = futures.remove(syncId);
349-
stats.received++;
350-
wait.decrementAndGet();
351-
complete(packet, future);
352-
} catch (Exception e) {
353-
die("Cant read answer", e);
354-
return;
355-
}
367+
Long syncId = (Long) headers.get(Key.SYNC.getId());
368+
TarantoolOp<?> future = futures.remove(syncId);
369+
stats.received++;
370+
wait.decrementAndGet();
371+
complete(packet, future);
372+
} catch (Exception e) {
373+
die("Cant read answer", e);
374+
return;
356375
}
357-
} catch (Exception e) {
358-
die("Cant init thread", e);
359376
}
360377
}
361378

@@ -498,7 +515,7 @@ public TarantoolClientOps<Integer, List<?>, Object, List<?>> syncOps() {
498515

499516
@Override
500517
public TarantoolClientOps<Integer, List<?>, Object, Future<List<?>>> asyncOps() {
501-
return (TarantoolClientOps)this;
518+
return (TarantoolClientOps) this;
502519
}
503520

504521
@Override
@@ -514,7 +531,7 @@ public TarantoolClientOps<Integer, List<?>, Object, Long> fireAndForgetOps() {
514531

515532
@Override
516533
public TarantoolSQLOps<Object, Long, List<Map<String, Object>>> sqlSyncOps() {
517-
return new TarantoolSQLOps<Object, Long, List<Map<String,Object>>>() {
534+
return new TarantoolSQLOps<Object, Long, List<Map<String, Object>>>() {
518535

519536
@Override
520537
public Long update(String sql, Object... bind) {
@@ -530,7 +547,7 @@ public List<Map<String, Object>> query(String sql, Object... bind) {
530547

531548
@Override
532549
public TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String, Object>>>> sqlAsyncOps() {
533-
return new TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String,Object>>>>() {
550+
return new TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String, Object>>>>() {
534551
@Override
535552
public Future<Long> update(String sql, Object... bind) {
536553
return (Future<Long>) exec(Code.EXECUTE, Key.SQL_TEXT, sql, Key.SQL_BIND, bind);
@@ -618,6 +635,7 @@ public TarantoolClientStats getStats() {
618635
* Manages state changes.
619636
*/
620637
protected final class StateHelper {
638+
static final int UNINITIALIZED = 0;
621639
static final int READING = 1;
622640
static final int WRITING = 2;
623641
static final int ALIVE = READING | WRITING;
@@ -627,10 +645,22 @@ protected final class StateHelper {
627645
private final AtomicInteger state;
628646

629647
private final AtomicReference<CountDownLatch> nextAliveLatch =
630-
new AtomicReference<CountDownLatch>(new CountDownLatch(1));
648+
new AtomicReference<>(new CountDownLatch(1));
631649

632650
private final CountDownLatch closedLatch = new CountDownLatch(1);
633651

652+
/**
653+
* The condition variable to signal a reconnection is needed from reader /
654+
* writer threads and waiting for that signal from the reconnection thread.
655+
*
656+
* The lock variable to access this condition.
657+
*
658+
* @see #awaitReconnection()
659+
* @see #trySignalForReconnection()
660+
*/
661+
protected final ReentrantLock connectorLock = new ReentrantLock();
662+
protected final Condition reconnectRequired = connectorLock.newCondition();
663+
634664
protected StateHelper(int state) {
635665
this.state = new AtomicInteger(state);
636666
}
@@ -639,35 +669,60 @@ protected int getState() {
639669
return state.get();
640670
}
641671

672+
/**
673+
* Set CLOSED state, drop RECONNECT state.
674+
*/
642675
protected boolean close() {
643-
for (;;) {
676+
for (; ; ) {
644677
int st = getState();
678+
679+
/* CLOSED is the terminal state. */
645680
if ((st & CLOSED) == CLOSED)
646681
return false;
682+
683+
/* Drop RECONNECT, set CLOSED. */
647684
if (compareAndSet(st, (st & ~RECONNECT) | CLOSED))
648685
return true;
649686
}
650687
}
651688

689+
/**
690+
* Move from a current state to a give one.
691+
*
692+
* Some moves are forbidden.
693+
*/
652694
protected boolean acquire(int mask) {
653-
for (;;) {
654-
int st = getState();
655-
if ((st & CLOSED) == CLOSED)
695+
for (; ; ) {
696+
int currentState = getState();
697+
698+
/* CLOSED is the terminal state. */
699+
if ((currentState & CLOSED) == CLOSED) {
700+
return false;
701+
}
702+
703+
/* Don't move to READING, WRITING or ALIVE from RECONNECT. */
704+
if ((currentState & RECONNECT) > mask) {
656705
return false;
706+
}
657707

658-
if ((st & mask) != 0)
708+
/* Cannot move from a state to the same state. */
709+
if ((currentState & mask) != 0) {
659710
throw new IllegalStateException("State is already " + mask);
711+
}
660712

661-
if (compareAndSet(st, st | mask))
713+
/* Set acquired state. */
714+
if (compareAndSet(currentState, currentState | mask)) {
662715
return true;
716+
}
663717
}
664718
}
665719

666720
protected void release(int mask) {
667-
for (;;) {
721+
for (; ; ) {
668722
int st = getState();
669-
if (compareAndSet(st, st & ~mask))
723+
if (compareAndSet(st, st & ~mask)) {
670724
return;
725+
}
671726
}
672727
}
673728

@@ -686,10 +741,18 @@ protected boolean compareAndSet(int expect, int update) {
686741
return true;
687742
}
688743

744+
/**
745+
* Reconnection uses another way to await state via receiving a signal
746+
* instead of latches.
747+
*/
689748
protected void awaitState(int state) throws InterruptedException {
690-
CountDownLatch latch = getStateLatch(state);
691-
if (latch != null) {
692-
latch.await();
749+
if (state == RECONNECT) {
750+
awaitReconnection();
751+
} else {
752+
CountDownLatch latch = getStateLatch(state);
753+
if (latch != null) {
754+
latch.await();
755+
}
693756
}
694757
}
695758

@@ -709,10 +772,42 @@ private CountDownLatch getStateLatch(int state) {
709772
CountDownLatch latch = nextAliveLatch.get();
710773
/* It may happen so that an error is detected but the state is still alive.
711774
Wait for the 'next' alive state in such cases. */
712-
return (getState() == ALIVE && thumbstone == null) ? null : latch;
775+
return (getState() == ALIVE && thumbstone == null) ? null : latch;
713776
}
714777
return null;
715778
}
779+
780+
/**
781+
* Blocks until a reconnection signal will be received.
782+
*
783+
* @see #trySignalForReconnection()
784+
*/
785+
private void awaitReconnection() throws InterruptedException {
786+
connectorLock.lock();
787+
try {
788+
while (getState() != StateHelper.RECONNECT) {
789+
reconnectRequired.await();
790+
}
791+
} finally {
792+
connectorLock.unlock();
793+
}
794+
}
795+
796+
/**
797+
* Signals to the connector that reconnection process can be performed.
798+
*
799+
* @see #awaitReconnection()
800+
*/
801+
private void trySignalForReconnection() {
802+
if (compareAndSet(StateHelper.UNINITIALIZED, StateHelper.RECONNECT)) {
803+
connectorLock.lock();
804+
try {
805+
reconnectRequired.signal();
806+
} finally {
807+
connectorLock.unlock();
808+
}
809+
}
810+
}
716811
}
717812

718813
protected static class TarantoolOp<V> extends CompletableFuture<V> {

Diff for: src/test/java/org/tarantool/ClientReconnectIT.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import static org.junit.jupiter.api.Assertions.assertEquals;
2222
import static org.junit.jupiter.api.Assertions.assertFalse;
23-
import static org.junit.jupiter.api.Assertions.assertNull;
2423
import static org.junit.jupiter.api.Assertions.assertNotNull;
2524
import static org.junit.jupiter.api.Assertions.assertThrows;
2625
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -227,13 +226,13 @@ public void run() {
227226
public void testLongParallelCloseReconnects() {
228227
int numThreads = 4;
229228
int numClients = 4;
230-
int timeBudget = 30*1000;
229+
int timeBudget = 30 * 1000;
231230

232231
SocketChannelProvider provider = new TestSocketChannelProvider(host,
233232
port, RESTART_TIMEOUT).setSoLinger(0);
234233

235234
final AtomicReferenceArray<TarantoolClient> clients =
236-
new AtomicReferenceArray<TarantoolClient>(numClients);
235+
new AtomicReferenceArray<>(numClients);
237236

238237
for (int idx = 0; idx < clients.length(); idx++) {
239238
clients.set(idx, makeClient(provider));
@@ -301,7 +300,7 @@ public void run() {
301300

302301
// Wait for all threads to finish.
303302
try {
304-
assertTrue(latch.await(RESTART_TIMEOUT, TimeUnit.MILLISECONDS));
303+
assertTrue(latch.await(RESTART_TIMEOUT * 2, TimeUnit.MILLISECONDS));
305304
} catch (InterruptedException e) {
306305
fail(e);
307306
}

0 commit comments

Comments
 (0)