Skip to content

Commit 1bb1f73

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 1bb1f73

File tree

2 files changed

+135
-50
lines changed

2 files changed

+135
-50
lines changed

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

+132-46
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

@@ -70,10 +69,12 @@ public class TarantoolClientImpl extends TarantoolBase<Future<?>> implements Tar
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);
@@ -165,6 +163,7 @@ protected void connect(final SocketChannel channel) throws Exception {
165163

166164
protected void startThreads(String threadName) throws InterruptedException {
167165
final CountDownLatch init = new CountDownLatch(2);
166+
final AtomicInteger generationSync = new AtomicInteger(2);
168167
reader = new Thread(new Runnable() {
169168
@Override
170169
public void run() {
@@ -174,8 +173,11 @@ public void run() {
174173
readThread();
175174
} finally {
176175
state.release(StateHelper.READING);
177-
if (state.compareAndSet(0, StateHelper.RECONNECT))
178-
LockSupport.unpark(connector);
176+
// avoid a case when this thread falls asleep here
177+
// after READING flag released and then can pollute the state
178+
if (generationSync.decrementAndGet() == 0) {
179+
state.trySignalForReconnection();
180+
}
179181
}
180182
}
181183
}
@@ -189,13 +191,23 @@ public void run() {
189191
writeThread();
190192
} finally {
191193
state.release(StateHelper.WRITING);
192-
if (state.compareAndSet(0, StateHelper.RECONNECT))
193-
LockSupport.unpark(connector);
194+
// avoid a case when this thread falls asleep here
195+
// after WRITING flag released and then can pollute the state
196+
if (generationSync.decrementAndGet() == 0) {
197+
state.trySignalForReconnection();
198+
}
194199
}
195200
}
196201
}
197202
});
198203

204+
// reconnection preparation is done
205+
// before reconnection the state will be released
206+
// reader/writer threads have been replaced by new ones
207+
// it's required to be sure that old r/w threads see correct
208+
// client's r/w references
209+
state.release(StateHelper.RECONNECT);
210+
199211
configureThreads(threadName);
200212
reader.start();
201213
writer.start();
@@ -337,25 +349,21 @@ private boolean directWrite(ByteBuffer buffer) throws InterruptedException, IOEx
337349
}
338350

339351
protected void readThread() {
340-
try {
341-
while (!Thread.currentThread().isInterrupted()) {
342-
try {
343-
TarantoolPacket packet = ProtoUtils.readPacket(readChannel);
352+
while (!Thread.currentThread().isInterrupted()) {
353+
try {
354+
TarantoolPacket packet = ProtoUtils.readPacket(readChannel);
344355

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

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-
}
358+
Long syncId = (Long) headers.get(Key.SYNC.getId());
359+
TarantoolOp<?> future = futures.remove(syncId);
360+
stats.received++;
361+
wait.decrementAndGet();
362+
complete(packet, future);
363+
} catch (Exception e) {
364+
die("Cant read answer", e);
365+
return;
356366
}
357-
} catch (Exception e) {
358-
die("Cant init thread", e);
359367
}
360368
}
361369

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

499507
@Override
500508
public TarantoolClientOps<Integer, List<?>, Object, Future<List<?>>> asyncOps() {
501-
return (TarantoolClientOps)this;
509+
return (TarantoolClientOps) this;
502510
}
503511

504512
@Override
@@ -514,7 +522,7 @@ public TarantoolClientOps<Integer, List<?>, Object, Long> fireAndForgetOps() {
514522

515523
@Override
516524
public TarantoolSQLOps<Object, Long, List<Map<String, Object>>> sqlSyncOps() {
517-
return new TarantoolSQLOps<Object, Long, List<Map<String,Object>>>() {
525+
return new TarantoolSQLOps<Object, Long, List<Map<String, Object>>>() {
518526

519527
@Override
520528
public Long update(String sql, Object... bind) {
@@ -530,7 +538,7 @@ public List<Map<String, Object>> query(String sql, Object... bind) {
530538

531539
@Override
532540
public TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String, Object>>>> sqlAsyncOps() {
533-
return new TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String,Object>>>>() {
541+
return new TarantoolSQLOps<Object, Future<Long>, Future<List<Map<String, Object>>>>() {
534542
@Override
535543
public Future<Long> update(String sql, Object... bind) {
536544
return (Future<Long>) exec(Code.EXECUTE, Key.SQL_TEXT, sql, Key.SQL_BIND, bind);
@@ -618,6 +626,7 @@ public TarantoolClientStats getStats() {
618626
* Manages state changes.
619627
*/
620628
protected final class StateHelper {
629+
static final int UNINITIALIZED = 0;
621630
static final int READING = 1;
622631
static final int WRITING = 2;
623632
static final int ALIVE = READING | WRITING;
@@ -627,10 +636,22 @@ protected final class StateHelper {
627636
private final AtomicInteger state;
628637

629638
private final AtomicReference<CountDownLatch> nextAliveLatch =
630-
new AtomicReference<CountDownLatch>(new CountDownLatch(1));
639+
new AtomicReference<>(new CountDownLatch(1));
631640

632641
private final CountDownLatch closedLatch = new CountDownLatch(1);
633642

643+
/**
644+
* The condition variable to signal a reconnection is needed from reader /
645+
* writer threads and waiting for that signal from the reconnection thread.
646+
*
647+
* The lock variable to access this condition.
648+
*
649+
* @see #awaitReconnection()
650+
* @see #trySignalForReconnection()
651+
*/
652+
protected final ReentrantLock connectorLock = new ReentrantLock();
653+
protected final Condition reconnectRequired = connectorLock.newCondition();
654+
634655
protected StateHelper(int state) {
635656
this.state = new AtomicInteger(state);
636657
}
@@ -639,35 +660,60 @@ protected int getState() {
639660
return state.get();
640661
}
641662

663+
/**
664+
* Set CLOSED state, drop RECONNECT state.
665+
*/
642666
protected boolean close() {
643-
for (;;) {
667+
for (; ; ) {
644668
int st = getState();
669+
670+
/* CLOSED is the terminal state. */
645671
if ((st & CLOSED) == CLOSED)
646672
return false;
673+
674+
/* Drop RECONNECT, set CLOSED. */
647675
if (compareAndSet(st, (st & ~RECONNECT) | CLOSED))
648676
return true;
649677
}
650678
}
651679

680+
/**
681+
* Move from a current state to a give one.
682+
*
683+
* Some moves are forbidden.
684+
*/
652685
protected boolean acquire(int mask) {
653-
for (;;) {
654-
int st = getState();
655-
if ((st & CLOSED) == CLOSED)
686+
for (; ; ) {
687+
int currentState = getState();
688+
689+
/* CLOSED is the terminal state. */
690+
if ((currentState & CLOSED) == CLOSED) {
691+
return false;
692+
}
693+
694+
/* Don't move to READING, WRITING or ALIVE from RECONNECT. */
695+
if ((currentState & RECONNECT) > mask) {
656696
return false;
697+
}
657698

658-
if ((st & mask) != 0)
699+
/* Cannot move from a state to the same state. */
700+
if ((currentState & mask) != 0) {
659701
throw new IllegalStateException("State is already " + mask);
702+
}
660703

661-
if (compareAndSet(st, st | mask))
704+
/* Set acquired state. */
705+
if (compareAndSet(currentState, currentState | mask)) {
662706
return true;
707+
}
663708
}
664709
}
665710

666711
protected void release(int mask) {
667-
for (;;) {
712+
for (; ; ) {
668713
int st = getState();
669-
if (compareAndSet(st, st & ~mask))
714+
if (compareAndSet(st, st & ~mask)) {
670715
return;
716+
}
671717
}
672718
}
673719

@@ -686,10 +732,18 @@ protected boolean compareAndSet(int expect, int update) {
686732
return true;
687733
}
688734

735+
/**
736+
* Reconnection uses another way to await state via receiving a signal
737+
* instead of latches.
738+
*/
689739
protected void awaitState(int state) throws InterruptedException {
690-
CountDownLatch latch = getStateLatch(state);
691-
if (latch != null) {
692-
latch.await();
740+
if (state == RECONNECT) {
741+
awaitReconnection();
742+
} else {
743+
CountDownLatch latch = getStateLatch(state);
744+
if (latch != null) {
745+
latch.await();
746+
}
693747
}
694748
}
695749

@@ -709,10 +763,42 @@ private CountDownLatch getStateLatch(int state) {
709763
CountDownLatch latch = nextAliveLatch.get();
710764
/* It may happen so that an error is detected but the state is still alive.
711765
Wait for the 'next' alive state in such cases. */
712-
return (getState() == ALIVE && thumbstone == null) ? null : latch;
766+
return (getState() == ALIVE && thumbstone == null) ? null : latch;
713767
}
714768
return null;
715769
}
770+
771+
/**
772+
* Blocks until a reconnection signal will be received.
773+
*
774+
* @see #trySignalForReconnection()
775+
*/
776+
private void awaitReconnection() throws InterruptedException {
777+
connectorLock.lock();
778+
try {
779+
while (getState() != StateHelper.RECONNECT) {
780+
reconnectRequired.await();
781+
}
782+
} finally {
783+
connectorLock.unlock();
784+
}
785+
}
786+
787+
/**
788+
* Signals to the connector that reconnection process can be performed.
789+
*
790+
* @see #awaitReconnection()
791+
*/
792+
private void trySignalForReconnection() {
793+
if (compareAndSet(StateHelper.UNINITIALIZED, StateHelper.RECONNECT)) {
794+
connectorLock.lock();
795+
try {
796+
reconnectRequired.signal();
797+
} finally {
798+
connectorLock.unlock();
799+
}
800+
}
801+
}
716802
}
717803

718804
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)