Skip to content

Replace uninterruptible Lock.lock with Lock.lockInterruptibly #1206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 10 additions & 18 deletions driver-core/src/main/com/mongodb/connection/netty/NettyStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@

import static com.mongodb.assertions.Assertions.assertNotNull;
import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.internal.Locks.lockInterruptibly;
import static com.mongodb.internal.Locks.withLock;
import static com.mongodb.internal.connection.SslHelper.enableHostNameVerification;
import static com.mongodb.internal.connection.SslHelper.enableSni;
import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;
Expand Down Expand Up @@ -286,7 +288,7 @@ public void readAsync(final int numBytes, final AsyncCompletionHandler<ByteBuf>
private void readAsync(final int numBytes, final AsyncCompletionHandler<ByteBuf> handler, final long readTimeoutMillis) {
ByteBuf buffer = null;
Throwable exceptionResult = null;
lock.lock();
lockInterruptibly(lock);
try {
exceptionResult = pendingException;
if (exceptionResult == null) {
Expand Down Expand Up @@ -344,18 +346,14 @@ private boolean hasBytesAvailable(final int numBytes) {
}

private void handleReadResponse(@Nullable final io.netty.buffer.ByteBuf buffer, @Nullable final Throwable t) {
PendingReader localPendingReader = null;
lock.lock();
try {
PendingReader localPendingReader = withLock(lock, () -> {
if (buffer != null) {
pendingInboundBuffers.add(buffer.retain());
} else {
pendingException = t;
}
localPendingReader = pendingReader;
} finally {
lock.unlock();
}
return pendingReader;
});

if (localPendingReader != null) {
//timeouts may be scheduled only by the public read methods
Expand All @@ -370,8 +368,7 @@ public ServerAddress getAddress() {

@Override
public void close() {
lock.lock();
try {
withLock(lock, () -> {
isClosed = true;
if (channel != null) {
channel.close();
Expand All @@ -382,9 +379,7 @@ public void close() {
iterator.remove();
nextByteBuf.release();
}
} finally {
lock.unlock();
}
});
}

@Override
Expand Down Expand Up @@ -519,8 +514,7 @@ private class OpenChannelFutureListener implements ChannelFutureListener {

@Override
public void operationComplete(final ChannelFuture future) {
lock.lock();
try {
withLock(lock, () -> {
if (future.isSuccess()) {
if (isClosed) {
channelFuture.channel().close();
Expand All @@ -538,9 +532,7 @@ public void operationComplete(final ChannelFuture future) {
initializeChannel(handler, socketAddressQueue);
}
}
} finally {
lock.unlock();
}
});
}
}

Expand Down
34 changes: 29 additions & 5 deletions driver-core/src/main/com/mongodb/internal/Locks.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@

package com.mongodb.internal;

import com.mongodb.MongoInterruptedException;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;
Expand All @@ -37,18 +40,39 @@ public static <V> V withLock(final Lock lock, final Supplier<V> supplier) {
}

public static <V, E extends Exception> V checkedWithLock(final Lock lock, final CheckedSupplier<V, E> supplier) throws E {
lockInterruptibly(lock);
try {
return supplier.get();
} finally {
lock.unlock();
}
}

public static void lockInterruptibly(final Lock lock) throws MongoInterruptedException {
try {
lock.lockInterruptibly();
try {
return supplier.get();
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
throw interruptAndCreateMongoInterruptedException("Interrupted waiting for lock", e);
}
}

public static void lockInterruptiblyUnfair(
// The type must be `ReentrantLock`, not `Lock`,
// because only `ReentrantLock.tryLock` is documented to have the barging behavior.
final ReentrantLock lock) throws MongoInterruptedException {
if (Thread.currentThread().isInterrupted()) {
throw interruptAndCreateMongoInterruptedException(null, null);
}
// `ReentrantLock.tryLock` is unfair
if (!lock.tryLock()) {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw interruptAndCreateMongoInterruptedException(null, e);
}
}
}

private Locks() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.mongodb.internal.Locks.lockInterruptibly;
import static com.mongodb.internal.authentication.HttpHelper.getHttpContents;

/**
Expand All @@ -48,7 +49,7 @@ public static BsonDocument obtainFromEnvironment() {
if (cachedValue.isPresent()) {
accessToken = cachedValue.get();
} else {
CACHED_ACCESS_TOKEN_LOCK.lock();
lockInterruptibly(CACHED_ACCESS_TOKEN_LOCK);
try {
cachedValue = cachedAccessToken.getValue();
if (cachedValue.isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
Expand All @@ -42,6 +41,8 @@
import static com.mongodb.assertions.Assertions.assertNotNull;
import static com.mongodb.assertions.Assertions.assertTrue;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.Locks.lockInterruptibly;
import static com.mongodb.internal.Locks.lockInterruptiblyUnfair;
import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE;
import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;

Expand Down Expand Up @@ -370,7 +371,7 @@ int permits() {
}

boolean acquirePermitImmediateUnfair() {
lockUnfair(lock);
lockInterruptiblyUnfair(lock);
try {
throwIfClosedOrPaused();
if (permits > 0) {
Expand Down Expand Up @@ -427,7 +428,7 @@ boolean acquirePermit(final long timeout, final TimeUnit unit) throws MongoInter
}

void releasePermit() {
lockUnfair(lock);
lockInterruptiblyUnfair(lock);
try {
assertTrue(permits < maxPermits);
//noinspection NonAtomicOperationOnVolatileField
Expand All @@ -439,7 +440,7 @@ void releasePermit() {
}

void pause(final Supplier<MongoException> causeSupplier) {
lockUnfair(lock);
lockInterruptiblyUnfair(lock);
try {
if (!paused) {
this.paused = true;
Expand All @@ -453,7 +454,7 @@ void pause(final Supplier<MongoException> causeSupplier) {

void ready() {
if (paused) {
lockUnfair(lock);
lockInterruptiblyUnfair(lock);
try {
this.paused = false;
this.causeSupplier = null;
Expand All @@ -468,7 +469,7 @@ void ready() {
*/
boolean close() {
if (!closed) {
lockUnfair(lock);
lockInterruptiblyUnfair(lock);
try {
if (!closed) {
closed = true;
Expand Down Expand Up @@ -515,32 +516,4 @@ static String sizeToString(final int size) {
return size == INFINITE_SIZE ? "infinite" : Integer.toString(size);
}

static void lockInterruptibly(final Lock lock) throws MongoInterruptedException {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw interruptAndCreateMongoInterruptedException(null, e);
}
}

private static void lockInterruptiblyUnfair(final ReentrantLock lock) throws MongoInterruptedException {
if (Thread.currentThread().isInterrupted()) {
throw interruptAndCreateMongoInterruptedException(null, null);
}
// `ReentrantLock.tryLock` is unfair
if (!lock.tryLock()) {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw interruptAndCreateMongoInterruptedException(null, e);
}
}
}

static void lockUnfair(final ReentrantLock lock) {
// `ReentrantLock.tryLock` is unfair
if (!lock.tryLock()) {
lock.lock();
}
}
}
Loading