All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mongodb.internal.connection.FutureAsyncCompletionHandler Maven / Gradle / Ivy

Go to download

The Java operations layer for the MongoDB Java Driver. Third parties can wrap this layer to provide custom higher-level APIs

There is a newer version: 5.3.0-beta0
Show newest version
/*
 * Copyright 2008-present MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mongodb.internal.connection;

import com.mongodb.MongoException;
import com.mongodb.MongoInternalException;
import com.mongodb.connection.AsyncCompletionHandler;
import com.mongodb.lang.Nullable;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;

class FutureAsyncCompletionHandler implements AsyncCompletionHandler {
    private final CountDownLatch latch = new CountDownLatch(1);
    private volatile T result;
    private volatile Throwable error;

    @Override
    public void completed(@Nullable final T result) {
        this.result = result;
        latch.countDown();
    }

    @Override
    public void failed(final Throwable t) {
        this.error = t;
        latch.countDown();
    }

    public void getOpen() throws IOException {
        get("Opening");
    }

    public void getWrite() throws IOException {
        get("Writing to");
    }

    public T getRead() throws IOException {
        return get("Reading from");
    }

    private T get(final String prefix) throws IOException {
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw interruptAndCreateMongoInterruptedException(prefix + " the AsynchronousSocketChannelStream failed", e);

        }
        if (error != null) {
            if (error instanceof IOException) {
                throw (IOException) error;
            } else if (error instanceof MongoException) {
                throw (MongoException) error;
            } else {
                throw new MongoInternalException(prefix + " the AsynchronousSocketChannelStream failed", error);
            }
        }
        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy