Search in sources :

Example 1 with Timeout

use of com.mongodb.internal.Timeout in project mongo-java-driver by mongodb.

the class DefaultConnectionPool method getAsync.

@Override
public void getAsync(final SingleResultCallback<InternalConnection> callback) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("Asynchronously getting a connection from the pool for server %s", serverId));
    }
    connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId));
    Timeout timeout = Timeout.startNow(settings.getMaxWaitTime(NANOSECONDS));
    SingleResultCallback<InternalConnection> eventSendingCallback = (result, failure) -> {
        SingleResultCallback<InternalConnection> errHandlingCallback = errorHandlingCallback(callback, LOGGER);
        if (failure == null) {
            connectionPoolListener.connectionCheckedOut(new ConnectionCheckedOutEvent(getId(result)));
            errHandlingCallback.onResult(result, null);
        } else {
            errHandlingCallback.onResult(null, checkOutFailed(failure));
        }
    };
    try {
        stateAndGeneration.throwIfClosedOrPaused();
    } catch (RuntimeException e) {
        eventSendingCallback.onResult(null, e);
        return;
    }
    asyncWorkManager.enqueue(new Task(timeout, t -> {
        if (t != null) {
            eventSendingCallback.onResult(null, t);
        } else {
            PooledConnection connection;
            try {
                connection = getPooledConnection(timeout);
            } catch (RuntimeException e) {
                eventSendingCallback.onResult(null, e);
                return;
            }
            if (connection.opened()) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(format("Pooled connection %s to server %s is already open", getId(connection), serverId));
                }
                eventSendingCallback.onResult(connection, null);
            } else {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(format("Pooled connection %s to server %s is not yet open", getId(connection), serverId));
                }
                openConcurrencyLimiter.openAsyncWithConcurrencyLimit(connection, timeout, eventSendingCallback);
            }
        }
    }));
}
Also used : SdamIssue(com.mongodb.internal.connection.SdamServerDescriptionManager.SdamIssue) ServerDescription(com.mongodb.connection.ServerDescription) ConcurrentPool.lockUnfair(com.mongodb.internal.connection.ConcurrentPool.lockUnfair) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) ConnectionDescription(com.mongodb.connection.ConnectionDescription) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentPool.sizeToString(com.mongodb.internal.connection.ConcurrentPool.sizeToString) MongoServerUnavailableException(com.mongodb.MongoServerUnavailableException) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Prune(com.mongodb.internal.connection.ConcurrentPool.Prune) MongoException(com.mongodb.MongoException) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BlockingQueue(java.util.concurrent.BlockingQueue) Assertions.assertFalse(com.mongodb.assertions.Assertions.assertFalse) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) Decoder(org.bson.codecs.Decoder) PRIVATE(com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE) List(java.util.List) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) NonNull(com.mongodb.lang.NonNull) Assertions.fail(com.mongodb.assertions.Assertions.fail) Optional(java.util.Optional) ThreadSafe(com.mongodb.annotations.ThreadSafe) Reason(com.mongodb.event.ConnectionCheckOutFailedEvent.Reason) Queue(java.util.Queue) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) NotThreadSafe(com.mongodb.annotations.NotThreadSafe) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) LongAdder(java.util.concurrent.atomic.LongAdder) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) Assertions.assertNotNull(com.mongodb.assertions.Assertions.assertNotNull) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) ErrorHandlingResultCallback.errorHandlingCallback(com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Deque(java.util.Deque) ConcurrentPool.lockInterruptibly(com.mongodb.internal.connection.ConcurrentPool.lockInterruptibly) Supplier(java.util.function.Supplier) INFINITE_SIZE(com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE) Assertions.isTrue(com.mongodb.assertions.Assertions.isTrue) MongoConnectionPoolClearedException(com.mongodb.MongoConnectionPoolClearedException) VisibleForTesting(com.mongodb.internal.VisibleForTesting) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SessionContext(com.mongodb.internal.session.SessionContext) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) LinkedList(java.util.LinkedList) Logger(com.mongodb.diagnostics.logging.Logger) ExecutorService(java.util.concurrent.ExecutorService) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) ByteBuf(org.bson.ByteBuf) MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) ReentrantLock(java.util.concurrent.locks.ReentrantLock) EventListenerHelper.getConnectionPoolListener(com.mongodb.internal.event.EventListenerHelper.getConnectionPoolListener) ServerId(com.mongodb.connection.ServerId) RequestContext(com.mongodb.RequestContext) Timeout(com.mongodb.internal.Timeout) MongoTimeoutException(com.mongodb.MongoTimeoutException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) OptionalProvider(com.mongodb.internal.inject.OptionalProvider) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) Condition(java.util.concurrent.locks.Condition) Lock(java.util.concurrent.locks.Lock) Assertions.assertNull(com.mongodb.assertions.Assertions.assertNull) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) Loggers(com.mongodb.diagnostics.logging.Loggers) DaemonThreadFactory(com.mongodb.internal.thread.DaemonThreadFactory) ObjectId(org.bson.types.ObjectId) Nullable(com.mongodb.lang.Nullable) ConnectionId(com.mongodb.connection.ConnectionId) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) StampedLock(java.util.concurrent.locks.StampedLock) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Timeout(com.mongodb.internal.Timeout) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent)

Example 2 with Timeout

use of com.mongodb.internal.Timeout in project mongo-java-driver by mongodb.

the class DefaultConnectionPoolTest method useConcurrently.

private static void useConcurrently(final DefaultConnectionPool pool, final int concurrentUsersCount, final boolean checkoutSync, final boolean checkoutAsync, final float invalidateAndReadyProb, final float invalidateProb, final float readyProb, final ExecutorService executor, final long durationNanos) throws ExecutionException, InterruptedException, TimeoutException {
    assertTrue(invalidateAndReadyProb >= 0 && invalidateAndReadyProb <= 1);
    Runnable spontaneouslyInvalidateReady = () -> {
        if (ThreadLocalRandom.current().nextFloat() < invalidateAndReadyProb) {
            pool.invalidate(null);
            pool.ready();
        }
        if (ThreadLocalRandom.current().nextFloat() < invalidateProb) {
            pool.invalidate(null);
        }
        if (ThreadLocalRandom.current().nextFloat() < readyProb) {
            pool.ready();
        }
    };
    Collection<Future<?>> tasks = new ArrayList<>();
    Timeout duration = Timeout.startNow(durationNanos);
    for (int i = 0; i < concurrentUsersCount; i++) {
        if ((checkoutSync && checkoutAsync) ? i % 2 == 0 : checkoutSync) {
            // check out synchronously and check in
            tasks.add(executor.submit(() -> {
                while (!(duration.expired() || Thread.currentThread().isInterrupted())) {
                    spontaneouslyInvalidateReady.run();
                    InternalConnection conn = null;
                    try {
                        conn = pool.get(TEST_WAIT_TIMEOUT_MILLIS, MILLISECONDS);
                    } catch (MongoConnectionPoolClearedException e) {
                    // expected because we spontaneously invalidate `pool`
                    } finally {
                        if (conn != null) {
                            conn.close();
                        }
                    }
                }
            }));
        } else if (checkoutAsync) {
            // check out asynchronously and check in
            tasks.add(executor.submit(() -> {
                while (!(duration.expired() || Thread.currentThread().isInterrupted())) {
                    spontaneouslyInvalidateReady.run();
                    CompletableFuture<InternalConnection> futureCheckOutCheckIn = new CompletableFuture<>();
                    pool.getAsync((conn, t) -> {
                        if (t != null) {
                            if (t instanceof MongoConnectionPoolClearedException) {
                                // expected because we spontaneously invalidate `pool`
                                futureCheckOutCheckIn.complete(null);
                            } else {
                                futureCheckOutCheckIn.completeExceptionally(t);
                            }
                        } else {
                            conn.close();
                            futureCheckOutCheckIn.complete(null);
                        }
                    });
                    try {
                        futureCheckOutCheckIn.get(TEST_WAIT_TIMEOUT_MILLIS, MILLISECONDS);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    } catch (ExecutionException | TimeoutException e) {
                        throw new AssertionError(e);
                    }
                }
            }));
        }
    }
    for (Future<?> task : tasks) {
        task.get(durationNanos + MILLISECONDS.toNanos(TEST_WAIT_TIMEOUT_MILLIS), NANOSECONDS);
    }
}
Also used : Timeout(com.mongodb.internal.Timeout) MongoConnectionPoolClearedException(com.mongodb.MongoConnectionPoolClearedException) ArrayList(java.util.ArrayList) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with Timeout

use of com.mongodb.internal.Timeout in project mongo-java-driver by mongodb.

the class DefaultConnectionPool method get.

@Override
public InternalConnection get(final long timeoutValue, final TimeUnit timeUnit) {
    connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId));
    Timeout timeout = Timeout.startNow(timeoutValue, timeUnit);
    try {
        stateAndGeneration.throwIfClosedOrPaused();
        PooledConnection connection = getPooledConnection(timeout);
        if (!connection.opened()) {
            connection = openConcurrencyLimiter.openOrGetAvailable(connection, timeout);
        }
        connectionPoolListener.connectionCheckedOut(new ConnectionCheckedOutEvent(getId(connection)));
        return connection;
    } catch (RuntimeException e) {
        throw (RuntimeException) checkOutFailed(e);
    }
}
Also used : ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Timeout(com.mongodb.internal.Timeout) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent)

Aggregations

Timeout (com.mongodb.internal.Timeout)3 MongoConnectionPoolClearedException (com.mongodb.MongoConnectionPoolClearedException)2 ConnectionCheckOutStartedEvent (com.mongodb.event.ConnectionCheckOutStartedEvent)2 ConnectionCheckedOutEvent (com.mongodb.event.ConnectionCheckedOutEvent)2 MongoException (com.mongodb.MongoException)1 MongoInterruptedException (com.mongodb.MongoInterruptedException)1 MongoServerUnavailableException (com.mongodb.MongoServerUnavailableException)1 MongoTimeoutException (com.mongodb.MongoTimeoutException)1 RequestContext (com.mongodb.RequestContext)1 NotThreadSafe (com.mongodb.annotations.NotThreadSafe)1 ThreadSafe (com.mongodb.annotations.ThreadSafe)1 Assertions.assertFalse (com.mongodb.assertions.Assertions.assertFalse)1 Assertions.assertNotNull (com.mongodb.assertions.Assertions.assertNotNull)1 Assertions.assertNull (com.mongodb.assertions.Assertions.assertNull)1 Assertions.assertTrue (com.mongodb.assertions.Assertions.assertTrue)1 Assertions.fail (com.mongodb.assertions.Assertions.fail)1 Assertions.isTrue (com.mongodb.assertions.Assertions.isTrue)1 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)1 ConnectionDescription (com.mongodb.connection.ConnectionDescription)1 ConnectionId (com.mongodb.connection.ConnectionId)1