org.apache.geode.CancelCriterion - java examples

Here are the examples of the java api org.apache.geode.CancelCriterion taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

60 Examples 7

19 View Complete Implementation : SingleThreadJTAExecutorTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced SingleThreadJTAExecutorTest {

    private SingleThreadJTAExecutor singleThreadJTAExecutor;

    private TXState txState;

    private ExecutorService executor;

    private BeforeCompletion beforeCompletion;

    private AfterCompletion afterCompletion;

    private CancelCriterion cancelCriterion;

    @Before
    public void setup() {
        txState = mock(TXState.clreplaced, RETURNS_DEEP_STUBS);
        executor = Executors.newSingleThreadExecutor();
        beforeCompletion = mock(BeforeCompletion.clreplaced);
        afterCompletion = mock(AfterCompletion.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        singleThreadJTAExecutor = new SingleThreadJTAExecutor(beforeCompletion, afterCompletion);
    }

    @Test
    public void executeBeforeCompletionCallsDoOps() {
        InOrder inOrder = inOrder(beforeCompletion, afterCompletion);
        singleThreadJTAExecutor.executeBeforeCompletion(txState, executor, cancelCriterion);
        verify(beforeCompletion, times(1)).execute(eq(cancelCriterion));
        await().untilreplacederted(() -> inOrder.verify(beforeCompletion, times(1)).doOp(eq(txState)));
        await().untilreplacederted(() -> inOrder.verify(afterCompletion, times(1)).doOp(eq(txState), eq(cancelCriterion)));
    }

    @Test
    public void cleanupInvokesCancel() {
        singleThreadJTAExecutor.cleanup();
        verify(afterCompletion, times(1)).cancel();
    }

    @Test(expected = RuntimeException.clreplaced)
    public void doOpsInvokesAfterCompletionDoOpWhenBeforeCompletionThrows() {
        doThrow(RuntimeException.clreplaced).when(beforeCompletion).doOp(txState);
        singleThreadJTAExecutor.doOps(txState, cancelCriterion);
        verify(afterCompletion, times(1)).doOp(eq(txState), eq(cancelCriterion));
    }
}

19 View Complete Implementation : MsgDestreamer.java
Copyright Apache License 2.0
Author : apache
/**
 * <p>
 * MsgDestreamer supports destreaming a streamed message from a tcp Connection that arrives in
 * chunks. This allows us to receive a message without needing to read it completely into a buffer
 * before we can start deserializing it.
 *
 * @since GemFire 5.0.2
 */
public clreplaced MsgDestreamer {

    /**
     * If an exception occurs during deserialization of the message it will be recorded here.
     */
    private Throwable failure;

    /**
     * Used to store the deserialized message on success.
     */
    private DistributionMessage result;

    /**
     * The current failed messages reply processor id if it has one
     */
    private int RPid;

    /**
     * The thread that will be doing the deserialization of the message.
     */
    private final DestreamerThread t;

    private int size;

    final CancelCriterion stopper;

    final Version version;

    public MsgDestreamer(DMStats stats, CancelCriterion stopper, Version v) {
        this.stopper = stopper;
        this.t = new DestreamerThread(stats, stopper);
        this.version = v;
        init();
    }

    private void init() {
        this.t.start();
    }

    public void close() {
        reset();
        this.t.close();
    }

    public void reset() {
        synchronized (this) {
            this.failure = null;
            this.result = null;
        }
        this.size = 0;
        this.t.setName("IDLE p2pDestreamer");
    }

    public void setName(String name) {
        this.t.setName("p2pDestreamer for " + name);
    }

    private void waitUntilDone() throws InterruptedException {
        if (this.t.isClosed() || Thread.interrupted())
            throw new InterruptedException();
        synchronized (this) {
            while (this.failure == null && this.result == null) {
                if (this.t.isClosed() || Thread.interrupted())
                    throw new InterruptedException();
                // spurious wakeup ok
                this.wait();
            }
        }
    }

    // private final String me = "MsgDestreamer<" + System.idenreplacedyHashCode(this) + ">";
    // public String toString() {
    // return this.me;
    // }
    // private void logit(String s) {
    // LogWriterI18n l = getLogger();
    // if (l != null) {
    // l.fine(this + ": " + s);
    // }
    // }
    // private LogWriterI18n getLogger() {
    // LogWriterI18n result = null;
    // DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
    // if (ds != null) {
    // result = ds.getLogWriter();
    // }
    // return result;
    // }
    /**
     * Adds a chunk to be deserialized
     *
     * @param bb contains the bytes of the chunk
     * @param length the number of bytes in bb that are this chunk
     */
    public void addChunk(ByteBuffer bb, int length) throws IOException {
        // if this destreamer has failed or this chunk is empty just return
        if (this.failure == null && length > 0) {
            // logit("addChunk bb length=" + length);
            this.t.addChunk(bb, length);
            this.size += length;
        }
    }

    /**
     * Returns the number of bytes added to this destreamer.
     */
    public int size() {
        return this.size;
    }

    /**
     * Waits for the deserialization to complete and returns the deserialized message.
     *
     * @throws IOException A problem occurred while deserializing the message.
     * @throws ClreplacedNotFoundException The clreplaced of an object read from <code>in</code> could not be
     *         found
     */
    public DistributionMessage getMessage() throws InterruptedException, IOException, ClreplacedNotFoundException {
        // if (Thread.interrupted()) throw new InterruptedException(); not necessary done in
        // waitUntilDone
        // this.t.join();
        waitUntilDone();
        if (this.failure != null) {
            // logit("failed with" + this.failure);
            if (this.failure instanceof ClreplacedNotFoundException) {
                throw (ClreplacedNotFoundException) this.failure;
            } else if (this.failure instanceof IOException) {
                throw (IOException) this.failure;
            } else {
                IOException io = new IOException("failure during message deserialization");
                io.initCause(this.failure);
                throw io;
            }
        } else {
            // logit("result =" + this.result);
            return this.result;
        }
    }

    /**
     * Returns the reply processor id for the current failed message. Returns 0 if it does not have
     * one. Note this method should only be called after getMessage has thrown an exception.
     */
    public int getRPid() {
        return this.RPid;
    }

    protected void setFailure(Throwable ex, int RPid) {
        synchronized (this) {
            this.failure = ex;
            this.RPid = RPid;
            this.notify();
        }
    }

    protected void setResult(DistributionMessage msg) {
        synchronized (this) {
            this.result = msg;
            this.RPid = 0;
            this.notify();
        }
    }

    /**
     * Thread used to deserialize chunks into a message.
     */
    private clreplaced DestreamerThread extends Thread {

        private volatile boolean closed = false;

        final DestreamerIS is;

        final DMStats stats;

        public DestreamerThread(DMStats stats, CancelCriterion stopper) {
            setDaemon(true);
            super.setName("IDLE p2pDestreamer");
            this.is = new DestreamerIS(this, stopper);
            this.stats = stats;
        }

        // private final String me = "DestreamerThread<" + System.idenreplacedyHashCode(this) + ">";
        // public String toString() {
        // return this.me;
        // }
        public void addChunk(ByteBuffer chunk, int bbLength) throws IOException {
            ByteBuffer bb = chunk.slice();
            bb.limit(bbLength);
            this.is.addChunk(bb);
        }

        @Override
        public void run() {
            for (; ; ) {
                if (isClosed()) {
                    return;
                }
                try {
                    ReplyProcessor21.initMessageRPId();
                    final Version v = version;
                    DataInputStream dis = v == null ? new DataInputStream(this.is) : new VersionedDataInputStream(this.is, v);
                    long startSer = this.stats.startMsgDeserialization();
                    setResult((DistributionMessage) InternalDataSerializer.readDSFID(dis));
                    this.stats.endMsgDeserialization(startSer);
                } catch (VirtualMachineError err) {
                    SystemFailure.initiateFailure(err);
                    // If this ever returns, rethrow the error. We're poisoned
                    // now, so don't let this thread continue.
                    throw err;
                } catch (Throwable ex) {
                    // Whenever you catch Error or Throwable, you must also
                    // catch VirtualMachineError (see above). However, there is
                    // _still_ a possibility that you are dealing with a cascading
                    // error condition, so you also need to check to see if the JVM
                    // is still usable:
                    SystemFailure.checkFailure();
                    setFailure(ex, ReplyProcessor21.getMessageRPId());
                } finally {
                    this.is.close();
                    ReplyProcessor21.clearMessageRPId();
                }
            }
        }

        public void close() {
            this.closed = true;
            interrupt();
        }

        public boolean isClosed() {
            return this.closed;
        }
    }

    /**
     * This input stream waits for data to be available. Once it is provided, by a call to addChunk,
     * it will stream the data in from that chunk, signal that is has completed, and then wait for
     * another chunk.
     */
    private static clreplaced DestreamerIS extends InputStream {

        final Object dataMon = new Object();

        final Object doneMon = new Object();

        ByteBuffer data;

        final DestreamerThread owner;

        final CancelCriterion stopper;

        private clreplaced Stopper extends CancelCriterion {

            private final CancelCriterion stopper;

            Stopper(CancelCriterion stopper) {
                this.stopper = stopper;
            }

            /*
       * (non-Javadoc)
       *
       * @see org.apache.geode.CancelCriterion#cancelInProgress()
       */
            @Override
            public String cancelInProgress() {
                String reason = stopper.cancelInProgress();
                if (reason != null) {
                    return reason;
                }
                if (owner.isClosed()) {
                    return "owner is closed";
                }
                return null;
            }

            /*
       * (non-Javadoc)
       *
       * @see org.apache.geode.CancelCriterion#generateCancelledException(java.lang.Throwable)
       */
            @Override
            public RuntimeException generateCancelledException(Throwable e) {
                String reason = cancelInProgress();
                if (reason == null) {
                    return null;
                }
                RuntimeException result = stopper.generateCancelledException(e);
                if (result != null) {
                    return result;
                }
                return new DistributedSystemDisconnectedException("owner is closed");
            }
        }

        public DestreamerIS(DestreamerThread t, CancelCriterion stopper) {
            this.owner = t;
            this.data = null;
            this.stopper = new Stopper(stopper);
        }

        // public String toString() {
        // return this.owner.me;
        // }
        // private void logit(String s) {
        // LogWriterI18n l = getLogger();
        // if (l != null) {
        // l.fine(this + ": " + s);
        // }
        // }
        // private LogWriterI18n getLogger() {
        // LogWriterI18n result = null;
        // DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
        // if (ds != null) {
        // result = ds.getLogWriter();
        // }
        // return result;
        // }
        private boolean isClosed() {
            return this.owner.isClosed();
        }

        private ByteBuffer waitForData() throws InterruptedException {
            if (isClosed() || Thread.interrupted())
                throw new InterruptedException();
            synchronized (this.dataMon) {
                ByteBuffer result = this.data;
                while (result == null) {
                    if (isClosed() || Thread.interrupted())
                        throw new InterruptedException();
                    // logit("about to dataMon wait");
                    // spurious wakeup ok
                    this.dataMon.wait();
                    // logit("after dataMon wait");
                    if (isClosed() || Thread.interrupted())
                        throw new InterruptedException();
                    result = this.data;
                }
                return result;
            }
        }

        private void provideData(ByteBuffer bb) {
            synchronized (this.dataMon) {
                // if (bb != null) {
                // logit("MDIS: providing bb with " +
                // bb.remaining() + " bytes");
                // }
                this.data = bb;
                // logit("dataMon notify bb=" + bb);
                this.dataMon.notify();
            }
        }

        private void waitUntilDone() throws InterruptedException {
            if (isClosed() || Thread.interrupted())
                throw new InterruptedException();
            synchronized (this.doneMon) {
                while (this.data != null) {
                    if (isClosed() || Thread.interrupted())
                        throw new InterruptedException();
                    // logit("about to doneMon wait");
                    // spurious wakeup ok
                    this.doneMon.wait();
                    // logit("after doneMon wait");
                    if (isClosed() || Thread.interrupted())
                        throw new InterruptedException();
                }
            }
        }

        private void signalDone() {
            synchronized (this.doneMon) {
                this.data = null;
                // logit("doneMon notify");
                this.doneMon.notify();
            }
        }

        public void addChunk(ByteBuffer bb) throws IOException {
            provideData(bb);
            for (; ; ) {
                stopper.checkCancelInProgress(null);
                boolean interrupted = Thread.interrupted();
                try {
                    waitUntilDone();
                    break;
                } catch (InterruptedException e) {
                    interrupted = true;
                } finally {
                    if (interrupted) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        private ByteBuffer waitForAvailableData() throws IOException {
            boolean available = false;
            ByteBuffer myData;
            do {
                // only the thread that sets data to null ever does this check
                // so I believe it is ok to do this check outside of sync.
                myData = this.data;
                if (myData == null) {
                    for (; ; ) {
                        if (isClosed()) {
                            // TODO
                            throw new IOException("owner closed");
                        }
                        stopper.checkCancelInProgress(null);
                        boolean interrupted = Thread.interrupted();
                        try {
                            myData = waitForData();
                            break;
                        } catch (InterruptedException e) {
                            interrupted = true;
                        } finally {
                            if (interrupted) {
                                Thread.currentThread().interrupt();
                            }
                        }
                    }
                    if (myData == null) {
                        // someone must have called close so tell our caller
                        // that we were interrupted. This fixes bug 37230.
                        stopper.checkCancelInProgress(null);
                        throw new InternalGemFireError("bug 37230, please report to support");
                    }
                // logit("received new bb with " +
                // myData.remaining() + " bytes");
                }
                int remaining = myData.remaining();
                if (remaining <= 0) {
                    signalDone();
                } else {
                    available = true;
                }
            } while (!available);
            return myData;
        }

        @Override
        public void close() {
            signalDone();
        }

        /**
         * See the InputStream read method for javadocs. Note that if an attempt to read past the end of
         * the wrapped ByteBuffer is done this method throws BufferUnderflowException
         */
        @Override
        public int read() throws IOException {
            ByteBuffer bb = waitForAvailableData();
            // logit("read result=" + result);
            return (bb.get() & 0xff);
        }

        /*
     * this method is not thread safe See the InputStream read method for javadocs. Note that if an
     * attempt to read past the end of the wrapped ByteBuffer is done this method throws
     * BufferUnderflowException
     */
        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            ByteBuffer bb = waitForAvailableData();
            int remaining = bb.remaining();
            int bytesToRead = len;
            if (remaining < len) {
                bytesToRead = remaining;
            }
            bb.get(b, off, bytesToRead);
            // logit("read[] read=" + bytesToRead);
            return bytesToRead;
        }

        @Override
        public int available() throws IOException {
            ByteBuffer bb = this.data;
            if (bb == null) {
                return 0;
            } else {
                return bb.remaining();
            }
        }
    }

    private static LogWriter getLogger() {
        LogWriter result = null;
        InternalDistributedSystem ids = InternalDistributedSystem.unsafeGetConnectedInstance();
        if (ids != null) {
            result = ids.getLogWriter();
        }
        return result;
    }
}

19 View Complete Implementation : BeforeCompletion.java
Copyright Apache License 2.0
Author : apache
public synchronized void execute(CancelCriterion cancelCriterion) {
    started = true;
    waitUntilFinished(cancelCriterion);
    if (exception != null) {
        throw exception;
    }
}

19 View Complete Implementation : AfterCompletion.java
Copyright Apache License 2.0
Author : apache
private void waitForExecuteOrCancel(CancelCriterion cancelCriterion) {
    waitForCondition(cancelCriterion, () -> action != null);
}

19 View Complete Implementation : OpExecutorImplJUnitTest.java
Copyright Apache License 2.0
Author : apache
@Category({ ClientServerTest.clreplaced })
public clreplaced OpExecutorImplJUnitTest {

    DummyManager manager;

    private LogWriter logger;

    private DummyEndpointManager endpointManager;

    private DummyQueueManager queueManager;

    private RegisterInterestTracker riTracker;

    protected int borrows;

    protected int returns;

    protected int invalidateConnections;

    protected int exchanges;

    protected int serverCrashes;

    protected int getPrimary;

    protected int getBackups;

    private CancelCriterion cancelCriterion;

    @Before
    public void setUp() {
        this.logger = new LocalLogWriter(FINE.intLevel(), System.out);
        this.endpointManager = new DummyEndpointManager();
        this.queueManager = new DummyQueueManager();
        this.manager = new DummyManager();
        riTracker = new RegisterInterestTracker();
        cancelCriterion = new CancelCriterion() {

            @Override
            public String cancelInProgress() {
                return null;
            }

            @Override
            public RuntimeException generateCancelledException(Throwable e) {
                return null;
            }
        };
    }

    @Test
    public void testExecute() throws Exception {
        OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null);
        Object result = exec.execute(new Op() {

            @Override
            public Object attempt(Connection cnx) throws Exception {
                return "hello";
            }
        });
        replacedertEquals("hello", result);
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(0, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        try {
            result = exec.execute(new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new SocketTimeoutException();
                }
            });
            fail("Should have got an exception");
        } catch (ServerConnectivityException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(3, exchanges);
        replacedertEquals(1, returns);
        replacedertEquals(4, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        try {
            result = exec.execute(new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new ServerOperationException("Something didn't work");
                }
            });
            fail("Should have got an exception");
        } catch (ServerOperationException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(0, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        try {
            result = exec.execute(new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new IOException("Something didn't work");
                }
            });
            fail("Should have got an exception");
        } catch (ServerConnectivityException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(3, exchanges);
        replacedertEquals(1, returns);
        replacedertEquals(4, invalidateConnections);
        replacedertEquals(4, serverCrashes);
    }

    private void reset() {
        borrows = 0;
        returns = 0;
        invalidateConnections = 0;
        exchanges = 0;
        serverCrashes = 0;
        getPrimary = 0;
        getBackups = 0;
    }

    @Test
    public void testExecuteOncePerServer() throws Exception {
        OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, null);
        manager.numServers = 5;
        try {
            exec.execute(new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new IOException("Something didn't work");
                }
            });
            fail("Should have got an exception");
        } catch (ServerConnectivityException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(4, exchanges);
        replacedertEquals(1, returns);
        replacedertEquals(6, invalidateConnections);
        replacedertEquals(6, serverCrashes);
    }

    @Test
    public void testRetryFailedServers() throws Exception {
        OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 10, 10, cancelCriterion, null);
        manager.numServers = 5;
        try {
            exec.execute(new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new IOException("Something didn't work");
                }
            });
            fail("Should have got an exception");
        } catch (ServerConnectivityException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(10, exchanges);
        replacedertEquals(1, returns);
        replacedertEquals(11, invalidateConnections);
        replacedertEquals(11, serverCrashes);
    }

    @Test
    public void testExecuteOn() throws Exception {
        OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null);
        ServerLocation server = new ServerLocation("localhost", -1);
        Object result = exec.executeOn(server, new Op() {

            @Override
            public Object attempt(Connection cnx) throws Exception {
                return "hello";
            }
        });
        replacedertEquals("hello", result);
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(0, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        try {
            result = exec.executeOn(server, new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new SocketTimeoutException();
                }
            });
            fail("Should have got an exception");
        } catch (ServerConnectivityException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(1, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        try {
            result = exec.executeOn(server, new Op() {

                @Override
                public Object attempt(Connection cnx) throws Exception {
                    throw new ServerOperationException("Something didn't work");
                }
            });
            fail("Should have got an exception");
        } catch (ServerOperationException expected) {
        // do nothing
        }
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(0, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        reset();
        {
            final String expectedEx = "java.lang.Exception";
            final String addExpected = "<ExpectedException action=add>" + expectedEx + "</ExpectedException>";
            final String removeExpected = "<ExpectedException action=remove>" + expectedEx + "</ExpectedException>";
            logger.info(addExpected);
            try {
                result = exec.executeOn(server, new Op() {

                    @Override
                    public Object attempt(Connection cnx) throws Exception {
                        throw new Exception("Something didn't work");
                    }
                });
                fail("Should have got an exception");
            } catch (ServerConnectivityException expected) {
            // do nothing
            } finally {
                logger.info(removeExpected);
            }
        }
        replacedertEquals(1, borrows);
        replacedertEquals(1, returns);
        replacedertEquals(1, invalidateConnections);
        replacedertEquals(1, serverCrashes);
    }

    @Test
    public void testExecuteOnAllQueueServers() {
        OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, null);
        exec.executeOnAllQueueServers(new Op() {

            @Override
            public Object attempt(Connection cnx) throws Exception {
                return "hello";
            }
        });
        replacedertEquals(0, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        replacedertEquals(1, getPrimary);
        replacedertEquals(1, getBackups);
        reset();
        queueManager.backups = 3;
        exec.executeOnAllQueueServers(new Op() {

            @Override
            public Object attempt(Connection cnx) throws Exception {
                throw new SocketTimeoutException();
            }
        });
        replacedertEquals(4, invalidateConnections);
        replacedertEquals(0, serverCrashes);
        replacedertEquals(1, getPrimary);
        replacedertEquals(1, getBackups);
        reset();
        queueManager.backups = 3;
        Object result = exec.executeOnQueuesAndReturnPrimaryResult(new Op() {

            int i = 0;

            @Override
            public Object attempt(Connection cnx) throws Exception {
                i++;
                if (i < 15) {
                    throw new IOException();
                }
                return "hello";
            }
        });
        replacedertEquals("hello", result);
        replacedertEquals(14, serverCrashes);
        replacedertEquals(14, invalidateConnections);
        replacedertEquals(12, getPrimary);
        replacedertEquals(1, getBackups);
    }

    @Test
    public void executeWithServerAffinityDoesNotChangeInitialRetryCountOfZero() {
        OpExecutorImpl opExecutor = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.clreplaced));
        Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.clreplaced);
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        opExecutor.setAffinityRetryCount(0);
        opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp);
        replacedertEquals(0, opExecutor.getAffinityRetryCount());
    }

    @Test
    public void executeWithServerAffinityWithNonZeroAffinityRetryCountWillNotSetToZero() {
        OpExecutorImpl opExecutor = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.clreplaced));
        Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.clreplaced);
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        opExecutor.setAffinityRetryCount(1);
        opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp);
        replacedertNotEquals(0, opExecutor.getAffinityRetryCount());
    }

    @Test
    public void executeWithServerAffinityWithServerConnectivityExceptionIncrementsRetryCountAndResetsToZero() {
        OpExecutorImpl opExecutor = spy(new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.clreplaced)));
        Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.clreplaced);
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        ServerConnectivityException serverConnectivityException = new ServerConnectivityException();
        doThrow(serverConnectivityException).when(opExecutor).executeOnServer(serverLocation, txSynchronizationOp, true, false);
        opExecutor.setupServerAffinity(true);
        when(((AbstractOp) txSynchronizationOp).getMessage()).thenReturn(mock(Message.clreplaced));
        opExecutor.setAffinityRetryCount(0);
        opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp);
        verify(opExecutor, times(1)).setAffinityRetryCount(1);
        replacedertEquals(0, opExecutor.getAffinityRetryCount());
    }

    @Test
    public void executeWithServerAffinityAndRetryCountGreaterThansTxRetryAttemptThrowsServerConnectivityException() {
        OpExecutorImpl opExecutor = spy(new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, -1, 10, cancelCriterion, mock(PoolImpl.clreplaced)));
        Op txSynchronizationOp = mock(TXSynchronizationOp.Impl.clreplaced);
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        ServerConnectivityException serverConnectivityException = new ServerConnectivityException();
        doThrow(serverConnectivityException).when(opExecutor).executeOnServer(serverLocation, txSynchronizationOp, true, false);
        opExecutor.setupServerAffinity(true);
        when(((AbstractOp) txSynchronizationOp).getMessage()).thenReturn(mock(Message.clreplaced));
        opExecutor.setAffinityRetryCount(opExecutor.TX_RETRY_ATTEMPT + 1);
        replacedertThatThrownBy(() -> opExecutor.executeWithServerAffinity(serverLocation, txSynchronizationOp)).isSameAs(serverConnectivityException);
    }

    private clreplaced DummyManager implements ConnectionManager {

        protected int numServers = Integer.MAX_VALUE;

        private int currentServer = 0;

        public DummyManager() {
        }

        @Override
        public void emergencyClose() {
        }

        @Override
        public Connection borrowConnection(long aquireTimeout) {
            borrows++;
            return new DummyConnection(new ServerLocation("localhost", currentServer++ % numServers));
        }

        @Override
        public Connection borrowConnection(ServerLocation server, boolean onlyUseExistingCnx) {
            borrows++;
            return new DummyConnection(server);
        }

        @Override
        public void close(boolean keepAlive) {
        }

        @Override
        public void returnConnection(Connection connection) {
            returns++;
        }

        @Override
        public void returnConnection(Connection connection, boolean accessed) {
            returns++;
        }

        @Override
        public void start(ScheduledExecutorService backgroundProcessor) {
        }

        @Override
        public Connection exchangeConnection(Connection conn, Set<ServerLocation> excludedServers) {
            if (excludedServers.size() >= numServers) {
                throw new NoAvailableServersException();
            }
            exchanges++;
            return new DummyConnection(new ServerLocation("localhost", currentServer++ % numServers));
        }

        @Override
        public int getConnectionCount() {
            return 0;
        }
    }

    private clreplaced DummyConnection implements Connection {

        private ServerLocation server;

        public DummyConnection(ServerLocation serverLocation) {
            this.server = serverLocation;
        }

        @Override
        public void close(boolean keepAlive) throws Exception {
        }

        @Override
        public void destroy() {
            invalidateConnections++;
        }

        @Override
        public boolean isDestroyed() {
            return false;
        }

        @Override
        public ByteBuffer getCommBuffer() {
            return null;
        }

        @Override
        public ServerLocation getServer() {
            return server;
        }

        @Override
        public Socket getSocket() {
            return null;
        }

        @Override
        public ConnectionStats getStats() {
            return null;
        }

        @Override
        public int getDistributedSystemId() {
            return 0;
        }

        @Override
        public Endpoint getEndpoint() {
            return new Endpoint(null, null, null, null, null);
        }

        @Override
        public ServerQueueStatus getQueueStatus() {
            return null;
        }

        @Override
        public Object execute(Op op) throws Exception {
            return op.attempt(this);
        }

        @Override
        public void emergencyClose() {
        }

        @Override
        public short getWanSiteVersion() {
            return -1;
        }

        @Override
        public void setWanSiteVersion(short wanSiteVersion) {
        }

        @Override
        public InputStream getInputStream() {
            return null;
        }

        @Override
        public OutputStream getOutputStream() {
            return null;
        }

        @Override
        public void setConnectionID(long id) {
        }

        @Override
        public long getConnectionID() {
            return 0;
        }
    }

    private clreplaced DummyEndpointManager implements EndpointManager {

        @Override
        public void addListener(EndpointListener listener) {
        }

        @Override
        public void close() {
        }

        @Override
        public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) {
            return null;
        }

        @Override
        public Map getEndpointMap() {
            return null;
        }

        @Override
        public void removeListener(EndpointListener listener) {
        }

        @Override
        public void serverCrashed(Endpoint endpoint) {
            serverCrashes++;
        }

        @Override
        public int getConnectedServerCount() {
            return 0;
        }

        @Override
        public Map getAllStats() {
            return null;
        }

        @Override
        public String getPoolName() {
            return null;
        }
    }

    private clreplaced DummyQueueManager implements QueueManager {

        int backups = 0;

        int currentServer = 0;

        @Override
        public QueueConnections getAllConnectionsNoWait() {
            return getAllConnections();
        }

        @Override
        public void emergencyClose() {
        }

        @Override
        public QueueConnections getAllConnections() {
            return new QueueConnections() {

                @Override
                public List getBackups() {
                    getBackups++;
                    ArrayList result = new ArrayList(backups);
                    for (int i = 0; i < backups; i++) {
                        result.add(new DummyConnection(new ServerLocation("localhost", currentServer++)));
                    }
                    return result;
                }

                @Override
                public Connection getPrimary() {
                    getPrimary++;
                    return new DummyConnection(new ServerLocation("localhost", currentServer++));
                }

                @Override
                public QueueConnectionImpl getConnection(Endpoint ep) {
                    return null;
                }
            };
        }

        @Override
        public void close(boolean keepAlive) {
        }

        @Override
        public void start(ScheduledExecutorService background) {
        }

        @Override
        public QueueState getState() {
            return null;
        }

        @Override
        public InternalPool getPool() {
            return null;
        }

        @Override
        public void readyForEvents(InternalDistributedSystem system) {
        }

        @Override
        public InternalLogWriter getSecurityLogger() {
            return null;
        }

        @Override
        public void checkEndpoint(ClientUpdater qc, Endpoint endpoint) {
        }
    }
}

19 View Complete Implementation : MembershipChangeListenerFactory.java
Copyright Apache License 2.0
Author : apache
public static BooleanSupplier cancelCondition(InternalPersistenceAdvisor persistenceAdvisor, CancelCriterion cancelCriterion) {
    return () -> {
        persistenceAdvisor.checkInterruptedByShutdownAll();
        cancelCriterion.checkCancelInProgress(null);
        return persistenceAdvisor.isClosed();
    };
}

19 View Complete Implementation : ConnectionTableTest.java
Copyright Apache License 2.0
Author : apache
@Before
public void initConnectionTable() throws Exception {
    InternalDistributedSystem system = mock(InternalDistributedSystem.clreplaced);
    when(system.isShareSockets()).thenReturn(false);
    DistributionManager dm = mock(DistributionManager.clreplaced);
    when(dm.getSystem()).thenReturn(system);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    DMStats dmStats = mock(DMStats.clreplaced);
    TCPConduit tcpConduit = mock(TCPConduit.clreplaced);
    when(tcpConduit.getDM()).thenReturn(dm);
    when(tcpConduit.getCancelCriterion()).thenReturn(cancelCriterion);
    when(tcpConduit.getStats()).thenReturn(dmStats);
    connection = mock(Connection.clreplaced);
    socket = mock(Socket.clreplaced);
    connectionTable = ConnectionTable.create(tcpConduit);
    factory = mock(PeerConnectionFactory.clreplaced);
    when(factory.createReceiver(connectionTable, socket)).thenReturn(connection);
}

19 View Complete Implementation : BeforeCompletion.java
Copyright Apache License 2.0
Author : apache
private void waitUntilFinished(CancelCriterion cancelCriterion) {
    while (!finished) {
        cancelCriterion.checkCancelInProgress(null);
        try {
            wait(1000);
        } catch (InterruptedException ignore) {
        // eat the interrupt and check for exit conditions
        }
    }
}

19 View Complete Implementation : ManagementListener.java
Copyright Apache License 2.0
Author : apache
/**
 * This Listener listens on various resource creation in GemFire and create/destroys GemFire
 * specific MBeans accordingly
 */
public clreplaced ManagementListener implements ResourceEventsListener {

    private final InternalDistributedSystem system;

    private final CancelCriterion cancelCriterion;

    /**
     * Adapter to co-ordinate between GemFire and Federation framework
     */
    private final ManagementAdapter adapter;

    /**
     * ReadWriteLock to protect between handling cache creation/removal vs other notifications
     */
    private final ReadWriteLock readWriteLock;

    public ManagementListener(InternalDistributedSystem system) {
        this(system.getCancelCriterion(), system, new ManagementAdapter(), new ReentrantReadWriteLock());
    }

    @VisibleForTesting
    ManagementListener(CancelCriterion cancelCriterion, InternalDistributedSystem system, ManagementAdapter adapter, ReadWriteLock readWriteLock) {
        this.cancelCriterion = cancelCriterion;
        this.system = system;
        this.adapter = adapter;
        this.readWriteLock = readWriteLock;
    }

    /**
     * Checks various conditions which might arise due to race condition for lock of
     * GemFireCacheImpl.clreplaced which is obtained while GemFireCacheImpl constructor, cache.close(),
     * DistributedSystem.disconnect().
     *
     * As ManagementService creation logic is called in cache.init() method it leaves a small window
     * of loosing the lock of GemFireCacheImpl.clreplaced
     *
     * These checks ensures that something unwanted has not happened during that small window
     *
     * @return true or false depending on the status of Cache and System
     */
    boolean shouldProceed(ResourceEvent event) {
        InternalDistributedSystem.getConnectedInstance();
        // CACHE_REMOVE is a special event. ForcedDisconnectException may raise this event.
        if (!system.isConnected() && !event.equals(ResourceEvent.CACHE_REMOVE)) {
            return false;
        }
        InternalCache currentCache = system.getCache();
        if (currentCache == null) {
            return false;
        }
        return !currentCache.isClosed();
    }

    /**
     * Handles various GFE resource life-cycle methods vis-a-vis Management and Monitoring
     *
     * It checks for race conditions cases by calling shouldProceed();
     *
     * @param event Management event for which invocation has happened
     * @param resource the GFE resource type
     */
    @Override
    public void handleEvent(ResourceEvent event, Object resource) {
        if (!shouldProceed(event)) {
            return;
        }
        try {
            if (event == ResourceEvent.CACHE_CREATE || event == ResourceEvent.CACHE_REMOVE) {
                readWriteLock.writeLock().lockInterruptibly();
            } else if (event != ResourceEvent.SYSTEM_ALERT) {
                readWriteLock.readLock().lockInterruptibly();
            }
        } catch (InterruptedException e) {
            // prefer CancelException if shutting down
            cancelCriterion.checkCancelInProgress(e);
            throw new RuntimeException(e);
        }
        try {
            switch(event) {
                case CACHE_CREATE:
                    InternalCache createdCache = (InternalCache) resource;
                    adapter.handleCacheCreation(createdCache);
                    break;
                case CACHE_REMOVE:
                    InternalCache removedCache = (InternalCache) resource;
                    adapter.handleCacheRemoval();
                    break;
                case REGION_CREATE:
                    Region createdRegion = (Region) resource;
                    adapter.handleRegionCreation(createdRegion);
                    break;
                case REGION_REMOVE:
                    Region removedRegion = (Region) resource;
                    adapter.handleRegionRemoval(removedRegion);
                    break;
                case DISKSTORE_CREATE:
                    DiskStore createdDisk = (DiskStore) resource;
                    adapter.handleDiskCreation(createdDisk);
                    break;
                case DISKSTORE_REMOVE:
                    DiskStore removedDisk = (DiskStore) resource;
                    adapter.handleDiskRemoval(removedDisk);
                    break;
                case GATEWAYRECEIVER_CREATE:
                    GatewayReceiver createdRecv = (GatewayReceiver) resource;
                    adapter.handleGatewayReceiverCreate(createdRecv);
                    break;
                case GATEWAYRECEIVER_DESTROY:
                    GatewayReceiver destroyedRecv = (GatewayReceiver) resource;
                    adapter.handleGatewayReceiverDestroy();
                    break;
                case GATEWAYRECEIVER_START:
                    GatewayReceiver startedRecv = (GatewayReceiver) resource;
                    adapter.handleGatewayReceiverStart(startedRecv);
                    break;
                case GATEWAYRECEIVER_STOP:
                    GatewayReceiver stoppededRecv = (GatewayReceiver) resource;
                    adapter.handleGatewayReceiverStop();
                    break;
                case GATEWAYSENDER_CREATE:
                    GatewaySender sender = (GatewaySender) resource;
                    adapter.handleGatewaySenderCreation(sender);
                    break;
                case GATEWAYSENDER_START:
                    GatewaySender startedSender = (GatewaySender) resource;
                    adapter.handleGatewaySenderStart(startedSender);
                    break;
                case GATEWAYSENDER_STOP:
                    GatewaySender stoppedSender = (GatewaySender) resource;
                    adapter.handleGatewaySenderStop(stoppedSender);
                    break;
                case GATEWAYSENDER_PAUSE:
                    GatewaySender pausedSender = (GatewaySender) resource;
                    adapter.handleGatewaySenderPaused(pausedSender);
                    break;
                case GATEWAYSENDER_RESUME:
                    GatewaySender resumedSender = (GatewaySender) resource;
                    adapter.handleGatewaySenderResumed(resumedSender);
                    break;
                case GATEWAYSENDER_REMOVE:
                    GatewaySender removedSender = (GatewaySender) resource;
                    adapter.handleGatewaySenderRemoved(removedSender);
                    break;
                case LOCKSERVICE_CREATE:
                    DLockService createdLockService = (DLockService) resource;
                    adapter.handleLockServiceCreation(createdLockService);
                    break;
                case LOCKSERVICE_REMOVE:
                    DLockService removedLockService = (DLockService) resource;
                    adapter.handleLockServiceRemoval(removedLockService);
                    break;
                case MANAGER_CREATE:
                    adapter.handleManagerCreation();
                    break;
                case MANAGER_START:
                    adapter.handleManagerStart();
                    break;
                case MANAGER_STOP:
                    adapter.handleManagerStop();
                    break;
                case ASYNCEVENTQUEUE_CREATE:
                    AsyncEventQueue queue = (AsyncEventQueue) resource;
                    adapter.handleAsyncEventQueueCreation(queue);
                    break;
                case ASYNCEVENTQUEUE_REMOVE:
                    AsyncEventQueue removedQueue = (AsyncEventQueue) resource;
                    adapter.handleAsyncEventQueueRemoval(removedQueue);
                    break;
                case SYSTEM_ALERT:
                    AlertDetails details = (AlertDetails) resource;
                    adapter.handleSystemNotification(details);
                    break;
                case CACHE_SERVER_START:
                    CacheServer startedServer = (CacheServer) resource;
                    adapter.handleCacheServerStart(startedServer);
                    break;
                case CACHE_SERVER_STOP:
                    CacheServer stoppedServer = (CacheServer) resource;
                    adapter.handleCacheServerStop(stoppedServer);
                    break;
                case LOCATOR_START:
                    Locator loc = (Locator) resource;
                    adapter.handleLocatorStart(loc);
                    break;
                case CACHE_SERVICE_CREATE:
                    CacheService service = (CacheService) resource;
                    adapter.handleCacheServiceCreation(service);
                    break;
                default:
                    break;
            }
        } finally {
            if (event == ResourceEvent.CACHE_CREATE || event == ResourceEvent.CACHE_REMOVE) {
                readWriteLock.writeLock().unlock();
            } else if (event != ResourceEvent.SYSTEM_ALERT) {
                readWriteLock.readLock().unlock();
            }
        }
    }
}

19 View Complete Implementation : AfterCompletion.java
Copyright Apache License 2.0
Author : apache
public synchronized void doOp(TXState txState, CancelCriterion cancelCriterion) {
    // there should be a transaction timeout that keeps this thread
    // from sitting around forever if the client goes away
    // The above was done by setting afterCompletionCancelled in txState
    // during cleanup. When client departed, the transaction/JTA
    // will be timed out and cleanup code will be executed.
    try {
        waitForExecuteOrCancel(cancelCriterion);
    } catch (RuntimeException | Error ignore) {
        action = Action.CANCEL;
    }
    started = true;
    logger.debug("executing afterCompletion notification");
    try {
        switch(action) {
            case CANCEL:
                txState.doCleanup();
                break;
            case COMMIT:
                txState.doAfterCompletionCommit();
                break;
            case ROLLBACK:
                txState.doAfterCompletionRollback();
                break;
        }
    } catch (RuntimeException exception) {
        this.exception = exception;
    } finally {
        logger.debug("afterCompletion notification completed");
        finished = true;
        notifyAll();
    }
}

19 View Complete Implementation : BeforeCompletionTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced BeforeCompletionTest {

    private BeforeCompletion beforeCompletion;

    private CancelCriterion cancelCriterion;

    private TXState txState;

    @Before
    public void setup() {
        beforeCompletion = new BeforeCompletion();
        cancelCriterion = mock(CancelCriterion.clreplaced);
        txState = mock(TXState.clreplaced);
    }

    @Test
    public void executeThrowsExceptionIfDoOpFailedWithException() {
        doThrow(new SynchronizationCommitConflictException("")).when(txState).doBeforeCompletion();
        beforeCompletion.doOp(txState);
        replacedertThatThrownBy(() -> beforeCompletion.execute(cancelCriterion)).isInstanceOf(SynchronizationCommitConflictException.clreplaced);
    }

    @Test
    public void executeThrowsTransactionDataNodeHasDepartedExceptionIfDoOpFailedWithCacheClosedException() {
        doThrow(new CacheClosedException("")).when(txState).doBeforeCompletion();
        beforeCompletion.doOp(txState);
        replacedertThatThrownBy(() -> beforeCompletion.execute(cancelCriterion)).isInstanceOf(TransactionDataNodeHasDepartedException.clreplaced);
    }

    @Test
    public void executeThrowsTransactionExceptionIfDoOpFailedWithRuntimeException() {
        doThrow(new RuntimeException("")).when(txState).doBeforeCompletion();
        beforeCompletion.doOp(txState);
        replacedertThatThrownBy(() -> beforeCompletion.execute(cancelCriterion)).isInstanceOf(TransactionException.clreplaced);
    }

    @Test
    public void doOpCallsDoBeforeCompletion() {
        beforeCompletion.doOp(txState);
        verify(txState).doBeforeCompletion();
    }

    @Test
    public void isStartedReturnsFalseIfNotExecuted() {
        replacedertThat(beforeCompletion.isStarted()).isFalse();
    }

    @Test
    public void isStartedReturnsTrueIfExecuted() {
        beforeCompletion.doOp(txState);
        beforeCompletion.execute(cancelCriterion);
        replacedertThat(beforeCompletion.isStarted()).isTrue();
    }

    @Test
    public void executeThrowsIfCancelCriterionThrows() {
        doThrow(new RuntimeException()).when(cancelCriterion).checkCancelInProgress(null);
        replacedertThatThrownBy(() -> beforeCompletion.execute(cancelCriterion)).isInstanceOf(RuntimeException.clreplaced);
    }

    @Test
    public void executeWaitsUntilDoOpFinish() {
        Thread thread = new Thread(() -> beforeCompletion.execute(cancelCriterion));
        thread.start();
        // give the thread a chance to get past the "finished" check by waiting until
        // checkCancelInProgress is called
        await().untilreplacederted(() -> verify(cancelCriterion, atLeastOnce()).checkCancelInProgress(null));
        beforeCompletion.doOp(txState);
        await().until(() -> !(thread.isAlive()));
    }
}

19 View Complete Implementation : ClusterElderManagerTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced ClusterElderManagerTest {

    private Distribution distribution;

    private CancelCriterion systemCancelCriterion;

    private InternalDistributedSystem system;

    private CancelCriterion cancelCriterion;

    private ClusterDistributionManager clusterDistributionManager;

    private InternalDistributedMember member0;

    private final InternalDistributedMember member1 = mock(InternalDistributedMember.clreplaced);

    private final InternalDistributedMember member2 = mock(InternalDistributedMember.clreplaced);

    @Rule
    public ConcurrencyRule concurrencyRule = new ConcurrencyRule();

    @Before
    public void before() {
        member0 = mock(InternalDistributedMember.clreplaced);
        clusterDistributionManager = mock(ClusterDistributionManager.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        system = mock(InternalDistributedSystem.clreplaced);
        systemCancelCriterion = mock(CancelCriterion.clreplaced);
        distribution = mock(Distribution.clreplaced);
        when(clusterDistributionManager.getCancelCriterion()).thenReturn(cancelCriterion);
        when(clusterDistributionManager.getSystem()).thenReturn(system);
        when(system.getCancelCriterion()).thenReturn(systemCancelCriterion);
        when(clusterDistributionManager.getDistribution()).thenReturn(distribution);
    }

    @Test
    public void getElderIdReturnsOldestMember() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
        replacedertThat(clusterElderManager.getElderId()).isEqualTo(member1);
    }

    @Test
    public void getElderIdWithNoMembers() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList());
        replacedertThat(clusterElderManager.getElderId()).isNull();
    }

    @Test
    public void getElderIdIgnoresAdminMembers() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(member1.getVmKind()).thenReturn(ClusterDistributionManager.ADMIN_ONLY_DM_TYPE);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
        replacedertThat(clusterElderManager.getElderId()).isEqualTo(member2);
    }

    @Test
    public void getElderIdIgnoresSurpriseMembers() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(distribution.isSurpriseMember(eq(member1))).thenReturn(true);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
        replacedertThat(clusterElderManager.getElderId()).isEqualTo(member2);
    }

    @Test
    public void isElderIfOldestMember() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
        when(clusterDistributionManager.getId()).thenReturn(member0);
        replacedertThat(clusterElderManager.isElder()).isTrue();
    }

    @Test
    public void isNotElderIfOldestMember() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        when(clusterDistributionManager.getId()).thenReturn(member0);
        replacedertThat(clusterElderManager.isElder()).isFalse();
    }

    @Test
    public void waitForElderReturnsTrueIfAnotherMemberIsElder() throws InterruptedException {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        replacedertThat(clusterElderManager.waitForElder(member1)).isTrue();
    }

    @Test
    public void waitForElderReturnsFalseIfWeAreElder() throws InterruptedException {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.isCurrentMember(eq(member1))).thenReturn(true);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
        replacedertThat(clusterElderManager.waitForElder(member1)).isFalse();
    }

    @Test
    public void waitForElderReturnsFalseIfDesiredElderIsNotACurrentMember() throws InterruptedException {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member2, member0, member1));
        replacedertThat(clusterElderManager.waitForElder(member1)).isFalse();
    }

    @Test
    public void waitForElderWaits() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
        when(clusterDistributionManager.isCloseInProgress()).thenReturn(false);
        replacedertThatInterruptableRunnableWaits(() -> {
            try {
                clusterElderManager.waitForElder(member0);
            } catch (InterruptedException e) {
            }
        });
    }

    @Test
    public void waitForElderDoesNotWaitIfShuttingDown() throws InterruptedException {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
        when(clusterDistributionManager.isCloseInProgress()).thenReturn(true);
        replacedertThat(clusterElderManager.waitForElder(member0)).isFalse();
    }

    @Test
    public void waitForElderStopsWaitingWhenUpdated() {
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
        AtomicReference<List<InternalDistributedMember>> currentMembers = new AtomicReference<>(Arrays.asList(member1, member0));
        when(clusterDistributionManager.getViewMembers()).then(invocation -> currentMembers.get());
        AtomicReference<MembershipListener> membershipListener = new AtomicReference<>();
        doAnswer(invocation -> {
            membershipListener.set(invocation.getArgument(0));
            return null;
        }).when(clusterDistributionManager).addMembershipListener(any());
        Callable<Boolean> waitForElder = () -> clusterElderManager.waitForElder(member0);
        Callable<Void> updateMembershipView = () -> {
            // Wait for membership listener to be added
            await().until(() -> membershipListener.get() != null);
            currentMembers.set(Arrays.asList(member0));
            membershipListener.get().memberDeparted(clusterDistributionManager, member1, true);
            return null;
        };
        concurrencyRule.add(waitForElder).expectValue(true);
        concurrencyRule.add(updateMembershipView);
        concurrencyRule.executeInParallel();
        replacedertThat(clusterElderManager.getElderId()).isEqualTo(member0);
    }

    @Test
    public void getElderStateAsElder() throws InterruptedException {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ElderState elderState = mock(ElderState.clreplaced);
        when(elderStateSupplier.get()).thenReturn(elderState);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
        replacedertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
        verify(elderStateSupplier, times(1)).get();
    }

    @Test
    public void getElderStateGetsBuiltOnceAsElder() throws InterruptedException {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ElderState elderState = mock(ElderState.clreplaced);
        when(elderStateSupplier.get()).thenReturn(elderState);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
        replacedertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
        replacedertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
        // Make sure that we only create the elder state once
        verify(elderStateSupplier, times(1)).get();
    }

    @Test
    public void getElderStateFromMultipleThreadsAsElder() {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ElderState elderState = mock(ElderState.clreplaced);
        when(elderStateSupplier.get()).thenReturn(elderState);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
        Callable<ElderState> callable = () -> clusterElderManager.getElderState(false);
        concurrencyRule.add(callable).expectValue(elderState);
        concurrencyRule.add(callable).expectValue(elderState);
        concurrencyRule.executeInParallel();
        // Make sure that we only create the elder state once
        verify(elderStateSupplier, times(1)).get();
    }

    @Test
    public void getElderStateNotAsElder() throws InterruptedException {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        replacedertThat(clusterElderManager.getElderState(false)).isEqualTo(null);
        verify(elderStateSupplier, times(0)).get();
    }

    @Test
    public void getElderStateWaitsToBecomeElder() {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
        when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
        replacedertThatInterruptableRunnableWaits(() -> {
            try {
                clusterElderManager.getElderState(true);
            } catch (InterruptedException e) {
            }
        });
        verify(elderStateSupplier, times(0)).get();
    }

    private void replacedertThatInterruptableRunnableWaits(Runnable runnable) {
        Thread waitThread = new Thread(runnable);
        waitThread.start();
        EnumSet<Thread.State> waitingStates = EnumSet.of(Thread.State.WAITING, Thread.State.TIMED_WAITING);
        try {
            await().until(() -> waitingStates.contains(waitThread.getState()));
        } finally {
            waitThread.interrupt();
            await().until(() -> !waitThread.isAlive());
        }
    }

    @Test
    public void getElderStateReturnsElderStateIfWaitsToBecomeElder() throws Exception {
        Supplier<ElderState> elderStateSupplier = mock(Supplier.clreplaced);
        ElderState elderState = mock(ElderState.clreplaced);
        when(elderStateSupplier.get()).thenReturn(elderState);
        ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
        when(clusterDistributionManager.getId()).thenReturn(member0);
        when(clusterDistributionManager.isCloseInProgress()).thenReturn(true);
        when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1));
        replacedertThat(clusterElderManager.getElderState(true)).isEqualTo(elderState);
    }
}

19 View Complete Implementation : SimpleStatSamplerIntegrationTest.java
Copyright Apache License 2.0
Author : apache
private void initStatisticsFactory() {
    CancelCriterion stopper = new CancelCriterion() {

        @Override
        public String cancelInProgress() {
            return null;
        }

        @Override
        public RuntimeException generateCancelledException(Throwable e) {
            return null;
        }
    };
    this.statisticsFactory = new LocalStatisticsFactory(stopper);
}

19 View Complete Implementation : PersistenceInitialImageAdvisorTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void propagatesException_ifCancelInProgress() {
    persistenceInitialImageAdvisor = persistenceInitialImageAdvisorWithDiskImage();
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(cacheDistributionAdvisor.getAdvisee().getCancelCriterion()).thenReturn(cancelCriterion);
    doThrow(new CacheClosedException("test")).when(cancelCriterion).checkCancelInProgress(any());
    Throwable thrown = catchThrowable(() -> persistenceInitialImageAdvisor.getAdvice(null));
    replacedertThat(thrown).isInstanceOf(CacheClosedException.clreplaced);
}

19 View Complete Implementation : DiskRegion.java
Copyright Apache License 2.0
Author : apache
/**
 * Represents a (disk-based) persistent store for region data. Used for both persistent recoverable
 * regions and overflow-only regions.
 *
 * @since GemFire 3.2
 */
public clreplaced DiskRegion extends AbstractDiskRegion {

    public static final long INVALID_ID = DiskStoreImpl.INVALID_ID;

    // //////////////////// Instance Fields ///////////////////////
    /**
     * The stats for this region
     */
    private final DiskRegionStats stats;

    /**
     * True if overflow is enabled on this region
     */
    final boolean overflowEnabled;

    /**
     * boolean to determine if region is closed*
     */
    private volatile boolean isRegionClosed = false;

    private final boolean isSync;

    private final String name;

    private final CancelCriterion cancel;

    private final DiskExceptionHandler exceptionHandler;

    // changed rwLock to lock to fix bug 41390
    // private final StoppableReentrantLock lock;
    private final StoppableReentrantReadWriteLock rwLock;

    /**
     * Creates a new <code>DiskRegion</code> that access disk on behalf of the given region.
     */
    protected DiskRegion(DiskStoreImpl ds, String name, boolean isBucket, boolean isPersistBackup, boolean overflowEnabled, boolean isSynchronous, DiskRegionStats stats, CancelCriterion cancel, DiskExceptionHandler exceptionHandler, RegionAttributes ra, EnumSet<DiskRegionFlag> flags, String parreplacedionName, int startingBucketId, String compressorClreplacedName, boolean offHeap) {
        super(ds, name);
        if (this.getParreplacedionName() != null) {
            // I think this code is saying to prefer the recovered parreplacedionName and startingBucketId.
            // Only use the preplaceded in values of these if we have not already recovered this region from
            // disk.
            if (this.getStartingBucketId() != startingBucketId || !this.getParreplacedionName().equals(parreplacedionName)) {
                parreplacedionName = this.getParreplacedionName();
                startingBucketId = this.getStartingBucketId();
            }
        }
        if (isRecreated() && isBackup() && !isPersistBackup) {
            // We recovered a persistent region from disk and tried
            // to create an overflow only region of the same name on the same disk store.
            throw new IllegalStateException("The region \"" + name + "\" has been persisted to disk so it can not be recreated on the same disk store without persistence. Either destroy the persistent region, recreate it as overflow and persistent, or create the overflow only region on a different disk store.");
        }
        if (isRecreated() && isBucket != isBucket()) {
            if (isBucket()) {
                throw new IllegalStateException("The region \"" + name + "\" has been persisted to disk as a parreplacedion region bucket but is not being recreated as a bucket. This should not be possible.");
            } else {
                throw new IllegalStateException("The region \"" + name + "\" has not been persisted to disk as a parreplacedion region bucket but is now being recreated as a bucket. This should not be possible.");
            }
        }
        if (isRecreated() && !flags.equals(getFlags())) {
            throw new IllegalStateException("The region \"" + name + "\" has changed it's concurrency enabled setting. Old setting " + getFlags() + ", new setting " + flags);
        }
        setBackup(isPersistBackup);
        // EvictionAttributes ea = region.getAttributes().getEvictionAttributes();
        // this.overflowEnabled = ea != null && ea.getAction().isOverflowToDisk();
        this.overflowEnabled = overflowEnabled;
        // if (region instanceof BucketRegion) {
        // this.stats = internalRegionArgs.getParreplacedionedRegion()
        // .getDiskRegionStats();
        // }
        // else {
        // this.stats = new DiskRegionStats(factory, name);
        // }
        this.stats = stats;
        this.name = name;
        // start simple init
        this.isSync = isSynchronous;
        this.cancel = cancel;
        this.exceptionHandler = exceptionHandler;
        // this.lock = new StoppableReentrantLock(ds.getCancelCriterion());
        this.rwLock = new StoppableReentrantReadWriteLock(ds.getCancelCriterion());
        if (ra != null) {
            byte raLruAlgorithm = (byte) (ra.getEvictionAttributes().getAlgorithm().getValue());
            byte raLruAction = (byte) (ra.getEvictionAttributes().getAction().getValue());
            int raLruLimit = ra.getEvictionAttributes().getMaximum();
            if (isRecreated()) {
                // check to see if recovered config differs from current config
                if (raLruAlgorithm != getLruAlgorithm() || raLruAction != getLruAction() || raLruLimit != getLruLimit() || ra.getConcurrencyLevel() != getConcurrencyLevel() || ra.getInitialCapacity() != getInitialCapacity() || ra.getLoadFactor() != getLoadFactor() || ra.getStatisticsEnabled() != getStatisticsEnabled() || offHeap != getOffHeap() || !hreplacedameCompressor(ra)) {
                    if (getRecoveredEntryMap() != null) {
                        getRecoveredEntryMap().lruCloseStats();
                    }
                    setEntriesMapIncompatible(true);
                    setConfigChanged(true);
                }
            }
            setConfig(raLruAlgorithm, raLruAction, raLruLimit, ra.getConcurrencyLevel(), ra.getInitialCapacity(), ra.getLoadFactor(), ra.getStatisticsEnabled(), isBucket, flags, parreplacedionName, startingBucketId, compressorClreplacedName, offHeap);
        }
        if (!isBucket) {
            // Bucket should create data storage only when the actual bucket
            // is created.
            createDataStorage();
        }
    }

    static DiskRegion create(DiskStoreImpl dsi, String name, boolean isBucket, boolean isPersistBackup, boolean overflowEnabled, boolean isSynchronous, DiskRegionStats stats, CancelCriterion cancel, DiskExceptionHandler exceptionHandler, RegionAttributes ra, EnumSet<DiskRegionFlag> flags, String parreplacedionName, int startingBucketId, Compressor compressor, boolean offHeap) {
        return dsi.getDiskInitFile().createDiskRegion(dsi, name, isBucket, isPersistBackup, overflowEnabled, isSynchronous, stats, cancel, exceptionHandler, ra, flags, parreplacedionName, startingBucketId, compressor, offHeap);
    }

    @Override
    public CancelCriterion getCancelCriterion() {
        return cancel;
    }

    public DiskExceptionHandler getExceptionHandler() {
        return exceptionHandler;
    }

    // //////////////////// Instance Methods //////////////////////
    private boolean hreplacedameCompressor(final RegionAttributes<?, ?> ra) {
        Compressor raCompressor = ra.getCompressor();
        if (raCompressor == null) {
            return Strings.isNullOrEmpty(getCompressorClreplacedName()) ? true : false;
        }
        return raCompressor.getClreplaced().getName().equals(getCompressorClreplacedName());
    }

    protected void register() {
        getDiskStore().addDiskRegion(this);
    }

    @Override
    public String getName() {
        return this.name;
    }

    /**
     * Returns the <code>DiskRegionStats</code> for this disk region
     */
    public DiskRegionStats getStats() {
        return this.stats;
    }

    @Override
    public void incNumOverflowBytesOnDisk(long delta) {
        getStats().incNumOverflowBytesOnDisk(delta);
        super.incNumOverflowBytesOnDisk(delta);
    }

    @Override
    public void incNumOverflowOnDisk(long delta) {
        getStats().incNumOverflowOnDisk(delta);
        super.incNumOverflowOnDisk(delta);
    }

    @Override
    public void incNumEntriesInVM(long delta) {
        getStats().incNumEntriesInVM(delta);
        super.incNumEntriesInVM(delta);
    }

    /**
     * Initializes the contents of the region that owns this disk region. Currently the only time this
     * method does any work is when backup is true and recovery data was discovered when this disk
     * region was created.
     */
    void initializeOwner(LocalRegion drs) {
        getDiskStore().initializeOwner(drs);
    }

    void finishInitializeOwner(LocalRegion drs, GIIStatus giiStatus) {
        if (isReadyForRecovery()) {
            // this.scheduleCompaction();
            if (GIIStatus.didFullGII(giiStatus)) {
                destroyRemainingRecoveredEntries(drs);
            } else if (GIIStatus.didDeltaGII(giiStatus)) {
            // TODO: not sure if we should destroy old tombstones for deltaGII
            } else if (getRegionVersionVector() != null) {
                destroyOldTomstones(drs);
            }
            releaseRecoveryData();
        }
        if (isBackup() && !this.isRegionClosed() && !this.getRVVTrusted()) {
            if (!GIIStatus.didGII(giiStatus)) {
                // If we did not do a GII, but we are still recovering using
                // an untrusted RVV, that means that the RVV may not reflect
                // what is in the region. We need to fix the RVV before
                // we mark the RVV as trusted and allow the region to recover.
                drs.repairRVV();
            }
            writeRVV(null, true);
            writeRVVGC((LocalRegion) drs);
        }
    }

    private void destroyOldTomstones(final DiskRecoveryStore drs) {
        // iterate over all region entries in drs
        drs.foreachRegionEntry(new RegionEntryCallback() {

            @Override
            public void handleRegionEntry(RegionEntry regionEntry) {
                DiskEntry de = (DiskEntry) regionEntry;
                synchronized (de) {
                    DiskId id = de.getDiskId();
                    if (id != null && regionEntry.isTombstone()) {
                        VersionStamp stamp = regionEntry.getVersionStamp();
                        if (getRegionVersionVector().isTombstoneTooOld(stamp.getMemberID(), stamp.getRegionVersion())) {
                            drs.destroyRecoveredEntry(de.getKey());
                        }
                    }
                }
            }
        });
    }

    private void destroyRemainingRecoveredEntries(final DiskRecoveryStore drs) {
        // iterate over all region entries in drs
        drs.foreachRegionEntry(new RegionEntryCallback() {

            @Override
            public void handleRegionEntry(RegionEntry regionEntry) {
                DiskEntry de = (DiskEntry) regionEntry;
                synchronized (de) {
                    DiskId id = de.getDiskId();
                    if (id != null) {
                        if (EntryBits.isRecoveredFromDisk(id.getUserBits())) {
                            drs.destroyRecoveredEntry(de.getKey());
                        }
                    }
                }
            }
        });
    }

    /**
     * Remark all entries as "Recovered From Disk" in preparation for a new GII. This will allow us to
     * destroy those entries if we do not receive them as part of a new GII.
     */
    public void resetRecoveredEntries(final DiskRecoveryStore drs) {
        // iterate over all region entries in drs
        drs.foreachRegionEntry(new RegionEntryCallback() {

            @Override
            public void handleRegionEntry(RegionEntry regionEntry) {
                DiskEntry de = (DiskEntry) regionEntry;
                synchronized (de) {
                    DiskId id = de.getDiskId();
                    if (id != null) {
                        id.setRecoveredFromDisk(true);
                    }
                }
            }
        });
    }

    public boolean isOverflowEnabled() {
        return this.overflowEnabled;
    }

    /**
     * Stores a key/value pair from a region entry on disk. Updates all of the necessary
     * {@linkplain DiskRegionStats statistics}and invokes {@link Oplog#create}or {@link Oplog#modify}.
     *
     * @param entry The entry which is going to be written to disk
     * @throws RegionClearedException If a clear operation completed before the put operation
     *         completed successfully, resulting in the put operation to abort.
     * @throws IllegalArgumentException If <code>id</code> is less than zero
     */
    public void put(DiskEntry entry, InternalRegion region, ValueWrapper value, boolean async) throws RegionClearedException {
        getDiskStore().put(region, entry, value, async);
    }

    /**
     * Returns the value of the key/value pair with the given diskId. Updates all of the necessary
     * {@linkplain DiskRegionStats statistics}
     *
     * @see #getBytesAndBitsWithoutLock(DiskId, boolean, boolean)
     */
    Object get(DiskId id) {
        return getDiskStore().get(this, id);
    }

    /**
     * Gets the Object from the OpLog . It can be invoked from OpLog , if by the time a get operation
     * reaches the OpLog, the entry gets compacted or if we allow concurrent put & get operations. It
     * will also minimize the synch lock on DiskId
     *
     * @param id DiskId object for the entry
     * @return value of the entry
     */
    BytesAndBits getBytesAndBitsWithoutLock(DiskId id, boolean faultIn, boolean bitOnly) {
        return getDiskStore().getBytesAndBitsWithoutLock(this, id, faultIn, bitOnly);
    }

    /**
     * @since GemFire 3.2.1
     */
    BytesAndBits getBytesAndBits(DiskId id) {
        return getBytesAndBits(id, true);
    }

    public BytesAndBits getBytesAndBits(DiskId id, boolean faultingIn) {
        return getDiskStore().getBytesAndBits(this, id, faultingIn);
    }

    /**
     * @since GemFire 3.2.1
     */
    byte getBits(DiskId id) {
        return getDiskStore().getBits(this, id);
    }

    /**
     * Asif: THIS SHOULD ONLY BE USED FOR TESTING PURPOSES AS IT IS NOT THREAD SAFE
     *
     * Returns the object stored on disk with the given id. This method is used for testing purposes
     * only. As such, it bypreplacedes the buffer and goes directly to the disk. This is not a thread safe
     * function , in the sense, it is possible that by the time the OpLog is queried , data might move
     * HTree with the oplog being destroyed
     *
     * @return null if entry has nothing stored on disk (id == INVALID_ID)
     * @throws IllegalArgumentException If <code>id</code> is less than zero, no action is taken.
     */
    public Object getNoBuffer(DiskId id) {
        return getDiskStore().getNoBuffer(this, id);
    }

    /**
     * Removes the key/value pair with the given id on disk.
     *
     * @throws RegionClearedException If a clear operation completed before the put operation
     *         completed successfully, resulting in the put operation to abort.
     * @throws IllegalArgumentException If <code>id</code> is {@linkplain #INVALID_ID invalid}or is
     *         less than zero, no action is taken.
     */
    void remove(LocalRegion region, DiskEntry entry) throws RegionClearedException {
        getDiskStore().remove(region, entry, false, false);
    }

    public void remove(InternalRegion region, DiskEntry entry, boolean async, boolean isClear) throws RegionClearedException {
        getDiskStore().remove(region, entry, async, isClear);
    }

    // //////////////////// Access Methods for DiskRegionSegment ///////////////
    public void forceRolling() {
        getDiskStore().forceRolling(this);
    }

    public boolean forceCompaction() {
        return getDiskStore().forceCompaction(this);
    }

    /**
     * Get serialized form of data off the disk
     *
     * @since GemFire 5.7
     */
    public Object getSerializedData(DiskId id) {
        return getDiskStore().getSerializedData(this, id);
    }

    /**
     * @since GemFire prPersistSprint1
     */
    public void scheduleAsyncWrite(AsyncDiskEntry ade) {
        getDiskStore().scheduleAsyncWrite(ade);
    }

    /**
     * @since GemFire prPersistSprint1
     */
    public void unscheduleAsyncWrite(DiskId did) {
        getDiskStore().unscheduleAsyncWrite(did);
    }

    public boolean testWaitForAsyncFlusherThread(int waitMs) {
        return getDiskStore().testWaitForAsyncFlusherThread(waitMs);
    }

    /**
     * force a flush but do it async (don't wait for the flush to complete).
     */
    public void asynchForceFlush() {
        getDiskStore().asynchForceFlush();
    }

    public void forceFlush() {
        getDiskStore().forceFlush();
    }

    /**
     * The diskStats are at PR level.Hence if the region is a bucket region, the stats should not be
     * closed, but the figures of entriesInVM and overflowToDisk contributed by that bucket need to be
     * removed from the stats .
     */
    private void statsClose(LocalRegion region) {
        if (region instanceof BucketRegion) {
            // region.getGemFireCache().getLogger().info("DEBUG statsClose br= " + region.getFullPath()
            // + " inVm=" + owner.getNumEntriesInVM()
            // + " onDisk=" + owner.getNumOverflowOnDisk());
            statsClear(region);
        } else {
            // region.getGemFireCache().getLogger().info("DEBUG statsClose r=" + region.getFullPath());
            this.stats.close();
        }
    }

    void statsClear(LocalRegion region) {
        if (region instanceof BucketRegion) {
            BucketRegion owner = (BucketRegion) region;
            long curInVM = owner.getNumEntriesInVM() * -1;
            long curOnDisk = owner.getNumOverflowOnDisk() * -1;
            long curOnDiskBytes = owner.getNumOverflowBytesOnDisk() * -1;
            incNumEntriesInVM(curInVM);
            incNumOverflowOnDisk(curOnDisk);
            incNumOverflowBytesOnDisk(curOnDiskBytes);
            owner.incNumEntriesInVM(curInVM);
            owner.incNumOverflowOnDisk(curOnDisk);
            owner.incNumOverflowBytesOnDisk(curOnDiskBytes);
        } else {
            // set them both to zero
            incNumEntriesInVM(getNumEntriesInVM() * -1);
            incNumOverflowOnDisk(getNumOverflowOnDisk() * -1);
            incNumOverflowBytesOnDisk(getNumOverflowBytesOnDisk() * -1);
        }
    }

    /**
     * Returns true if the state of the specified entry was recovered from disk. If so it will also
     * set it to no longer be recovered.
     *
     * @since GemFire prPersistSprint1
     */
    public boolean testIsRecoveredAndClear(RegionEntry re) {
        DiskEntry de = (DiskEntry) re;
        return testIsRecoveredAndClear(de.getDiskId());
    }

    public boolean testIsRecoveredAndClear(DiskId id) {
        if (!isReadyForRecovery())
            return false;
        if (id == null)
            return false;
        synchronized (id) {
            byte bits = id.getUserBits();
            if (EntryBits.isRecoveredFromDisk(bits)) {
                bits = EntryBits.setRecoveredFromDisk(bits, false);
                id.setUserBits(bits);
                return true;
            }
        }
        return false;
    }

    /**
     * returns the active child
     */
    Oplog testHook_getChild() {
        return getDiskStore().getPersistentOplogs().getChild();
    }

    /**
     * For Testing *
     */
    // void addToOplogSet(long oplogID, File opFile, DirectoryHolder dirHolder) {
    // getDiskStore().addToOplogSet(oplogID, opFile, dirHolder);
    // }
    // /** For Testing * */
    // void setIsRecovering(boolean isRecovering) {
    // this.isRecovering = isRecovering;
    // }
    public void flushForTesting() {
        getDiskStore().flushForTesting();
    }

    public void pauseFlusherForTesting() {
        getDiskStore().pauseFlusherForTesting();
    }

    @Override
    public boolean isSync() {
        return this.isSync;
    }

    /**
     * Stops the compactor without taking a write lock. Then it invokes appropriate methods of super &
     * current clreplaced to clear the Oplogs & once done restarts the compactor.
     */
    void clear(LocalRegion region, RegionVersionVector rvv) {
        getDiskStore().clear(region, this, rvv);
    }

    /**
     * stops the compactor outside the write lock. Once stopped then it proceeds to close the current
     * * old oplogs
     */
    void close(LocalRegion region) {
        try {
            getDiskStore().close(region, this, false);
        } finally {
            statsClose(region);
        }
    }

    /**
     * stops the compactor outside the write lock. Once stopped then it proceeds to close the current
     * * old oplogs
     */
    void close(LocalRegion region, boolean closeDataOnly) {
        try {
            getDiskStore().close(region, this, closeDataOnly);
        } finally {
            statsClose(region);
        }
    }

    @Override
    void beginDestroyRegion(LocalRegion region) {
        try {
            getDiskStore().beginDestroyRegion(region, this);
        } finally {
            statsClose(region);
        }
    }

    private final AtomicInteger clearCount = new AtomicInteger();

    /**
     * ThreadLocal to be used for maintaining consistency during clear*
     */
    private final ThreadLocal<Integer> childReference = new ThreadLocal<Integer>();

    void incClearCount() {
        this.clearCount.incrementAndGet();
    }

    @Override
    public boolean didClearCountChange() {
        Integer i = childReference.get();
        boolean result = i != null && i.intValue() != this.clearCount.get();
        // // now that we get a readLock it should not be possible for the lock to change
        // replacedert !result;
        return result;
    }

    public void removeClearCountReference() {
        // releaseReadLock();
        // TODO: After Java 1.5 transition use .remove
        childReference.set(null);
    }

    public void setClearCountReference() {
        // acquireReadLock();
        if (LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER) {
            CacheObserverHolder.getInstance().beforeSettingDiskRef();
            childReference.set(Integer.valueOf(this.clearCount.get()));
            CacheObserverHolder.getInstance().afterSettingDiskRef();
        } else {
            childReference.set(Integer.valueOf(this.clearCount.get()));
        }
    }

    /**
     * Note that this is no longer implemented by getting a write lock but instead locks the same lock
     * that acquireReadLock does.
     */
    void acquireWriteLock() {
        this.rwLock.writeLock().lock();
    // basicAcquireLock();
    }

    /**
     * Note that this is no longer implemented by getting a read lock but instead locks the same lock
     * that acquireWriteLock does.
     */
    void releaseWriteLock() {
        this.rwLock.writeLock().unlock();
    // this.lock.unlock();
    }

    @Override
    public void acquireReadLock() {
        getDiskStore().acquireReadLock(this);
    }

    @Override
    public void releaseReadLock() {
        getDiskStore().releaseReadLock(this);
    }

    void basicAcquireReadLock() {
        this.rwLock.readLock().lock();
    // basicAcquireLock();
    }

    void basicReleaseReadLock() {
        this.rwLock.readLock().unlock();
    // basicReleaseLock();
    }

    /*
   * private void basicAcquireLock() { this.lock.lock(); } private void basicReleaseLock() { // It
   * is replacedumed that releasing the lock will not throw any // ShutdownException this.lock.unlock();
   * }
   */
    boolean isCompactionPossible() {
        return getDiskStore().isCompactionPossible();
    }

    void cleanupFailedInitialization(LocalRegion region) {
        if (regionPreviouslyHostedData()) {
            close(region, isBucket());
        } else {
            destroyPartiallyInitializedRegion(region);
        }
    }

    void prepareForClose(LocalRegion region) {
        getDiskStore().prepareForClose(region, this);
    }

    @Override
    public boolean isRegionClosed() {
        return this.isRegionClosed;
    }

    void setRegionClosed(boolean v) {
        this.isRegionClosed = v;
    }

    // test hook
    public void forceIFCompaction() {
        getDiskStore().forceIFCompaction();
    }

    // unit test access
    void addToBeCompacted(Oplog oplog) {
        getOplogSet().addToBeCompacted(oplog);
    }

    CompactableOplog[] getOplogToBeCompacted() {
        return getDiskStore().getOplogToBeCompacted();
    }

    Oplog removeOplog(long id) {
        return getOplogSet().removeOplog(id);
    }

    DirectoryHolder getNextDir() {
        return getOplogSet().getNextDir();
    }

    long newOplogEntryId() {
        return getOplogSet().newOplogEntryId();
    }

    void setChild(Oplog oplog) {
        getOplogSet().setChild(oplog);
    }

    DirectoryHolder getInfoFileDir() {
        return getDiskStore().getInfoFileDir();
    }

    public DirectoryHolder[] getDirectories() {
        return getDiskStore().directories;
    }

    Map<Long, Oplog> getOplogIdToOplog() {
        return getOplogSet().getOplogIdToOplog();
    }

    void testHookCloseAllOverflowChannels() {
        getDiskStore().testHookCloseAllOverflowChannels();
    }

    void testHookCloseAllOverflowOplogs() {
        getDiskStore().testHookCloseAllOverflowOplogs();
    }

    /**
     * Only called on overflow-only regions. Needs to take every entry currently using disk storage
     * and free up that storage
     */
    void freeAllEntriesOnDisk(LocalRegion region) {
        if (region == null) {
            return;
        }
        region.foreachRegionEntry(new RegionEntryCallback() {

            @Override
            public void handleRegionEntry(RegionEntry regionEntry) {
                DiskEntry de = (DiskEntry) regionEntry;
                DiskId id = de.getDiskId();
                if (id != null) {
                    synchronized (id) {
                        id.unmarkForWriting();
                        if (EntryBits.isNeedsValue(id.getUserBits())) {
                            long oplogId = id.getOplogId();
                            long offset = id.getOffsetInOplog();
                            // int length = id.getValueLength();
                            if (oplogId != -1 && offset != -1) {
                                id.setOplogId(-1);
                                OverflowOplog oplog = getDiskStore().overflowOplogs.getChild((int) oplogId);
                                if (oplog != null) {
                                    oplog.freeEntry(de);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    @Override
    public void finishPendingDestroy() {
        boolean wasFullDestroy = wasAboutToDestroy();
        super.endDestroy(null);
        if (wasFullDestroy) {
            // now do some recreate work
            setRegionClosed(false);
            register();
        }
    }

    @Override
    public DiskStoreID getDiskStoreID() {
        return getDiskStore().getDiskStoreID();
    }

    public void waitForAsyncRecovery() {
        getDiskStore().waitForAsyncRecovery(this);
    }

    @Override
    public void endRead(long start, long end, long bytesRead) {
        getStats().endRead(start, end, bytesRead);
    }

    /**
     * Record that we have done tombstone garbage collection to disk. On recovery or compaction, we
     * will discard tombstones less than the GC RVV.
     */
    public void writeRVVGC(LocalRegion region) {
        if (this.getFlags().contains(DiskRegionFlag.IS_WITH_VERSIONING)) {
            getDiskStore().writeRVVGC(this, region);
        }
    }

    /**
     * Record current RVV to disk and update into disk region RVV.
     */
    public void writeRVV(LocalRegion region, Boolean isRVVTrusted) {
        if (this.getFlags().contains(DiskRegionFlag.IS_WITH_VERSIONING)) {
            getDiskStore().writeRVV(this, region, isRVVTrusted);
        }
    }

    public void replaceIncompatibleEntry(DiskEntry old, DiskEntry repl) {
        acquireReadLock();
        try {
            getOplogSet().getChild().replaceIncompatibleEntry(this, old, repl);
        } finally {
            releaseReadLock();
        }
    }

    @Override
    public void close() {
    // nothing needed
    }

    @Override
    public EvictionController getExistingController(InternalRegionArguments internalArgs) {
        // should never be called so throw an exception
        throw new IllegalStateException("getExistingController should never be called on " + getClreplaced());
    }

    private boolean regionPreviouslyHostedData() {
        return isRecreated() && this.getMyPersistentID() != null && !this.wasAboutToDestroy() && !this.wasAboutToDestroyDataStorage();
    }

    private void destroyPartiallyInitializedRegion(final LocalRegion region) {
        if (this.isBucket() && !this.wasAboutToDestroy()) {
            /*
       * For bucket regions, we only destroy data storage for the following reason:
       * The ProxyBucketRegion and DiskInitFile will hold a reference to the same AbstractDiskRegion
       * object. If we do a full region destroy, it will result in the proxy and init file
       * referencing different objects. This can lead to a memory leak because disk compaction will
       * use the init file's version which may not have all changes from the in-memory version. A
       * partial destroy ensures that the ProxyBucketRegion and DiskInitFile continue to share the
       * same AbstractDiskRegion reference, which prevents this memory leak.
       *
       * Because we only destroy data storage, the persistence view will be maintained (disk ID will
       * be non-null) but all data and initializing/initialized persistent IDs will be deleted.
       */
            beginDestroyDataStorage();
        }
        endDestroy(region);
    }
}

19 View Complete Implementation : TXRegionLockRequestImplTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced TXRegionLockRequestImplTest {

    private InternalCache cache;

    private LocalRegion region;

    private CancelCriterion cancelCriterion;

    @Before
    public void setUp() {
        cache = mock(InternalCache.clreplaced);
        region = mock(LocalRegion.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        when(cache.getCancelCriterion()).thenReturn(cancelCriterion);
        doThrow(new CacheClosedException()).when(cancelCriterion).checkCancelInProgress(any());
    }

    @Test
    public void getKeysThrowsCancelExceptionIfCacheIsClosed() {
        TXRegionLockRequestImpl txRegionLockRequest = new TXRegionLockRequestImpl(cache, region);
        replacedertThatThrownBy(() -> txRegionLockRequest.getKeys()).isInstanceOf(CancelException.clreplaced);
    }
}

19 View Complete Implementation : SingleThreadJTAExecutor.java
Copyright Apache License 2.0
Author : apache
void doOps(TXState txState, CancelCriterion cancelCriterion) {
    try {
        beforeCompletion.doOp(txState);
    } finally {
        afterCompletion.doOp(txState, cancelCriterion);
    }
}

19 View Complete Implementation : StoppableCountDownLatchTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced StoppableCountDownLatchTest {

    private static final long TIMEOUT_MILLIS = getTimeout().getValueInMS();

    private CancelCriterion stopper;

    @Rule
    public ErrorCollector errorCollector = new ErrorCollector();

    @Rule
    public ExecutorServiceRule executorServiceRule = new ExecutorServiceRule();

    @Rule
    public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();

    @Before
    public void setUp() {
        stopper = mock(CancelCriterion.clreplaced);
    }

    @Test
    public void defaultRetryIntervalNanosIsTwoSeconds() {
        long twoSeconds = 2;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1);
        replacedertThat(NANOSECONDS.toSeconds(latch.retryIntervalNanos())).isEqualTo(MILLISECONDS.toSeconds(RETRY_TIME_MILLIS_DEFAULT)).isEqualTo(twoSeconds);
    }

    @Test
    public void awaitReturnsAfterCountDown() {
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1, MILLISECONDS.toNanos(2), System::nanoTime);
        Future<Void> latchFuture = executorServiceRule.submit(() -> latch.await());
        latch.countDown();
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
    }

    @Test
    public void awaitIsInterruptible() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await());
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(InterruptedException.clreplaced));
        });
        await().until(() -> theThread.get() != null);
        theThread.get().interrupt();
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }

    @Test
    public void awaitIsCancelable() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        String cancelMessage = "cancel";
        doNothing().doThrow(new CancelException(cancelMessage) {
        }).when(stopper).checkCancelInProgress(any());
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await());
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(CancelException.clreplaced).hasMessage(cancelMessage));
        });
        await().until(() -> theThread.get() != null);
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }

    @Test
    public void awaitWithTimeoutAndTimeUnitReturnsTrueAfterCountDown() throws Exception {
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1, MILLISECONDS.toNanos(2), System::nanoTime);
        Future<Boolean> latchFuture = executorServiceRule.submit(() -> latch.await(TIMEOUT_MILLIS, MILLISECONDS));
        latch.countDown();
        replacedertThat(latchFuture.get(TIMEOUT_MILLIS, MILLISECONDS)).isTrue();
    }

    @Test
    public void awaitWithTimeoutAndTimeUnitReturnsFalseAfterTimeout() throws Exception {
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1, MILLISECONDS.toNanos(2), System::nanoTime);
        long theTimeoutMillis = 2;
        long startNanos = System.nanoTime();
        Future<Boolean> latchFuture = executorServiceRule.submit(() -> latch.await(theTimeoutMillis, MILLISECONDS));
        replacedertThat(latchFuture.get(TIMEOUT_MILLIS, MILLISECONDS)).isFalse();
        replacedertThat(System.nanoTime() - startNanos).isGreaterThanOrEqualTo(theTimeoutMillis);
    }

    @Test
    public void awaitWithTimeoutAndTimeUnitIsInterruptible() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await(TIMEOUT_MILLIS, MILLISECONDS));
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(InterruptedException.clreplaced));
        });
        await().until(() -> theThread.get() != null);
        theThread.get().interrupt();
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }

    @Test
    public void awaitWithTimeoutAndTimeUnitIsCancelableAtBeginning() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        String cancelMessage = "cancel";
        doThrow(new CancelException(cancelMessage) {
        }).when(stopper).checkCancelInProgress(any());
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await(TIMEOUT_MILLIS, MILLISECONDS));
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(CancelException.clreplaced).hasMessage(cancelMessage));
        });
        await().until(() -> theThread.get() != null);
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }

    @Test
    public void awaitWithTimeoutMillisReturnsTrueAfterCountDown() throws Exception {
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1, MILLISECONDS.toNanos(2), System::nanoTime);
        Future<Boolean> latchFuture = executorServiceRule.submit(() -> latch.await(TIMEOUT_MILLIS));
        latch.countDown();
        replacedertThat(latchFuture.get(TIMEOUT_MILLIS, MILLISECONDS)).isTrue();
    }

    @Test
    public void awaitWithTimeoutMillisReturnsFalseAfterTimeout() throws Exception {
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, 1, MILLISECONDS.toNanos(2), System::nanoTime);
        long theTimeoutMillis = 2;
        long startNanos = System.nanoTime();
        Future<Boolean> latchFuture = executorServiceRule.submit(() -> latch.await(theTimeoutMillis));
        replacedertThat(latchFuture.get(TIMEOUT_MILLIS, MILLISECONDS)).isFalse();
        replacedertThat(System.nanoTime() - startNanos).isGreaterThanOrEqualTo(theTimeoutMillis);
    }

    @Test
    public void awaitWithTimeoutMillisIsInterruptible() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await(getTimeout().getValueInMS()));
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(InterruptedException.clreplaced));
        });
        await().until(() -> theThread.get() != null);
        theThread.get().interrupt();
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }

    @Test
    public void awaitWithTimeoutMillisIsCancelableAtBeginning() {
        int theCount = 1;
        StoppableCountDownLatch latch = new StoppableCountDownLatch(stopper, theCount, MILLISECONDS.toNanos(2), System::nanoTime);
        AtomicReference<Thread> theThread = new AtomicReference<>();
        String cancelMessage = "cancel";
        doThrow(new CancelException(cancelMessage) {
        }).when(stopper).checkCancelInProgress(any());
        Future<Void> latchFuture = executorServiceRule.submit(() -> {
            theThread.set(Thread.currentThread());
            Throwable thrown = catchThrowable(() -> latch.await(TIMEOUT_MILLIS));
            errorCollector.checkSucceeds(() -> replacedertThat(thrown).isInstanceOf(CancelException.clreplaced).hasMessage(cancelMessage));
        });
        await().until(() -> theThread.get() != null);
        await().untilreplacederted(() -> replacedertThat(latchFuture.isDone()).isTrue());
        replacedertThat(latch.getCount()).isEqualTo(theCount);
    }
}

19 View Complete Implementation : ColocationHelperTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced ColocationHelperTest {

    private CancelCriterion cancelCriterion;

    private ParreplacedionedRegion parreplacedionedRegion;

    private ParreplacedionRegionConfig parreplacedionRegionConfig;

    private DistributedRegion prRoot;

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

    @Before
    public void setUp() throws Exception {
        InternalCache cache = mock(InternalCache.clreplaced);
        ParreplacedionAttributes parreplacedionAttributes = mock(ParreplacedionAttributes.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        parreplacedionRegionConfig = mock(ParreplacedionRegionConfig.clreplaced);
        parreplacedionedRegion = mock(ParreplacedionedRegion.clreplaced);
        prRoot = mock(DistributedRegion.clreplaced);
        when(cache.getCancelCriterion()).thenReturn(cancelCriterion);
        when(cache.getRegion(anyString(), anyBoolean())).thenReturn(prRoot);
        when(parreplacedionedRegion.getCache()).thenReturn(cache);
        when(parreplacedionedRegion.getParreplacedionAttributes()).thenReturn(parreplacedionAttributes);
        when(parreplacedionAttributes.getColocatedWith()).thenReturn("region2");
    }

    @Test
    public void getColocatedRegion_throwsIllegalStateException_ifNotColocated() {
        when(parreplacedionedRegion.getFullPath()).thenReturn("/region1");
        Throwable thrown = catchThrowable(() -> ColocationHelper.getColocatedRegion(parreplacedionedRegion));
        replacedertThat(thrown).as("Expected IllegalStateException for missing colocated parent region").isInstanceOf(IllegalStateException.clreplaced).hasMessageMatching("Region specified in 'colocated-with' .* does not exist.*");
    }

    @Test
    public void getColocatedRegion_logsWarning_ifMissingRegion_whenPRConfigHasRegion() {
        when(parreplacedionedRegion.getFullPath()).thenReturn("/region1");
        when(prRoot.get(eq("#region2"))).thenReturn(parreplacedionRegionConfig);
        Throwable thrown = catchThrowable(() -> ColocationHelper.getColocatedRegion(parreplacedionedRegion));
        replacedertThat(thrown).as("Expected IllegalStateException for missing colocated parent region").isInstanceOf(IllegalStateException.clreplaced).hasMessageMatching("Region specified in 'colocated-with' .* does not exist.*");
    }

    @Test
    public void getColocatedRegion_throwsCacheClosedException_whenCacheIsClosed() {
        doThrow(new CacheClosedException("test")).when(cancelCriterion).checkCancelInProgress(any());
        when(prRoot.get(any())).thenReturn(parreplacedionRegionConfig);
        Throwable thrown = catchThrowable(() -> ColocationHelper.getColocatedRegion(parreplacedionedRegion));
        replacedertThat(thrown).isInstanceOf(CacheClosedException.clreplaced);
    }
}

19 View Complete Implementation : DiskRegion.java
Copyright Apache License 2.0
Author : apache
static DiskRegion create(DiskStoreImpl dsi, String name, boolean isBucket, boolean isPersistBackup, boolean overflowEnabled, boolean isSynchronous, DiskRegionStats stats, CancelCriterion cancel, DiskExceptionHandler exceptionHandler, RegionAttributes ra, EnumSet<DiskRegionFlag> flags, String parreplacedionName, int startingBucketId, Compressor compressor, boolean offHeap) {
    return dsi.getDiskInitFile().createDiskRegion(dsi, name, isBucket, isPersistBackup, overflowEnabled, isSynchronous, stats, cancel, exceptionHandler, ra, flags, parreplacedionName, startingBucketId, compressor, offHeap);
}

19 View Complete Implementation : AfterCompletion.java
Copyright Apache License 2.0
Author : apache
private synchronized void waitForCondition(CancelCriterion cancelCriterion, BooleanSupplier condition) {
    while (!condition.getAsBoolean()) {
        if (cancelCriterion != null) {
            cancelCriterion.checkCancelInProgress(null);
        }
        try {
            logger.debug("waiting for notification");
            wait(1000);
        } catch (InterruptedException ignore) {
        // eat the interrupt and check for exit conditions
        }
    }
}

19 View Complete Implementation : AfterCompletionTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced AfterCompletionTest {

    private AfterCompletion afterCompletion;

    private CancelCriterion cancelCriterion;

    private TXState txState;

    private Thread doOpThread;

    @Before
    public void setup() {
        afterCompletion = new AfterCompletion();
        cancelCriterion = mock(CancelCriterion.clreplaced);
        txState = mock(TXState.clreplaced);
    }

    @Test
    public void isStartedReturnsFalseIfNotExecuted() {
        replacedertThat(afterCompletion.isStarted()).isFalse();
    }

    @Test
    public void isStartedReturnsTrueIfExecuted() {
        startDoOp();
        afterCompletion.executeCommit();
        verifyDoOpFinished();
        replacedertThat(afterCompletion.isStarted()).isTrue();
    }

    @Test
    public void executeCallsDoAfterCompletionCommit() {
        startDoOp();
        afterCompletion.executeCommit();
        verifyDoOpFinished();
        verify(txState).doAfterCompletionCommit();
    }

    @Test
    public void executeThrowsDoAfterCompletionCommitThrows() {
        startDoOp();
        doThrow(new RuntimeException()).when(txState).doAfterCompletionCommit();
        replacedertThatThrownBy(() -> afterCompletion.executeCommit()).isInstanceOf(RuntimeException.clreplaced);
        verifyDoOpFinished();
    }

    @Test
    public void executeCallsDoAfterCompletionRollback() {
        startDoOp();
        afterCompletion.executeRollback();
        verifyDoOpFinished();
        verify(txState).doAfterCompletionRollback();
    }

    @Test
    public void executeThrowsDoAfterCompletionRollbackThrows() {
        startDoOp();
        doThrow(new RuntimeException()).when(txState).doAfterCompletionRollback();
        replacedertThatThrownBy(() -> afterCompletion.executeRollback()).isInstanceOf(RuntimeException.clreplaced);
        verifyDoOpFinished();
    }

    @Test
    public void doOpInvokesDoCleanupIfCancelCriteriaThrows() {
        doThrow(new RuntimeException()).when(cancelCriterion).checkCancelInProgress(null);
        afterCompletion.doOp(txState, cancelCriterion);
        verify(txState).doCleanup();
    }

    @Test
    public void cancelCallsDoCleanup() {
        startDoOp();
        afterCompletion.cancel();
        verifyDoOpFinished();
        verify(txState).doCleanup();
    }

    private void startDoOp() {
        doOpThread = new Thread(() -> afterCompletion.doOp(txState, cancelCriterion));
        doOpThread.start();
        await().untilreplacederted(() -> verify(cancelCriterion, atLeastOnce()).checkCancelInProgress(null));
    }

    private void verifyDoOpFinished() {
        await().until(() -> !doOpThread.isAlive());
    }
}

18 View Complete Implementation : ReplyProcessor21Test.java
Copyright Apache License 2.0
Author : apache
@Test
public void testReplyProcessorInitiatesSuspicion() throws Exception {
    DistributionManager dm = mock(DistributionManager.clreplaced);
    DMStats stats = mock(DMStats.clreplaced);
    InternalDistributedSystem system = mock(InternalDistributedSystem.clreplaced);
    DistributionConfig distributionConfig = mock(DistributionConfig.clreplaced);
    when(distributionConfig.getAckWaitThreshold()).thenReturn(1);
    when(distributionConfig.getAckSevereAlertThreshold()).thenReturn(10);
    when(system.getConfig()).thenReturn(distributionConfig);
    Distribution distribution = mock(Distribution.clreplaced);
    when(dm.getStats()).thenReturn(stats);
    when(dm.getSystem()).thenReturn(system);
    InternalDistributedMember member = mock(InternalDistributedMember.clreplaced);
    List<InternalDistributedMember> members = Arrays.asList(member);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(dm.getCancelCriterion()).thenReturn(cancelCriterion);
    when(dm.getDistribution()).thenReturn(distribution);
    when(dm.getViewMembers()).thenReturn(members);
    when(dm.getDistributionManagerIds()).thenReturn(new HashSet<>(members));
    when(dm.addMembershipListenerAndGetDistributionManagerIds(any(org.apache.geode.distributed.internal.MembershipListener.clreplaced))).thenReturn(new HashSet(members));
    List<InternalDistributedMember> mbrs = new ArrayList<>(1);
    mbrs.add(member);
    ReplyProcessor21 rp = new ReplyProcessor21(dm, mbrs);
    rp.enableSevereAlertProcessing();
    boolean result = rp.waitForReplies(WAIT_FOR_REPLIES_MILLIS);
    // the wait should have timed out
    replacedertFalse(result);
    verify(distribution, atLeastOnce()).suspectMembers(any(), anyString());
}

18 View Complete Implementation : LocalRegionBulkOperationTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced LocalRegionBulkOperationTest {

    private LocalRegion region;

    private EntryEventImpl event;

    private EventID eventID;

    private ServerRegionProxy serverRegionProxy;

    private CancelCriterion cancelCriterion;

    private PutAllPartialResultException exception;

    private final Object callbacks = new Object();

    private final CacheClosedException cacheClosedException = new CacheClosedException();

    @Before
    public void setup() {
        region = mock(LocalRegion.clreplaced);
        event = mock(EntryEventImpl.clreplaced);
        eventID = mock(EventID.clreplaced);
        serverRegionProxy = mock(ServerRegionProxy.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        exception = mock(PutAllPartialResultException.clreplaced);
        when(event.getEventId()).thenReturn(eventID);
        when(event.getCallbackArgument()).thenReturn(callbacks);
        when(region.hreplacederverProxy()).thenReturn(true);
        when(region.getServerProxy()).thenReturn(serverRegionProxy);
        when(region.getRegionMap()).thenReturn(mock(RegionMap.clreplaced));
        when(region.getDataView()).thenReturn(mock(InternalDataView.clreplaced));
        when(region.getCancelCriterion()).thenReturn(cancelCriterion);
        when(exception.getFailure()).thenReturn(cacheClosedException);
        when(cancelCriterion.generateCancelledException(cacheClosedException)).thenReturn(cacheClosedException);
    }

    @Test(expected = CacheClosedException.clreplaced)
    public void basicRemoveAllThrowsCacheClosedExceptionIfCacheIsClosing() {
        String[] strings = { "key" };
        Set keys = new HashSet<>(Arrays.asList(strings));
        DistributedRemoveAllOperation removeAll = mock(DistributedRemoveAllOperation.clreplaced);
        when(removeAll.getBaseEvent()).thenReturn(event);
        when(region.basicRemoveAll(keys, removeAll, null)).thenCallRealMethod();
        when(serverRegionProxy.removeAll(keys, eventID, callbacks)).thenThrow(exception);
        region.basicRemoveAll(keys, removeAll, null);
    }

    @Test(expected = CacheClosedException.clreplaced)
    public void basicPutAllThrowsCacheClosedExceptionIfCacheIsClosing() {
        Map map = new HashMap();
        map.put("key", "value");
        DistributedPutAllOperation putAll = mock(DistributedPutAllOperation.clreplaced);
        when(putAll.getBaseEvent()).thenReturn(event);
        when(region.basicPutAll(map, putAll, null)).thenCallRealMethod();
        when(region.getAtomicThresholdInfo()).thenReturn(mock(MemoryThresholdInfo.clreplaced));
        when(serverRegionProxy.putAll(map, eventID, true, callbacks)).thenThrow(exception);
        region.basicPutAll(map, putAll, null);
    }
}

18 View Complete Implementation : LocalRegionPartialMockTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced LocalRegionPartialMockTest {

    private LocalRegion region;

    private EntryEventImpl event;

    private ServerRegionProxy serverRegionProxy;

    private Operation operation;

    private CancelCriterion cancelCriterion;

    private RegionAttributes regionAttributes;

    private InternalCache cache;

    private CacheClientProxy proxy;

    private final Object key = new Object();

    private final String value = "value";

    @Before
    public void setup() {
        region = mock(LocalRegion.clreplaced);
        event = mock(EntryEventImpl.clreplaced);
        serverRegionProxy = mock(ServerRegionProxy.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        regionAttributes = mock(RegionAttributes.clreplaced);
        cache = mock(InternalCache.clreplaced);
        proxy = mock(CacheClientProxy.clreplaced);
        when(region.getServerProxy()).thenReturn(serverRegionProxy);
        when(event.isFromServer()).thenReturn(false);
        when(event.getKey()).thenReturn(key);
        when(event.getRawNewValue()).thenReturn(value);
        when(region.getCancelCriterion()).thenReturn(cancelCriterion);
        when(region.getAttributes()).thenReturn(regionAttributes);
        when(region.getCache()).thenReturn(cache);
    }

    @Test
    public void serverPutWillCheckPutIfAbsentResult() {
        Object result = new Object();
        operation = Operation.PUT_IF_ABSENT;
        when(event.getOperation()).thenReturn(operation);
        when(event.isCreate()).thenReturn(true);
        when(serverRegionProxy.put(key, value, null, event, operation, true, null, null, true)).thenReturn(result);
        doCallRealMethod().when(region).serverPut(event, true, null);
        region.serverPut(event, true, null);
        verify(region).checkPutIfAbsentResult(event, value, result);
    }

    @Test
    public void checkPutIfAbsentResultSucceedsIfResultIsNull() {
        Object result = null;
        doCallRealMethod().when(region).checkPutIfAbsentResult(event, value, result);
        region.checkPutIfAbsentResult(event, value, result);
        verify(event, never()).hasRetried();
    }

    @Test(expected = EntryNotFoundException.clreplaced)
    public void checkPutIfAbsentResultThrowsIfResultNotNullAndEventHasNotRetried() {
        Object result = new Object();
        when(event.hasRetried()).thenReturn(false);
        doCallRealMethod().when(region).checkPutIfAbsentResult(event, value, result);
        region.checkPutIfAbsentResult(event, value, result);
    }

    @Test
    public void testNotifiesSerialGatewaySenderEmptySenders() {
        doCallRealMethod().when(region).notifiesSerialGatewaySender();
        replacedertThat(region.notifiesSerialGatewaySender()).isFalse();
    }

    @Test
    public void testNotifiesSerialGatewaySenderPdxRegion() {
        when(region.isPdxTypesRegion()).thenReturn(false);
        doCallRealMethod().when(region).notifiesSerialGatewaySender();
        replacedertThat(region.notifiesSerialGatewaySender()).isFalse();
    }

    @Test
    public void testNotifiesSerialGatewaySenderWithSerialGatewaySender() {
        createGatewaySender("sender1", false);
        doCallRealMethod().when(region).notifiesSerialGatewaySender();
        replacedertThat(region.notifiesSerialGatewaySender()).isTrue();
    }

    @Test
    public void testNotifiesSerialGatewaySenderWithParallelGatewaySender() {
        createGatewaySender("sender1", true);
        doCallRealMethod().when(region).notifiesSerialGatewaySender();
        replacedertThat(region.notifiesSerialGatewaySender()).isFalse();
    }

    @Test
    public void testInitializationThreadInitValue() throws InterruptedException, ExecutionException {
        ExecutorService executionService = Executors.newFixedThreadPool(1);
        Future future = executionService.submit(() -> replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(AFTER_INITIAL_IMAGE));
        future.get();
    }

    @Test
    public void testSetThreadInitLevelRequirement() throws InterruptedException, ExecutionException {
        ExecutorService executionService = Executors.newFixedThreadPool(1);
        Future future = executionService.submit(() -> {
            replacedertThat(LocalRegion.setThreadInitLevelRequirement(ANY_INIT)).isEqualTo(AFTER_INITIAL_IMAGE);
            replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(ANY_INIT);
            replacedertThat(LocalRegion.setThreadInitLevelRequirement(BEFORE_INITIAL_IMAGE)).isEqualTo(ANY_INIT);
            replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(BEFORE_INITIAL_IMAGE);
            replacedertThat(LocalRegion.setThreadInitLevelRequirement(AFTER_INITIAL_IMAGE)).isEqualTo(BEFORE_INITIAL_IMAGE);
            replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(AFTER_INITIAL_IMAGE);
        });
        future.get();
    }

    @Test
    public void testSetThreadInitLevelRequirementDoesNotAffectOtherThreads() throws InterruptedException, ExecutionException {
        ExecutorService executionService1 = Executors.newFixedThreadPool(1);
        Future future1 = executionService1.submit(() -> {
            replacedertThat(LocalRegion.setThreadInitLevelRequirement(ANY_INIT)).isEqualTo(AFTER_INITIAL_IMAGE);
            replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(ANY_INIT);
        });
        future1.get();
        ExecutorService executionService2 = Executors.newFixedThreadPool(1);
        Future future2 = executionService2.submit(() -> replacedertThat(LocalRegion.getThreadInitLevelRequirement()).isEqualTo(AFTER_INITIAL_IMAGE));
        future2.get();
    }

    private void createGatewaySender(String senderId, boolean isParallel) {
        // Create set of sender ids
        Set<String> allGatewaySenderIds = Stream.of(senderId).collect(Collectors.toSet());
        when(region.getAllGatewaySenderIds()).thenReturn(allGatewaySenderIds);
        // Create set of senders
        GatewaySender sender = mock(GatewaySender.clreplaced);
        when(sender.getId()).thenReturn(senderId);
        when(sender.isParallel()).thenReturn(isParallel);
        Set<GatewaySender> allGatewaySenders = Stream.of(sender).collect(Collectors.toSet());
        when(cache.getAllGatewaySenders()).thenReturn(allGatewaySenders);
    }

    @Test
    public void testDoNotNotifyClientsOfTombstoneGCNoCacheClientNotifier() {
        Map regionGCVersions = new HashMap();
        Set keysRemoved = new HashSet();
        EventID eventID = new EventID();
        FilterInfo routing = new FilterInfo();
        doCallRealMethod().when(region).notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        region.notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        verify(region, never()).getFilterProfile();
    }

    @Test
    public void testDoNotNotifyClientsOfTombstoneGCNoProxy() {
        Map regionGCVersions = new HashMap();
        Set keysRemoved = new HashSet();
        EventID eventID = new EventID();
        FilterInfo routing = null;
        when(cache.getCCPTimer()).thenReturn(mock(SystemTimer.clreplaced));
        CacheClientNotifier ccn = CacheClientNotifier.getInstance(cache, mock(ClientRegistrationEventQueueManager.clreplaced), disabledClock(), mock(CacheServerStats.clreplaced), 10, 10, mock(ConnectionListener.clreplaced), null, true);
        doCallRealMethod().when(region).notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        region.notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        verify(region, never()).getFilterProfile();
        when(cache.getCacheServers()).thenReturn(Collections.emptyList());
        ccn.shutdown(111);
    }

    @Test
    public void testNotifyClientsOfTombstoneGC() {
        Map regionGCVersions = new HashMap();
        Set keysRemoved = new HashSet();
        EventID eventID = new EventID();
        FilterInfo routing = null;
        when(cache.getCCPTimer()).thenReturn(mock(SystemTimer.clreplaced));
        CacheClientNotifier ccn = CacheClientNotifier.getInstance(cache, mock(ClientRegistrationEventQueueManager.clreplaced), disabledClock(), mock(CacheServerStats.clreplaced), 10, 10, mock(ConnectionListener.clreplaced), null, true);
        when(proxy.getProxyID()).thenReturn(mock(ClientProxyMembershipID.clreplaced));
        ccn.addClientProxyToMap(proxy);
        doCallRealMethod().when(region).notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        when(region.getFilterProfile()).thenReturn(null);
        region.notifyClientsOfTombstoneGC(regionGCVersions, keysRemoved, eventID, routing);
        when(cache.getCacheServers()).thenReturn(Collections.emptyList());
        when(proxy.getAcceptorId()).thenReturn(Long.valueOf(111));
        ccn.shutdown(111);
    }
}

18 View Complete Implementation : ParallelGatewaySenderHelper.java
Copyright Apache License 2.0
Author : apache
public static AbstractGatewaySender createGatewaySender(GemFireCacheImpl cache) {
    // Mock gateway sender
    AbstractGatewaySender sender = mock(AbstractGatewaySender.clreplaced);
    when(sender.getCache()).thenReturn(cache);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(sender.getCancelCriterion()).thenReturn(cancelCriterion);
    return sender;
}

18 View Complete Implementation : HostStatSamplerTest.java
Copyright Apache License 2.0
Author : apache
/**
 * Unit tests for {@link HostStatSampler}.
 */
public clreplaced HostStatSamplerTest {

    private CancelCriterion cancelCriterion;

    private StatSamplerStats statSamplerStats;

    private NanoTimer timer;

    private LogFile logFile;

    private StatisticsManager statisticsManager;

    private HostStatSampler hostStatSampler;

    @Before
    public void setUp() {
        cancelCriterion = mock(CancelCriterion.clreplaced);
        statSamplerStats = mock(StatSamplerStats.clreplaced);
        timer = new NanoTimer();
        logFile = null;
        statisticsManager = mock(StatisticsManager.clreplaced);
    }

    @Test
    public void getSpecialStatsId_returnsPidFromPidSupplier_ifValueIsGreaterThanZero() {
        int thePid = 42;
        when(statisticsManager.getPid()).thenReturn(thePid);
        long anySystemId = 2;
        hostStatSampler = new TestableHostStatSampler(cancelCriterion, statSamplerStats, timer, logFile, statisticsManager, anySystemId);
        replacedertThat(hostStatSampler.getSpecialStatsId()).isEqualTo(thePid);
    }

    @Test
    public void getSpecialStatsId_returnsSystemId_ifValueFromPidSupplierIsZero() {
        when(statisticsManager.getPid()).thenReturn(0);
        long theSystemId = 21;
        hostStatSampler = new TestableHostStatSampler(cancelCriterion, statSamplerStats, timer, logFile, statisticsManager, theSystemId);
        replacedertThat(hostStatSampler.getSpecialStatsId()).isEqualTo(theSystemId);
    }

    @Test
    public void getSpecialStatsId_returnsSystemId_ifValueFromPidSupplierIsLessThanZero() {
        when(statisticsManager.getPid()).thenReturn(-1);
        long theSystemId = 21;
        hostStatSampler = new TestableHostStatSampler(cancelCriterion, statSamplerStats, timer, logFile, statisticsManager, theSystemId);
        replacedertThat(hostStatSampler.getSpecialStatsId()).isEqualTo(theSystemId);
    }

    @Test
    public void getSpecialStatsId_returnsSystemId_ifPidSupplierThrows() {
        when(statisticsManager.getPid()).thenThrow(new UncheckedPidUnavailableException(new PidUnavailableException("Pid not found")));
        long theSystemId = 21;
        hostStatSampler = new TestableHostStatSampler(cancelCriterion, statSamplerStats, timer, logFile, statisticsManager, theSystemId);
        replacedertThat(hostStatSampler.getSpecialStatsId()).isEqualTo(theSystemId);
    }

    private static clreplaced TestableHostStatSampler extends HostStatSampler {

        private final StatisticsManager statisticsManager;

        private final long systemId;

        TestableHostStatSampler(CancelCriterion stopper, StatSamplerStats samplerStats, NanoTimer timer, LogFile logFile, StatisticsManager statisticsManager, long systemId) {
            super(stopper, samplerStats, timer, logFile);
            this.statisticsManager = statisticsManager;
            this.systemId = systemId;
        }

        @Override
        protected void checkListeners() {
        }

        @Override
        protected int getSampleRate() {
            return 0;
        }

        @Override
        public boolean isSamplingEnabled() {
            return false;
        }

        @Override
        protected StatisticsManager getStatisticsManager() {
            return statisticsManager;
        }

        @Override
        public File getArchiveFileName() {
            return null;
        }

        @Override
        public long getArchiveFileSizeLimit() {
            return 0;
        }

        @Override
        public long getArchiveDiskSpaceLimit() {
            return 0;
        }

        @Override
        public long getSystemId() {
            return systemId;
        }

        @Override
        public String getProductDescription() {
            return null;
        }
    }
}

18 View Complete Implementation : ConnectionTest.java
Copyright Apache License 2.0
Author : apache
/**
 * Test whether suspicion is raised about a member that closes its shared/unordered TCPConduit
 * connection
 */
@Test
public void testSuspicionRaised() throws Exception {
    ConnectionTable connectionTable = mock(ConnectionTable.clreplaced);
    Distribution distribution = mock(Distribution.clreplaced);
    DistributionManager distributionManager = mock(DistributionManager.clreplaced);
    DMStats dmStats = mock(DMStats.clreplaced);
    CancelCriterion stopper = mock(CancelCriterion.clreplaced);
    SocketCloser socketCloser = mock(SocketCloser.clreplaced);
    TCPConduit tcpConduit = mock(TCPConduit.clreplaced);
    when(connectionTable.getBufferPool()).thenReturn(new BufferPool(dmStats));
    when(connectionTable.getConduit()).thenReturn(tcpConduit);
    when(connectionTable.getDM()).thenReturn(distributionManager);
    when(connectionTable.getSocketCloser()).thenReturn(socketCloser);
    when(distributionManager.getDistribution()).thenReturn(distribution);
    when(stopper.cancelInProgress()).thenReturn(null);
    when(tcpConduit.getCancelCriterion()).thenReturn(stopper);
    when(tcpConduit.getDM()).thenReturn(distributionManager);
    when(tcpConduit.getSocketId()).thenReturn(new InetSocketAddress(getLocalHost(), 10337));
    when(tcpConduit.getStats()).thenReturn(dmStats);
    SocketChannel channel = SocketChannel.open();
    Connection connection = new Connection(connectionTable, channel.socket());
    connection.setSharedUnorderedForTest();
    connection.run();
    verify(distribution).suspectMember(isNull(), anyString());
}

18 View Complete Implementation : ConnectionManagerImplTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced ConnectionManagerImplTest {

    ConnectionManagerImpl connectionManager;

    public final String poolName = "poolName";

    public final ConnectionFactory connectionFactory = mock(ConnectionFactory.clreplaced);

    public final EndpointManager endpointManager = mock(EndpointManager.clreplaced);

    public final InternalLogWriter securityLogger = mock(InternalLogWriter.clreplaced);

    public final CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);

    public final PoolStats poolStats = mock(PoolStats.clreplaced);

    public final ScheduledExecutorService backgroundProcessor = mock(ScheduledExecutorService.clreplaced);

    public int maxConnections = 800;

    public int minConnections = 10;

    public long idleTimeout = 1000;

    public long timeout = 1000;

    public int lifetimeTimeout = 1000;

    public long pingInterval = 10;

    private ConnectionManagerImpl createDefaultConnectionManager() {
        return new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, minConnections, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
    }

    @Test
    public void startExecutedPrefillConnectionsOnce() {
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        connectionManager.start(backgroundProcessor);
        verify(backgroundProcessor, times(1)).execute(any());
        connectionManager.close(false);
    }

    @Test
    public void startShouldEatRejectedExecutionException() {
        doThrow(RejectedExecutionException.clreplaced).when(backgroundProcessor).execute(any());
        connectionManager = createDefaultConnectionManager();
        replacedertThatCode(() -> connectionManager.start(backgroundProcessor)).doesNotThrowAnyException();
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionThrowsWhenUsingExistingConnectionsAndNoConnectionsExist() {
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        connectionManager = createDefaultConnectionManager();
        replacedertThatThrownBy(() -> connectionManager.borrowConnection(serverLocation, true)).isInstanceOf(AllConnectionsInUseException.clreplaced);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionCreatesAConnectionOnSpecifiedServerWhenNoneExist() {
        Connection connection = mock(Connection.clreplaced);
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation, false)).thenReturn(connection);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        replacedertThat(connectionManager.borrowConnection(serverLocation, false)).isInstanceOf(PooledConnection.clreplaced);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(1);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionCreatesAConnectionWhenNoneExist() {
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        replacedertThat(connectionManager.borrowConnection(timeout)).isInstanceOf(PooledConnection.clreplaced);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(1);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionReturnsAnActiveConnection() {
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        PooledConnection heldConnection = (PooledConnection) connectionManager.borrowConnection(timeout);
        replacedertThatThrownBy(() -> heldConnection.activate()).isInstanceOf(InternalGemFireException.clreplaced).hasMessageContaining("Connection already active");
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionReturnsAConnectionWhenOneExists() {
        ServerLocation serverLocation = mock(ServerLocation.clreplaced);
        Endpoint endpoint = mock(Endpoint.clreplaced);
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        when(connection.getServer()).thenReturn(serverLocation);
        when(connection.getEndpoint()).thenReturn(endpoint);
        when(endpoint.getLocation()).thenReturn(serverLocation);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        Connection heldConnection = connectionManager.borrowConnection(timeout);
        connectionManager.returnConnection(heldConnection);
        heldConnection = connectionManager.borrowConnection(timeout);
        replacedertThat(heldConnection.getServer()).isEqualTo(connection.getServer());
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(1);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionThrowsExceptionWhenUnableToCreateConnection() {
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(null);
        doNothing().when(backgroundProcessor).execute(any());
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        replacedertThatThrownBy(() -> connectionManager.borrowConnection(timeout)).isInstanceOf(NoAvailableServersException.clreplaced);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(0);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionWillSchedulePrefillIfUnderMinimumConnections() {
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(null);
        doNothing().when(backgroundProcessor).execute(any());
        // set it high to prevent prefill retry
        pingInterval = 20000000;
        connectionManager = spy(createDefaultConnectionManager());
        connectionManager.start(backgroundProcessor);
        replacedertThatThrownBy(() -> connectionManager.borrowConnection(timeout)).isInstanceOf(NoAvailableServersException.clreplaced);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(0);
        verify(connectionManager, times(2)).startBackgroundPrefill();
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionGivesUpWhenShuttingDown() {
        int maxConnections = 1;
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        connectionManager = new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, 1, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
        connectionManager.start(backgroundProcessor);
        connectionManager.shuttingDown.set(true);
        // reach max connection count so we can't create a new connection and end up in the wait loop
        connectionManager.borrowConnection(timeout);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(maxConnections);
        replacedertThatThrownBy(() -> connectionManager.borrowConnection(timeout)).isInstanceOf(PoolCancelledException.clreplaced);
        connectionManager.close(false);
    }

    @Test
    public void borrowConnectionTimesOutWithException() {
        int maxConnections = 1;
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        connectionManager = new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, 1, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
        connectionManager.start(backgroundProcessor);
        // reach max connection count so we can't create a new connection and end up in the wait loop
        connectionManager.borrowConnection(timeout);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(maxConnections);
        replacedertThatThrownBy(() -> connectionManager.borrowConnection(10)).isInstanceOf(AllConnectionsInUseException.clreplaced);
        connectionManager.close(false);
    }

    @Test
    public void borrowWithServerLocationBreaksMaxConnectionContract() {
        int maxConnections = 2;
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation2, false)).thenReturn(connection2);
        ServerLocation serverLocation3 = mock(ServerLocation.clreplaced);
        Connection connection3 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation3, false)).thenReturn(connection3);
        connectionManager = new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, 1, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
        connectionManager.start(backgroundProcessor);
        connectionManager.borrowConnection(serverLocation1, false);
        connectionManager.borrowConnection(serverLocation2, false);
        connectionManager.borrowConnection(serverLocation3, false);
        replacedertThat(connectionManager.getConnectionCount()).isGreaterThan(maxConnections);
        connectionManager.close(false);
    }

    @Test
    public void returnConnectionReturnsToHead() {
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        when(connection1.getServer()).thenReturn(serverLocation1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        Endpoint endpoint2 = mock(Endpoint.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation2, false)).thenReturn(connection2);
        when(connection2.getServer()).thenReturn(serverLocation2);
        when(connection2.getEndpoint()).thenReturn(endpoint2);
        when(endpoint2.getLocation()).thenReturn(serverLocation2);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        Connection heldConnection1 = connectionManager.borrowConnection(serverLocation1, false);
        Connection heldConnection2 = connectionManager.borrowConnection(serverLocation2, false);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(2);
        connectionManager.returnConnection(heldConnection1, true);
        connectionManager.returnConnection(heldConnection2, true);
        replacedertThat(connectionManager.borrowConnection(timeout).getServer()).isEqualTo(connection2.getServer());
        connectionManager.close(false);
    }

    @Test
    public void shouldDestroyConnectionsDoNotGetReturnedToPool() {
        Connection connection = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(any())).thenReturn(connection);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        Connection heldConnection = connectionManager.borrowConnection(timeout);
        heldConnection.destroy();
        connectionManager.returnConnection(heldConnection, true);
        replacedertThat(connectionManager.borrowConnection(timeout)).isNotEqualTo(connection);
        verify(connectionFactory, times(2)).createClientToServerConnection(any());
        connectionManager.close(false);
    }

    @Test
    public void connectionGetsDestroyedWhenReturningToPoolAndOverMaxConnections() {
        int maxConnections = 2;
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation2, false)).thenReturn(connection2);
        ServerLocation serverLocation3 = mock(ServerLocation.clreplaced);
        Connection connection3 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation3, false)).thenReturn(connection3);
        connectionManager = new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, 1, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
        connectionManager.start(backgroundProcessor);
        Connection heldConnection1 = connectionManager.borrowConnection(serverLocation1, false);
        Connection heldConnection2 = connectionManager.borrowConnection(serverLocation2, false);
        Connection heldConnection3 = connectionManager.borrowConnection(serverLocation3, false);
        replacedertThat(connectionManager.getConnectionCount()).isGreaterThan(maxConnections);
        connectionManager.returnConnection(heldConnection3);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(maxConnections);
        connectionManager.returnConnection(heldConnection1);
        connectionManager.returnConnection(heldConnection2);
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(maxConnections);
        connectionManager.close(false);
    }

    @Test
    public void exchangeCreatesNewConnectionIfNoneAreAvailable() {
        Set<ServerLocation> excluded = Collections.emptySet();
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Endpoint endpoint2 = mock(Endpoint.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(eq(Collections.EMPTY_SET))).thenReturn(connection2);
        when(connection2.getServer()).thenReturn(serverLocation2);
        when(connection2.getEndpoint()).thenReturn(endpoint2);
        when(endpoint2.getLocation()).thenReturn(serverLocation2);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        Connection heldConnection = connectionManager.borrowConnection(serverLocation1, false);
        heldConnection = connectionManager.exchangeConnection(heldConnection, excluded);
        replacedertThat(heldConnection.getServer()).isEqualTo(connection2.getServer());
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(2);
        verify(connectionFactory, times(1)).createClientToServerConnection(Collections.EMPTY_SET);
        connectionManager.close(false);
    }

    @Test
    public void exchangeBreaksMaxConnectionContractWhenNoConnectionsAreAvailable() {
        int maxConnections = 2;
        Set<ServerLocation> excluded = Collections.emptySet();
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation2, false)).thenReturn(connection2);
        ServerLocation serverLocation3 = mock(ServerLocation.clreplaced);
        Connection connection3 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation3, false)).thenReturn(connection3);
        ServerLocation serverLocation4 = mock(ServerLocation.clreplaced);
        Endpoint endpoint4 = mock(Endpoint.clreplaced);
        Connection connection4 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(eq(Collections.EMPTY_SET))).thenReturn(connection4);
        when(connection4.getServer()).thenReturn(serverLocation4);
        when(connection4.getEndpoint()).thenReturn(endpoint4);
        when(endpoint4.getLocation()).thenReturn(serverLocation4);
        connectionManager = new ConnectionManagerImpl(poolName, connectionFactory, endpointManager, maxConnections, 1, idleTimeout, lifetimeTimeout, securityLogger, pingInterval, cancelCriterion, poolStats);
        connectionManager.start(backgroundProcessor);
        Connection heldConnection = connectionManager.borrowConnection(serverLocation1, false);
        connectionManager.borrowConnection(serverLocation2, false);
        connectionManager.borrowConnection(serverLocation3, false);
        replacedertThat(connectionManager.getConnectionCount()).isGreaterThan(maxConnections);
        heldConnection = connectionManager.exchangeConnection(heldConnection, excluded);
        replacedertThat(connectionManager.getConnectionCount()).isGreaterThan(maxConnections);
        replacedertThat(heldConnection.getServer()).isEqualTo(connection4.getServer());
        verify(connectionFactory, times(1)).createClientToServerConnection(Collections.EMPTY_SET);
        connectionManager.close(false);
    }

    @Test
    public void exchangeReturnsExistingConnectionIfOneExists() {
        Set<ServerLocation> excluded = Collections.emptySet();
        ServerLocation serverLocation1 = mock(ServerLocation.clreplaced);
        Connection connection1 = mock(Connection.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation1, false)).thenReturn(connection1);
        ServerLocation serverLocation2 = mock(ServerLocation.clreplaced);
        Connection connection2 = mock(Connection.clreplaced);
        Endpoint endpoint2 = mock(Endpoint.clreplaced);
        when(connectionFactory.createClientToServerConnection(serverLocation2, false)).thenReturn(connection2);
        when(connection2.getServer()).thenReturn(serverLocation2);
        when(connection2.getEndpoint()).thenReturn(endpoint2);
        when(endpoint2.getLocation()).thenReturn(serverLocation2);
        connectionManager = createDefaultConnectionManager();
        connectionManager.start(backgroundProcessor);
        Connection heldConnection1 = connectionManager.borrowConnection(serverLocation1, false);
        Connection heldConnection2 = connectionManager.borrowConnection(serverLocation2, false);
        connectionManager.returnConnection(heldConnection2);
        heldConnection2 = connectionManager.exchangeConnection(heldConnection1, excluded);
        replacedertThat(heldConnection2.getServer()).isEqualTo(connection2.getServer());
        replacedertThat(connectionManager.getConnectionCount()).isEqualTo(2);
        connectionManager.close(false);
    }
}

18 View Complete Implementation : DLockGrantorTest.java
Copyright Apache License 2.0
Author : apache
@Before
public void setup() {
    dLockService = mock(DLockService.clreplaced, RETURNS_DEEP_STUBS);
    distributionManager = mock(DistributionManager.clreplaced);
    when(dLockService.getDistributionManager()).thenReturn(distributionManager);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(distributionManager.getCancelCriterion()).thenReturn(cancelCriterion);
    grantor = DLockGrantor.createGrantor(dLockService, 1);
}

18 View Complete Implementation : ConnectionFactoryImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates connections, using a connection source to determine which server to connect to.
 *
 * @since GemFire 5.7
 */
public clreplaced ConnectionFactoryImpl implements ConnectionFactory {

    private static final Logger logger = LogService.getLogger();

    // TODO - GEODE-1746, the handshake holds state. It seems like the code depends
    // on all of the handshake operations happening in a single thread. I don't think we
    // want that, need to refactor.
    private final ServerDenyList denyList;

    private ConnectionSource source;

    private PoolImpl pool;

    private final CancelCriterion cancelCriterion;

    private final ConnectionConnector connectionConnector;

    /**
     * Test hook for client version support
     *
     * @since GemFire 5.7
     */
    @MutableForTesting
    public static boolean testFailedConnectionToServer = false;

    ConnectionFactoryImpl(ConnectionSource source, EndpointManager endpointManager, InternalDistributedSystem sys, int socketBufferSize, int handshakeTimeout, int readTimeout, ClientProxyMembershipID proxyId, CancelCriterion cancelCriterion, boolean usedByGateway, GatewaySender sender, long pingInterval, boolean multiuserSecureMode, PoolImpl pool, final DistributionConfig distributionConfig) {
        this(new ConnectionConnector(endpointManager, sys, socketBufferSize, handshakeTimeout, readTimeout, usedByGateway, sender, (usedByGateway || sender != null) ? SocketCreatorFactory.getSocketCreatorForComponent(distributionConfig, SecurableCommunicationChannel.GATEWAY) : SocketCreatorFactory.getSocketCreatorForComponent(distributionConfig, SecurableCommunicationChannel.SERVER), new ClientSideHandshakeImpl(proxyId, sys, sys.getSecurityService(), multiuserSecureMode)), source, pingInterval, pool, cancelCriterion);
    }

    public ConnectionFactoryImpl(ConnectionConnector connectionConnector, ConnectionSource source, long pingInterval, PoolImpl pool, CancelCriterion cancelCriterion) {
        this.connectionConnector = connectionConnector;
        this.source = source;
        this.pool = pool;
        this.cancelCriterion = cancelCriterion;
        denyList = new ServerDenyList(pingInterval);
    }

    public void start(ScheduledExecutorService background) {
        denyList.start(background);
    }

    @Override
    public ServerDenyList getDenyList() {
        return denyList;
    }

    @Override
    public Connection createClientToServerConnection(ServerLocation location, boolean forQueue) throws GemFireSecurityException {
        FailureTracker failureTracker = denyList.getFailureTracker(location);
        Connection connection = null;
        try {
            connection = connectionConnector.connectClientToServer(location, forQueue);
            failureTracker.reset();
            authenticateIfRequired(connection);
        } catch (GemFireConfigException | CancelException | GemFireSecurityException | GatewayConfigurationException e) {
            throw e;
        } catch (ServerRefusedConnectionException src) {
            // propagate this up, don't retry
            logger.warn("Could not create a new connection to server: {}", src.getMessage());
            testFailedConnectionToServer = true;
            throw src;
        } catch (Exception e) {
            if (e.getMessage() != null && (e.getMessage().equals("Connection refused") || e.getMessage().equals("Connection reset"))) {
                // this is the most common case, so don't print an exception
                if (logger.isDebugEnabled()) {
                    logger.debug("Unable to connect to {}: connection refused", location);
                }
            } else {
                logger.warn("Could not connect to: " + location, e);
            }
            testFailedConnectionToServer = true;
        }
        return connection;
    }

    private void authenticateIfRequired(Connection conn) {
        cancelCriterion.checkCancelInProgress(null);
        if (!pool.isUsedByGateway() && !pool.getMultiuserAuthentication()) {
            ServerLocation server = conn.getServer();
            if (server.getRequiresCredentials()) {
                if (server.getUserId() == -1) {
                    Long uniqueID = (Long) AuthenticateUserOp.executeOn(conn, pool);
                    server.setUserId(uniqueID);
                    if (logger.isDebugEnabled()) {
                        logger.debug("CFI.authenticateIfRequired() Completed authentication on {}", conn);
                    }
                }
            }
        }
    }

    @Override
    public ServerLocation findBestServer(ServerLocation currentServer, Set<ServerLocation> excludedServers) {
        if (currentServer != null && source.isBalanced()) {
            return currentServer;
        }
        final Set<ServerLocation> origExcludedServers = excludedServers;
        excludedServers = new HashSet<>(excludedServers);
        Set<ServerLocation> denyListedServers = denyList.getBadServers();
        excludedServers.addAll(denyListedServers);
        ServerLocation server = source.findReplacementServer(currentServer, excludedServers);
        if (server == null) {
            // Nothing worked! Let's try without the denylist.
            if (excludedServers.size() > origExcludedServers.size()) {
                // We had some servers denylisted so lets give this another whirl.
                server = source.findReplacementServer(currentServer, origExcludedServers);
            }
        }
        if (server == null && logger.isDebugEnabled()) {
            logger.debug("Source was unable to findForReplacement any servers");
        }
        return server;
    }

    @Override
    public Connection createClientToServerConnection(Set<ServerLocation> excludedServers) throws GemFireSecurityException {
        final Set<ServerLocation> origExcludedServers = excludedServers;
        excludedServers = new HashSet<>(excludedServers);
        Set<ServerLocation> denyListedServers = denyList.getBadServers();
        excludedServers.addAll(denyListedServers);
        Connection conn = null;
        RuntimeException fatalException = null;
        boolean tryDenyList = true;
        do {
            ServerLocation server = source.findServer(excludedServers);
            if (server == null) {
                if (tryDenyList) {
                    // Nothing worked! Let's try without the denylist.
                    tryDenyList = false;
                    int size = excludedServers.size();
                    excludedServers.removeAll(denyListedServers);
                    // make sure we didn't remove any of the ones that the caller set not to use
                    excludedServers.addAll(origExcludedServers);
                    if (excludedServers.size() < size) {
                        // We are able to remove some exclusions, so lets give this another whirl.
                        continue;
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Source was unable to locate any servers");
                }
                if (fatalException != null) {
                    throw fatalException;
                }
                return null;
            }
            try {
                conn = createClientToServerConnection(server, false);
            } catch (CancelException | GemFireSecurityException | GatewayConfigurationException e) {
                throw e;
            } catch (ServerRefusedConnectionException srce) {
                fatalException = srce;
                if (logger.isDebugEnabled()) {
                    logger.debug("ServerRefusedConnectionException attempting to connect to {}", server, srce);
                }
            } catch (Exception e) {
                logger.warn(String.format("Could not connect to: %s", server), e);
            }
            excludedServers.add(server);
        } while (conn == null);
        return conn;
    }

    @Override
    public ClientUpdater createServerToClientConnection(Endpoint endpoint, QueueManager qManager, boolean isPrimary, ClientUpdater failedUpdater) {
        String clientUpdateName = CacheClientUpdater.CLIENT_UPDATER_THREAD_NAME + " on " + endpoint.getMemberId() + " port " + endpoint.getLocation().getPort();
        if (logger.isDebugEnabled()) {
            logger.debug("Establishing: {}", clientUpdateName);
        }
        return connectionConnector.connectServerToClient(endpoint, qManager, isPrimary, failedUpdater, clientUpdateName);
    }
}

18 View Complete Implementation : RecoveryRunnable.java
Copyright Apache License 2.0
Author : apache
@Override
public void run() {
    CancelCriterion stopper = redundancyProvider.getParreplacedionedRegion().getGemFireCache().getDistributedSystem().getCancelCriterion();
    DistributedSystem.setThreadsSocketPolicy(true);
    SystemFailure.checkFailure();
    if (stopper.isCancelInProgress()) {
        return;
    }
    try {
        run2();
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // If this ever returns, rethrow the error. We're poisoned
        // now, so don't let this thread continue.
        throw err;
    } catch (Throwable t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        if (logger.isDebugEnabled()) {
            logger.debug("Unexpected exception in PR redundancy recovery", t);
        }
        failure = t;
    }
}

18 View Complete Implementation : SingleThreadJTAExecutor.java
Copyright Apache License 2.0
Author : apache
public void executeBeforeCompletion(TXState txState, Executor executor, CancelCriterion cancelCriterion) {
    executor.execute(() -> doOps(txState, cancelCriterion));
    beforeCompletion.execute(cancelCriterion);
}

18 View Complete Implementation : CallbackSampler.java
Copyright Apache License 2.0
Author : apache
public clreplaced CallbackSampler {

    private static final Logger logger = LogService.getLogger();

    private StatisticsManager statisticsManager;

    private final CancelCriterion cancelCriterion;

    private long sampleIntervalNanos;

    private ScheduledExecutorService executor;

    private final StatSamplerStats statSamplerStats;

    public CallbackSampler(final CancelCriterion cancelCriterion, final StatSamplerStats statSamplerStats) {
        this.cancelCriterion = cancelCriterion;
        this.statSamplerStats = statSamplerStats;
    }

    public void start(StatisticsManager statisticsManager, int sampleInterval, TimeUnit timeUnit) {
        ScheduledExecutorService executor = LoggingExecutors.newSingleThreadScheduledExecutor("CallbackSampler");
        start(executor, statisticsManager, sampleInterval, timeUnit);
    }

    void start(ScheduledExecutorService executor, StatisticsManager statisticsManager, int sampleInterval, TimeUnit timeUnit) {
        stop();
        this.statisticsManager = statisticsManager;
        this.executor = executor;
        executor.scheduleAtFixedRate(() -> sampleCallbacks(), sampleInterval, sampleInterval, timeUnit);
    }

    private void sampleCallbacks() {
        if (cancelCriterion.isCancelInProgress()) {
            executor.shutdown();
        }
        int errors = 0;
        int suppliers = 0;
        long start = System.nanoTime();
        try {
            for (Statistics stats : statisticsManager.getStatsList()) {
                StatisticsImpl statistics = (StatisticsImpl) stats;
                errors += statistics.updateSuppliedValues();
                suppliers += statistics.getSupplierCount();
            }
        } catch (VirtualMachineError e) {
            SystemFailure.initiateFailure(e);
        } catch (Throwable throwable) {
            logger.error("Error invoking statistic suppliers", throwable);
        } finally {
            long end = System.nanoTime();
            statSamplerStats.incSampleCallbackDuration(TimeUnit.NANOSECONDS.toMillis(end - start));
            statSamplerStats.incSampleCallbackErrors(errors);
            statSamplerStats.setSampleCallbacks(suppliers);
        }
    }

    public void stop() {
        if (executor != null) {
            this.executor.shutdown();
        }
    }
}

18 View Complete Implementation : StoppableCondition.java
Copyright Apache License 2.0
Author : apache
/**
 * This clreplaced is functionally equivalent to {@link java.util.concurrent.locks.Condition}; however it
 * only implements the acquire(long) method. Its purpose is to perform a cancellation check
 */
public clreplaced StoppableCondition implements java.io.Serializable {

    private static final long serialVersionUID = -7091681525970431937L;

    /**
     * The underlying condition *
     */
    private final Condition condition;

    /**
     * The cancellation object
     */
    private final CancelCriterion stopper;

    public static final long TIME_TO_WAIT = 15000;

    /**
     * Create a new StoppableCondition based on given condition and cancellation criterion
     *
     * @param c the underlying condition
     */
    StoppableCondition(Condition c, CancelCriterion stopper) {
        replacedert.replacedertTrue(stopper != null);
        this.condition = c;
        this.stopper = stopper;
    }

    public boolean await(long timeoutMs) throws InterruptedException {
        stopper.checkCancelInProgress(null);
        return condition.await(timeoutMs, TimeUnit.MILLISECONDS);
    }

    public synchronized void signal() {
        condition.signal();
    }

    public synchronized void signalAll() {
        condition.signalAll();
    }
}

18 View Complete Implementation : StoppableCountDownLatch.java
Copyright Apache License 2.0
Author : apache
/**
 * This clreplaced is a "stoppable" cover for {@link CountDownLatch}.
 */
public clreplaced StoppableCountDownLatch {

    static final String RETRY_TIME_MILLIS_PROPERTY = GEMFIRE_PREFIX + "stoppable-retry-interval";

    static final long RETRY_TIME_MILLIS_DEFAULT = 2000;

    static final long RETRY_TIME_NANOS = MILLISECONDS.toNanos(Long.getLong(RETRY_TIME_MILLIS_PROPERTY, RETRY_TIME_MILLIS_DEFAULT));

    private final CountDownLatch delegate;

    private final CancelCriterion stopper;

    /**
     * This is how often waiters will wake up to check for cancellation
     */
    private final long retryIntervalNanos;

    private final NanoTimer nanoTimer;

    /**
     * @param stopper the CancelCriterion to check before awaiting
     * @param count the number of times {@link #countDown} must be invoked before threads can preplaced
     *        through {@link #await()}
     *
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public StoppableCountDownLatch(final CancelCriterion stopper, final int count) {
        this(stopper, count, RETRY_TIME_NANOS, System::nanoTime);
    }

    StoppableCountDownLatch(final CancelCriterion stopper, final int count, final long retryIntervalNanos, final NanoTimer nanoTimer) {
        replacedert.replacedertTrue(stopper != null);
        delegate = new CountDownLatch(count);
        this.stopper = stopper;
        this.retryIntervalNanos = retryIntervalNanos;
        this.nanoTimer = nanoTimer;
    }

    public void await() throws InterruptedException {
        do {
            stopper.checkCancelInProgress(null);
        } while (!delegate.await(retryIntervalNanos, NANOSECONDS));
    }

    public boolean await(final long timeout, final TimeUnit unit) throws InterruptedException {
        stopper.checkCancelInProgress(null);
        long timeoutNanos = unit.toNanos(timeout);
        if (timeoutNanos > retryIntervalNanos) {
            return awaitWithCheck(timeoutNanos);
        }
        return delegate.await(timeoutNanos, NANOSECONDS);
    }

    /**
     * @param timeoutMillis how long to wait in milliseconds
     *
     * @return true if it was unlatched
     */
    public boolean await(final long timeoutMillis) throws InterruptedException {
        stopper.checkCancelInProgress(null);
        long timeoutNanos = MILLISECONDS.toNanos(timeoutMillis);
        if (timeoutNanos > retryIntervalNanos) {
            return awaitWithCheck(timeoutNanos);
        }
        return delegate.await(timeoutNanos, NANOSECONDS);
    }

    public void countDown() {
        delegate.countDown();
    }

    public long getCount() {
        return delegate.getCount();
    }

    @Override
    public String toString() {
        return "(Stoppable) " + delegate;
    }

    long retryIntervalNanos() {
        return retryIntervalNanos;
    }

    private boolean awaitWithCheck(final long timeoutNanos) throws InterruptedException {
        long startNanos = nanoTimer.nanoTime();
        boolean unlatched;
        do {
            stopper.checkCancelInProgress(null);
            unlatched = delegate.await(retryIntervalNanos, NANOSECONDS);
        } while (!unlatched && nanoTimer.nanoTime() - startNanos < timeoutNanos);
        return unlatched;
    }

    @FunctionalInterface
    interface NanoTimer {

        long nanoTime();
    }
}

18 View Complete Implementation : StoppableReentrantLock.java
Copyright Apache License 2.0
Author : apache
/**
 * Instances of {@link java.util.concurrent.locks.Lock} that respond to cancellations
 */
public clreplaced StoppableReentrantLock {

    /**
     * the underlying lock
     */
    private final ReentrantLock lock;

    /**
     * This is how often waiters will wake up to check for cancellation
     */
    // milliseconds
    private static final long RETRY_TIME = 15 * 1000;

    /**
     * the cancellation criterion
     */
    private final CancelCriterion stopper;

    /**
     * Create a new instance with the given cancellation criterion
     *
     * @param stopper the cancellation criterion
     */
    public StoppableReentrantLock(CancelCriterion stopper) {
        replacedert.replacedertTrue(stopper != null);
        this.lock = new ReentrantLock();
        this.stopper = stopper;
    }

    /**
     * Create a new instance with given fairness and cancellation criterion
     *
     * @param fair whether to be fair
     * @param stopper the cancellation criterion
     */
    public StoppableReentrantLock(boolean fair, CancelCriterion stopper) {
        replacedert.replacedertTrue(stopper != null);
        this.stopper = stopper;
        this.lock = new ReentrantLock();
    }

    public void lock() {
        for (; ; ) {
            boolean interrupted = Thread.interrupted();
            try {
                lockInterruptibly();
                break;
            } catch (InterruptedException e) {
                interrupted = true;
            } finally {
                if (interrupted)
                    Thread.currentThread().interrupt();
            }
        }
    // for
    }

    public void lockInterruptibly() throws InterruptedException {
        for (; ; ) {
            stopper.checkCancelInProgress(null);
            if (lock.tryLock(RETRY_TIME, TimeUnit.MILLISECONDS))
                break;
        }
    }

    /**
     * @return true if the lock is acquired
     */
    public boolean tryLock() {
        stopper.checkCancelInProgress(null);
        return lock.tryLock();
    }

    /**
     * @param timeoutMs how long to wait in milliseconds
     * @return true if the lock was acquired
     */
    public boolean tryLock(long timeoutMs) throws InterruptedException {
        stopper.checkCancelInProgress(null);
        return lock.tryLock(timeoutMs, TimeUnit.MILLISECONDS);
    }

    public void unlock() {
        lock.unlock();
    }

    /**
     * @return the new stoppable condition
     */
    public StoppableCondition newCondition() {
        return new StoppableCondition(lock.newCondition(), stopper);
    }

    /**
     * @return true if it is held
     */
    public boolean isHeldByCurrentThread() {
        return lock.isHeldByCurrentThread();
    }
}

18 View Complete Implementation : TXFailoverOpTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced TXFailoverOpTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private ConnectionManager manager;

    private EndpointManager endpointManager;

    private QueueManager queueManager;

    private RegisterInterestTracker riTracker;

    private CancelCriterion cancelCriterion;

    private PoolImpl mockPool;

    @Before
    public void setUp() {
        endpointManager = mock(EndpointManager.clreplaced);
        queueManager = mock(QueueManager.clreplaced);
        manager = mock(ConnectionManager.clreplaced);
        riTracker = mock(RegisterInterestTracker.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        mockPool = mock(PoolImpl.clreplaced);
        when(mockPool.execute(any())).thenThrow(new TransactionException()).thenReturn(true);
    }

    private OpExecutorImpl getTestableOpExecutorImpl() {
        return new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, cancelCriterion, mockPool) {

            @Override
            public ServerLocation getNextOpServerLocation() {
                return mock(ServerLocation.clreplaced);
            }

            @Override
            protected Object executeOnServer(ServerLocation p_server, Op op, boolean accessed, boolean onlyUseExistingCnx) {
                throw new ServerConnectivityException();
            }
        };
    }

    @Test
    public void txFailoverThrowsTransactionExceptionBack() throws Exception {
        OpExecutorImpl exec = getTestableOpExecutorImpl();
        exec.setupServerAffinity(Boolean.TRUE);
        expectedException.expect(TransactionException.clreplaced);
        TXFailoverOp.execute(exec, 1);
    }
}

17 View Complete Implementation : ConnectionManagerJUnitTest.java
Copyright Apache License 2.0
Author : apache
@Category({ ClientServerTest.clreplaced })
public clreplaced ConnectionManagerJUnitTest {

    private static final long TIMEOUT_MILLIS = 30 * 1000;

    // Some machines do not have a monotonic clock.
    private static final long ALLOWABLE_ERROR_IN_MILLIS = 100;

    ConnectionManager manager;

    private InternalLogWriter logger;

    protected DummyFactory factory;

    private DistributedSystem ds;

    private ScheduledExecutorService background;

    protected EndpointManager endpointManager;

    private CancelCriterion cancelCriterion;

    private PoolStats poolStats;

    @Before
    public void setUp() {
        this.logger = new LocalLogWriter(FINEST.intLevel(), System.out);
        factory = new DummyFactory();
        Properties properties = new Properties();
        properties.put(MCAST_PORT, "0");
        properties.put(LOCATORS, "");
        ds = DistributedSystem.connect(properties);
        background = Executors.newSingleThreadScheduledExecutor();
        poolStats = new PoolStats(ds, "connectionManagerJUnitTest");
        endpointManager = new EndpointManagerImpl("pool", ds, ds.getCancelCriterion(), poolStats);
        cancelCriterion = new CancelCriterion() {

            @Override
            public String cancelInProgress() {
                return null;
            }

            @Override
            public RuntimeException generateCancelledException(Throwable e) {
                return null;
            }
        };
    }

    @After
    public void tearDown() throws InterruptedException {
        ds.disconnect();
        if (manager != null) {
            manager.close(false);
        }
        background.shutdownNow();
    }

    @Test
    public void testAddVarianceToInterval() {
        replacedertThat(ConnectionManagerImpl.addVarianceToInterval(0)).as("Zero gets zero variance").isEqualTo(0);
        replacedertThat(ConnectionManagerImpl.addVarianceToInterval(300000)).as("Large value gets +/-10% variance").isNotEqualTo(300000).isGreaterThanOrEqualTo(270000).isLessThanOrEqualTo(330000);
        replacedertThat(ConnectionManagerImpl.addVarianceToInterval(9)).as("Small value gets +/-1 variance").isNotEqualTo(9).isGreaterThanOrEqualTo(8).isLessThanOrEqualTo(10);
    }

    @Test
    public void testGet() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 3, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection[] conn = new Connection[4];
        conn[0] = manager.borrowConnection(0);
        replacedert.replacedertEquals(1, factory.creates);
        manager.returnConnection(conn[0]);
        conn[0] = manager.borrowConnection(0);
        replacedert.replacedertEquals(1, factory.creates);
        conn[1] = manager.borrowConnection(0);
        manager.returnConnection(conn[0]);
        manager.returnConnection(conn[1]);
        replacedert.replacedertEquals(2, factory.creates);
        conn[0] = manager.borrowConnection(0);
        conn[1] = manager.borrowConnection(0);
        conn[2] = manager.borrowConnection(0);
        replacedert.replacedertEquals(3, factory.creates);
        try {
            conn[4] = manager.borrowConnection(10);
            fail("Should have received an all connections in use exception");
        } catch (AllConnectionsInUseException e) {
        // expected exception
        }
    }

    @Test
    public void testPrefill() throws InterruptedException {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 10, 2, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        final String descrip = manager.toString();
        WaitCriterion ev = new WaitCriterion() {

            @Override
            public boolean done() {
                return factory.creates == 2 && factory.destroys == 0;
            }

            @Override
            public String description() {
                return "waiting for manager " + descrip;
            }
        };
        GeodeAwaitility.await().untilreplacederted(ev);
    }

    @Test
    public void testInvalidateConnection() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 10, 0, 0L, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection conn = manager.borrowConnection(0);
        replacedert.replacedertEquals(1, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        conn.destroy();
        manager.returnConnection(conn);
        replacedert.replacedertEquals(1, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
        conn = manager.borrowConnection(0);
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
    }

    @Test
    public void testInvalidateServer() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 10, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        ServerLocation server1 = new ServerLocation("localhost", 1);
        ServerLocation server2 = new ServerLocation("localhost", 2);
        factory.nextServer = server1;
        Connection conn1 = manager.borrowConnection(0);
        Connection conn2 = manager.borrowConnection(0);
        Connection conn3 = manager.borrowConnection(0);
        factory.nextServer = server2;
        Connection conn4 = manager.borrowConnection(0);
        replacedert.replacedertEquals(4, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        manager.returnConnection(conn2);
        endpointManager.serverCrashed(conn2.getEndpoint());
        replacedert.replacedertEquals(3, factory.destroys);
        conn1.destroy();
        manager.returnConnection(conn1);
        replacedert.replacedertEquals(3, factory.destroys);
        manager.returnConnection(conn3);
        manager.returnConnection(conn4);
        replacedert.replacedertEquals(3, factory.destroys);
        manager.borrowConnection(0);
        replacedert.replacedertEquals(4, factory.creates);
        replacedert.replacedertEquals(3, factory.destroys);
    }

    @Test
    public void testIdleExpiration() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException {
        final long idleTimeoutMillis = 300;
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 5, 2, idleTimeoutMillis, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        {
            factory.waitWhile(() -> factory.creates < 2);
            replacedert.replacedertEquals(2, factory.creates);
            replacedert.replacedertEquals(0, factory.destroys);
            replacedert.replacedertEquals(0, factory.closes);
            replacedert.replacedertEquals(0, poolStats.getIdleExpire());
        // no need to wait; dangerous because it gives connections a chance to expire
        // //wait for prefill task to finish.
        // Thread.sleep(100);
        }
        Connection conn1 = manager.borrowConnection(500);
        Connection conn2 = manager.borrowConnection(500);
        Connection conn3 = manager.borrowConnection(500);
        Connection conn4 = manager.borrowConnection(500);
        Connection conn5 = manager.borrowConnection(500);
        // wait to make sure checked out connections aren't timed out
        Thread.sleep(idleTimeoutMillis * 2);
        replacedert.replacedertEquals(5, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        replacedert.replacedertEquals(0, factory.closes);
        replacedert.replacedertEquals(0, poolStats.getIdleExpire());
        {
            // make sure a connection that has been preplacedivated can idle-expire
            conn1.preplacedivate(true);
            long elapsedMillis = factory.waitWhile(() -> factory.destroys < 1);
            replacedert.replacedertEquals(5, factory.creates);
            replacedert.replacedertEquals(1, factory.destroys);
            replacedert.replacedertEquals(1, factory.closes);
            replacedert.replacedertEquals(1, poolStats.getIdleExpire());
            checkIdleTimeout(idleTimeoutMillis, elapsedMillis);
        }
        // now return all other connections to pool and verify that just 2 expire
        manager.returnConnection(conn2);
        manager.returnConnection(conn3);
        manager.returnConnection(conn4);
        manager.returnConnection(conn5);
        {
            long elapsedMillis = factory.waitWhile(() -> factory.destroys < 3);
            replacedert.replacedertEquals(5, factory.creates);
            replacedert.replacedertEquals(3, factory.destroys);
            replacedert.replacedertEquals(3, factory.closes);
            replacedert.replacedertEquals(3, poolStats.getIdleExpire());
            checkIdleTimeout(idleTimeoutMillis, elapsedMillis);
        }
        // wait to make sure min-connections don't time out
        Thread.sleep(idleTimeoutMillis * 2);
        replacedert.replacedertEquals(5, factory.creates);
        replacedert.replacedertEquals(3, factory.destroys);
        replacedert.replacedertEquals(3, factory.closes);
        replacedert.replacedertEquals(3, poolStats.getIdleExpire());
    }

    private void checkIdleTimeout(final long idleTimeoutMillis, long elapsedMillis) {
        replacedert.replacedertTrue("Elapsed " + elapsedMillis + " is less than idle timeout " + idleTimeoutMillis, elapsedMillis >= (idleTimeoutMillis - ALLOWABLE_ERROR_IN_MILLIS));
        replacedert.replacedertTrue("Elapsed " + elapsedMillis + " is greater than idle timeout " + idleTimeoutMillis, elapsedMillis <= (idleTimeoutMillis + ALLOWABLE_ERROR_IN_MILLIS));
    }

    @Test
    public void testBug41516() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException {
        final long idleTimeoutMillis = 300;
        final long BORROW_TIMEOUT_MILLIS = 500;
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 2, 1, idleTimeoutMillis, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection conn1 = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        Connection conn2 = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        // Return some connections, let them idle expire
        manager.returnConnection(conn1);
        manager.returnConnection(conn2);
        {
            long elapsedMillis = factory.waitWhile(() -> factory.destroys < 1);
            replacedert.replacedertEquals(1, factory.destroys);
            replacedert.replacedertEquals(1, factory.closes);
            replacedert.replacedertEquals(1, poolStats.getIdleExpire());
            replacedert.replacedertTrue("Elapsed " + elapsedMillis + " is less than idle timeout " + idleTimeoutMillis, elapsedMillis + ALLOWABLE_ERROR_IN_MILLIS >= idleTimeoutMillis);
        }
        // Ok, now get some connections that fill our queue
        Connection ping1 = manager.borrowConnection(new ServerLocation("localhost", 5), false);
        Connection ping2 = manager.borrowConnection(new ServerLocation("localhost", 5), false);
        manager.returnConnection(ping1);
        manager.returnConnection(ping2);
        manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        long startNanos = nowNanos();
        try {
            manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
            fail("Didn't get an exception");
        } catch (AllConnectionsInUseException e) {
        // expected
        }
        long elapsedMillis = elapsedMillis(startNanos);
        replacedert.replacedertTrue("Elapsed = " + elapsedMillis, elapsedMillis >= BORROW_TIMEOUT_MILLIS - ALLOWABLE_ERROR_IN_MILLIS);
    }

    @Test
    public void testLifetimeExpiration() throws InterruptedException, AllConnectionsInUseException, NoAvailableServersException, Throwable {
        int lifetimeTimeout = 500;
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 2, 2, -1, lifetimeTimeout, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        {
            factory.waitWhile(() -> factory.creates < 2);
            replacedert.replacedertEquals(2, factory.creates);
            replacedert.replacedertEquals(0, factory.destroys);
            replacedert.replacedertEquals(0, factory.finds);
        }
        // need to start a thread that keeps the connections busy
        // so that their last access time keeps changing
        AtomicReference exception = new AtomicReference();
        int updaterCount = 2;
        UpdaterThread[] updaters = new UpdaterThread[updaterCount];
        for (int i = 0; i < updaterCount; i++) {
            updaters[i] = new UpdaterThread(null, exception, i, (lifetimeTimeout / 10) * 2);
        }
        for (int i = 0; i < updaterCount; i++) {
            updaters[i].start();
        }
        {
            long durationMillis = factory.waitWhile(() -> factory.finds < 2);
            replacedert.replacedertEquals(2, factory.finds);
            // server shouldn't have changed so no increase in creates or destroys
            replacedert.replacedertEquals(2, factory.creates);
            replacedert.replacedertEquals(0, factory.destroys);
            replacedert.replacedertEquals(0, factory.closes);
            replacedert.replacedertTrue("took too long to expire lifetime; expected=" + lifetimeTimeout + " but took=" + durationMillis, durationMillis < lifetimeTimeout * 5);
        }
        for (int i = 0; i < updaterCount; i++) {
            ThreadUtils.join(updaters[i], 30 * 1000);
        }
        if (exception.get() != null) {
            throw (Throwable) exception.get();
        }
        for (int i = 0; i < updaterCount; i++) {
            replacedert.replacedertFalse("Updater [" + i + "] is still running", updaters[i].isAlive());
        }
    }

    @Test
    public void testExclusiveConnectionAccess() throws Throwable {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 1, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        AtomicReference exception = new AtomicReference();
        AtomicBoolean haveConnection = new AtomicBoolean();
        int updaterCount = 10;
        UpdaterThread[] updaters = new UpdaterThread[updaterCount];
        for (int i = 0; i < updaterCount; i++) {
            updaters[i] = new UpdaterThread(haveConnection, exception, i);
        }
        for (int i = 0; i < updaterCount; i++) {
            updaters[i].start();
        }
        for (int i = 0; i < updaterCount; i++) {
            ThreadUtils.join(updaters[i], 30 * 1000);
        }
        if (exception.get() != null) {
            throw (Throwable) exception.get();
        }
        for (int i = 0; i < updaterCount; i++) {
            replacedert.replacedertFalse("Updater [" + i + "] is still running", updaters[i].isAlive());
        }
    }

    @Test
    public void testClose() throws AllConnectionsInUseException, NoAvailableServersException, InterruptedException {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 10, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection conn1 = manager.borrowConnection(0);
        manager.borrowConnection(0);
        manager.returnConnection(conn1);
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        manager.close(false);
        replacedert.replacedertEquals(2, factory.closes);
        replacedert.replacedertEquals(2, factory.destroys);
    }

    @Test
    public void testExchangeConnection() throws Exception {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 2, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection conn1 = manager.borrowConnection(10);
        Connection conn2 = manager.borrowConnection(10);
        try {
            manager.borrowConnection(10);
            fail("Exepected no servers available");
        } catch (AllConnectionsInUseException e) {
        // expected
        }
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        replacedert.replacedertEquals(2, manager.getConnectionCount());
        Connection conn3 = manager.exchangeConnection(conn1, Collections.emptySet());
        replacedert.replacedertEquals(3, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
        replacedert.replacedertEquals(2, manager.getConnectionCount());
        manager.returnConnection(conn2);
        replacedert.replacedertEquals(3, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
        replacedert.replacedertEquals(2, manager.getConnectionCount());
        Connection conn4 = manager.exchangeConnection(conn3, Collections.singleton(conn3.getServer()));
        replacedert.replacedertEquals(4, factory.creates);
        replacedert.replacedertEquals(2, factory.destroys);
        replacedert.replacedertEquals(2, manager.getConnectionCount());
        manager.returnConnection(conn4);
    }

    /**
     * This tests that a deadlock between connection formation and connection pool closing has been
     * fixed. See GEODE-4615
     */
    @Test
    public void testThatMapCloseCausesCacheClosedException() throws Exception {
        final ConnectionManagerImpl connectionManager = new ConnectionManagerImpl("pool", factory, endpointManager, 2, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager = connectionManager;
        connectionManager.start(background);
        final ConnectionManagerImpl.ConnectionMap connectionMap = connectionManager.allConnectionsMap;
        final int thread1 = 0;
        final int thread2 = 1;
        final boolean[] ready = new boolean[2];
        Thread thread = new Thread("ConnectionManagerJUnitTest thread") {

            @Override
            public void run() {
                setReady(ready, thread1);
                waitUntilReady(ready, thread2);
                connectionMap.close(false);
            }
        };
        thread.setDaemon(true);
        thread.start();
        try {
            Connection firstConnection = connectionManager.borrowConnection(0);
            synchronized (firstConnection) {
                setReady(ready, thread2);
                waitUntilReady(ready, thread1);
                // the other thread will now try to close the connection map but it will block
                // because this thread has locked one of the connections
                await().until(() -> connectionMap.closing);
                try {
                    connectionManager.borrowConnection(0);
                    fail("expected a CacheClosedException");
                } catch (CacheClosedException e) {
                // expected
                }
            }
        } finally {
            if (thread.isAlive()) {
                System.out.println("stopping background thread");
                thread.interrupt();
                thread.join();
            }
        }
    }

    private void setReady(boolean[] ready, int index) {
        System.out.println(Thread.currentThread().getName() + ": setting that thread" + (index + 1) + " is ready");
        synchronized (ready) {
            ready[index] = true;
        }
    }

    private void waitUntilReady(boolean[] ready, int index) {
        System.out.println(Thread.currentThread().getName() + ": waiting for thread" + (index + 1) + " to be ready");
        await().until(() -> {
            synchronized (ready) {
                return (ready[index]);
            }
        });
    }

    private long nowNanos() {
        return System.nanoTime();
    }

    private long elapsedNanos(long startNanos) {
        return nowNanos() - startNanos;
    }

    private long elapsedMillis(long startNanos) {
        return NANOSECONDS.toMillis(elapsedNanos(startNanos));
    }

    @Test
    public void testBlocking() throws Throwable {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 1, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        final Connection conn1 = manager.borrowConnection(10);
        long BORROW_TIMEOUT_MILLIS = 300;
        long startNonos = nowNanos();
        try {
            manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
            fail("Should have received no servers available");
        } catch (AllConnectionsInUseException expected) {
        }
        long elapsedMillis = elapsedMillis(startNonos);
        replacedert.replacedertTrue("Should have blocked for " + BORROW_TIMEOUT_MILLIS + " millis for a connection", elapsedMillis >= BORROW_TIMEOUT_MILLIS - ALLOWABLE_ERROR_IN_MILLIS);
        Thread returnThread = new Thread() {

            @Override
            public void run() {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    fail("interrupted");
                }
                manager.returnConnection(conn1);
            }
        };
        returnThread.start();
        BORROW_TIMEOUT_MILLIS = 5000;
        startNonos = nowNanos();
        Connection conn2 = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        elapsedMillis = elapsedMillis(startNonos);
        replacedert.replacedertTrue("Should have blocked for less than " + BORROW_TIMEOUT_MILLIS + " milliseconds", elapsedMillis < BORROW_TIMEOUT_MILLIS + ALLOWABLE_ERROR_IN_MILLIS);
        manager.returnConnection(conn2);
        final Connection conn3 = manager.borrowConnection(10);
        Thread invalidateThread = new Thread() {

            @Override
            public void run() {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    fail("interrupted");
                }
                conn3.destroy();
                manager.returnConnection(conn3);
            }
        };
        invalidateThread.start();
        startNonos = nowNanos();
        conn2 = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        elapsedMillis = elapsedMillis(startNonos);
        replacedert.replacedertTrue("Should have blocked for less than " + BORROW_TIMEOUT_MILLIS + " milliseconds", elapsedMillis < BORROW_TIMEOUT_MILLIS + ALLOWABLE_ERROR_IN_MILLIS);
        manager.returnConnection(conn2);
        final Connection conn4 = manager.borrowConnection(10);
        Thread invalidateThread2 = new Thread() {

            @Override
            public void run() {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    fail("interrupted");
                }
                endpointManager.serverCrashed(conn4.getEndpoint());
                manager.returnConnection(conn4);
            }
        };
        invalidateThread2.start();
        startNonos = nowNanos();
        conn2 = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
        elapsedMillis = elapsedMillis(startNonos);
        replacedert.replacedertTrue("Should have blocked for less than " + BORROW_TIMEOUT_MILLIS + " milliseconds", elapsedMillis < BORROW_TIMEOUT_MILLIS + ALLOWABLE_ERROR_IN_MILLIS);
        manager.returnConnection(conn2);
    }

    @Test
    public void testExplicitServer() throws Exception {
        manager = new ConnectionManagerImpl("pool", factory, endpointManager, 1, 0, -1, -1, logger, 60 * 1000, cancelCriterion, poolStats);
        manager.start(background);
        Connection conn1 = manager.borrowConnection(0);
        try {
            manager.borrowConnection(10);
            fail("Should have received an error");
        } catch (AllConnectionsInUseException expected) {
        // do nothing
        }
        Connection conn3 = manager.borrowConnection(new ServerLocation("localhost", -2), false);
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(0, factory.destroys);
        replacedert.replacedertEquals(0, factory.closes);
        manager.returnConnection(conn3);
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
        replacedert.replacedertEquals(1, factory.closes);
        manager.returnConnection(conn1);
        replacedert.replacedertEquals(2, factory.creates);
        replacedert.replacedertEquals(1, factory.destroys);
        replacedert.replacedertEquals(1, factory.closes);
    }

    private clreplaced UpdaterThread extends Thread {

        private AtomicReference exception;

        private final AtomicBoolean haveConnection;

        private int id;

        private final int iterations;

        public UpdaterThread(AtomicBoolean haveConnection, AtomicReference exception, int id) {
            this(haveConnection, exception, id, 10);
        }

        public UpdaterThread(AtomicBoolean haveConnection, AtomicReference exception, int id, int iterations) {
            this.haveConnection = haveConnection;
            this.exception = exception;
            this.id = id;
            this.iterations = iterations;
        }

        private Connection borrow(int i) {
            long startNanos = nowNanos();
            long BORROW_TIMEOUT_MILLIS = 2000;
            Connection conn = manager.borrowConnection(BORROW_TIMEOUT_MILLIS);
            if (haveConnection != null) {
                replacedert.replacedertTrue("Updater[" + id + "] loop[" + i + "] Someone else has the connection!", haveConnection.compareAndSet(false, true));
            }
            long elapsedMillis = elapsedMillis(startNanos);
            replacedert.replacedertTrue("Elapsed time (" + elapsedMillis + ") >= " + BORROW_TIMEOUT_MILLIS, elapsedMillis < BORROW_TIMEOUT_MILLIS + ALLOWABLE_ERROR_IN_MILLIS);
            return conn;
        }

        @Override
        public void run() {
            int i = 0;
            Connection conn = null;
            try {
                for (i = 0; i < iterations; i++) {
                    conn = borrow(i);
                    try {
                        Thread.sleep(10);
                        if (haveConnection != null) {
                            replacedert.replacedertTrue("Updater[" + id + "] loop[" + i + "] Someone else changed the connection flag", haveConnection.compareAndSet(true, false));
                        }
                    } finally {
                        manager.returnConnection(conn);
                    }
                }
            } catch (Throwable t) {
                this.exception.compareAndSet(null, new Exception("ERROR Updater[" + id + "] loop[" + i + "]", t));
            }
        }
    }

    public clreplaced DummyFactory implements ConnectionFactory {

        public ServerLocation nextServer = new ServerLocation("localhost", -1);

        protected volatile int creates;

        protected volatile int destroys;

        protected volatile int closes;

        protected volatile int finds;

        /**
         * Wait as long as "whileCondition" is true.
         * The wait will timeout after TIMEOUT_MILLIS has elapsed.
         *
         * @return the elapsed time in milliseconds.
         */
        public synchronized long waitWhile(BooleanSupplier whileCondition) throws InterruptedException {
            final long startNanos = nowNanos();
            long remainingMillis = TIMEOUT_MILLIS;
            while (whileCondition.getAsBoolean() && remainingMillis > 0) {
                wait(remainingMillis);
                remainingMillis = TIMEOUT_MILLIS - elapsedMillis(startNanos);
            }
            return elapsedMillis(startNanos);
        }

        @Override
        public ServerDenyList getDenyList() {
            return new ServerDenyList(1);
        }

        @Override
        public ServerLocation findBestServer(ServerLocation currentServer, Set excludedServers) {
            synchronized (this) {
                finds++;
                this.notifyAll();
            }
            if (excludedServers != null) {
                if (excludedServers.contains(nextServer)) {
                    return null;
                }
            }
            return nextServer;
        }

        @Override
        public Connection createClientToServerConnection(Set excluded) {
            return createClientToServerConnection(nextServer, true);
        }

        /*
     * (non-Javadoc)
     *
     * @see
     * org.apache.geode.cache.client.internal.ConnectionFactory#createClientToServerConnection(org.
     * apache.geode.distributed.internal.ServerLocation)
     */
        @Override
        public Connection createClientToServerConnection(final ServerLocation location, boolean forQueue) {
            synchronized (this) {
                creates++;
                this.notifyAll();
            }
            DistributedMember fakeMember = null;
            fakeMember = new InternalDistributedMember("localhost", 555);
            final DistributedMember member = fakeMember;
            return new Connection() {

                private Endpoint endpoint = endpointManager.referenceEndpoint(location, member);

                @Override
                public void destroy() {
                    synchronized (DummyFactory.this) {
                        destroys++;
                        DummyFactory.this.notifyAll();
                    }
                }

                @Override
                public ServerLocation getServer() {
                    return location;
                }

                @Override
                public ByteBuffer getCommBuffer() {
                    return null;
                }

                @Override
                public Socket getSocket() {
                    return null;
                }

                @Override
                public ConnectionStats getStats() {
                    return null;
                }

                @Override
                public void close(boolean keepAlive) throws Exception {
                    synchronized (DummyFactory.this) {
                        closes++;
                        DummyFactory.this.notifyAll();
                    }
                }

                @Override
                public Endpoint getEndpoint() {
                    return endpoint;
                }

                @Override
                public ServerQueueStatus getQueueStatus() {
                    return null;
                }

                @Override
                public Object execute(Op op) throws Exception {
                    return op.attempt(this);
                }

                @Override
                public boolean isDestroyed() {
                    return false;
                }

                @Override
                public void emergencyClose() {
                }

                @Override
                public short getWanSiteVersion() {
                    return -1;
                }

                @Override
                public int getDistributedSystemId() {
                    return -1;
                }

                @Override
                public void setWanSiteVersion(short wanSiteVersion) {
                }

                @Override
                public InputStream getInputStream() {
                    return null;
                }

                @Override
                public OutputStream getOutputStream() {
                    return null;
                }

                @Override
                public void setConnectionID(long id) {
                }

                @Override
                public long getConnectionID() {
                    return 0;
                }
            };
        }

        @Override
        public ClientUpdater createServerToClientConnection(Endpoint endpoint, QueueManager manager, boolean isPrimary, ClientUpdater failedUpdater) {
            return null;
        }
    }
}

17 View Complete Implementation : OpExecutorImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Called from the client and execute client to server requests against servers. Handles retrying to
 * different servers, and marking servers dead if we get exception from them.
 *
 * @since GemFire 5.7
 */
public clreplaced OpExecutorImpl implements ExecutablePool {

    private static final Logger logger = LogService.getLogger();

    private static final boolean TRY_SERVERS_ONCE = Boolean.getBoolean(GeodeGlossary.GEMFIRE_PREFIX + "PoolImpl.TRY_SERVERS_ONCE");

    static final int TX_RETRY_ATTEMPT = Integer.getInteger(GeodeGlossary.GEMFIRE_PREFIX + "txRetryAttempt", 500);

    private final ConnectionManager connectionManager;

    private final int retryAttempts;

    private final long serverTimeout;

    private final EndpointManager endpointManager;

    private final RegisterInterestTracker riTracker;

    private final QueueManager queueManager;

    private final CancelCriterion cancelCriterion;

    private PoolImpl /* final */
    pool;

    private final ThreadLocal<Boolean> serverAffinity = ThreadLocal.withInitial(() -> Boolean.FALSE);

    private boolean serverAffinityFailover = false;

    private final ThreadLocal<ServerLocation> affinityServerLocation = new ThreadLocal<>();

    private final ThreadLocal<Integer> affinityRetryCount = ThreadLocal.withInitial(() -> 0);

    public OpExecutorImpl(ConnectionManager connectionManager, QueueManager queueManager, EndpointManager endpointManager, RegisterInterestTracker riTracker, int retryAttempts, long serverTimeout, CancelCriterion cancelCriterion, PoolImpl pool) {
        this.connectionManager = connectionManager;
        this.queueManager = queueManager;
        this.endpointManager = endpointManager;
        this.riTracker = riTracker;
        this.retryAttempts = retryAttempts;
        this.serverTimeout = serverTimeout;
        this.cancelCriterion = cancelCriterion;
        this.pool = pool;
    }

    @Override
    public Object execute(Op op) {
        return execute(op, retryAttempts);
    }

    @Override
    public Object execute(Op op, int retries) {
        if (serverAffinity.get()) {
            ServerLocation loc = affinityServerLocation.get();
            if (loc == null) {
                loc = getNextOpServerLocation();
                affinityServerLocation.set(loc);
                if (logger.isDebugEnabled()) {
                    logger.debug("setting server affinity to {}", affinityServerLocation.get());
                }
            }
            return executeWithServerAffinity(loc, op);
        }
        Connection conn = connectionManager.borrowConnection(serverTimeout);
        try {
            Set<ServerLocation> attemptedServers = null;
            for (int attempt = 0; true; attempt++) {
                // when an op is retried we may need to try to recover the previous
                // attempt's version stamp
                if (attempt == 1 && (op instanceof AbstractOp)) {
                    AbstractOp absOp = (AbstractOp) op;
                    absOp.getMessage().setIsRetry();
                }
                try {
                    authenticateIfRequired(conn, op);
                    return executeWithPossibleReAuthentication(conn, op);
                } catch (MessageTooLargeException e) {
                    throw new GemFireIOException("unable to transmit message to server", e);
                } catch (Exception e) {
                    handleException(e, conn, attempt, attempt >= retries && retries != -1);
                    if (null == attemptedServers) {
                        // don't allocate this until we need it
                        attemptedServers = new HashSet<>();
                    }
                    attemptedServers.add(conn.getServer());
                    try {
                        conn = connectionManager.exchangeConnection(conn, attemptedServers);
                    } catch (NoAvailableServersException nse) {
                        // if retries is -1, don't try again after the last server has failed
                        if (retries == -1 || TRY_SERVERS_ONCE) {
                            handleException(e, conn, attempt, true);
                        } else {
                            // try one of the failed servers again, until we exceed the retry attempts.
                            attemptedServers.clear();
                            try {
                                conn = connectionManager.exchangeConnection(conn, attemptedServers);
                            } catch (NoAvailableServersException nse2) {
                                handleException(e, conn, attempt, true);
                            }
                        }
                    }
                }
            }
        } finally {
            connectionManager.returnConnection(conn);
        }
    }

    /**
     * execute the given op on the given server. If the server cannot be reached, sends a
     * TXFailoverOp, then retries the given op
     *
     * @param loc the server to execute the op on
     * @param op the op to execute
     * @return the result of execution
     */
    Object executeWithServerAffinity(ServerLocation loc, Op op) {
        final int initialRetryCount = getAffinityRetryCount();
        try {
            try {
                return executeOnServer(loc, op, true, false);
            } catch (ServerConnectivityException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("caught exception while executing with affinity:{}", e.getMessage(), e);
                }
                if (!serverAffinityFailover || e instanceof ServerOperationException) {
                    throw e;
                }
                int retryCount = getAffinityRetryCount();
                if ((retryAttempts != -1 && retryCount >= retryAttempts) || retryCount > TX_RETRY_ATTEMPT) {
                    // prevent stack overflow
                    throw e;
                }
                setAffinityRetryCount(retryCount + 1);
            }
            affinityServerLocation.set(null);
            if (logger.isDebugEnabled()) {
                logger.debug("reset server affinity: attempting txFailover");
            }
            // send TXFailoverOp, so that new server can
            // do bootstrapping, then re-execute original op
            AbstractOp absOp = (AbstractOp) op;
            absOp.getMessage().setIsRetry();
            int transactionId = absOp.getMessage().getTransactionId();
            // for CommitOp we do not have transactionId in AbstractOp
            // so set it explicitly for TXFailoverOp
            TXFailoverOp.execute(pool, transactionId);
            if (op instanceof ExecuteRegionFunctionOpImpl) {
                op = new ExecuteRegionFunctionOpImpl((ExecuteRegionFunctionOpImpl) op, (byte) 1, new HashSet<>());
                ((ExecuteRegionFunctionOpImpl) op).getMessage().setTransactionId(transactionId);
            } else if (op instanceof ExecuteFunctionOpImpl) {
                op = new ExecuteFunctionOpImpl((ExecuteFunctionOpImpl) op, (byte) 1);
                ((ExecuteFunctionOpImpl) op).getMessage().setTransactionId(transactionId);
            }
            return pool.execute(op);
        } finally {
            if (initialRetryCount == 0) {
                setAffinityRetryCount(0);
            }
        }
    }

    @Override
    public void setupServerAffinity(boolean allowFailover) {
        if (logger.isDebugEnabled()) {
            logger.debug("setting up server affinity");
        }
        serverAffinityFailover = allowFailover;
        serverAffinity.set(Boolean.TRUE);
    }

    @Override
    public void releaseServerAffinity() {
        if (logger.isDebugEnabled()) {
            logger.debug("reset server affinity");
        }
        serverAffinity.set(Boolean.FALSE);
        affinityServerLocation.set(null);
    }

    @Override
    public ServerLocation getServerAffinityLocation() {
        return affinityServerLocation.get();
    }

    int getAffinityRetryCount() {
        return affinityRetryCount.get();
    }

    void setAffinityRetryCount(int retryCount) {
        affinityRetryCount.set(retryCount);
    }

    @Override
    public void setServerAffinityLocation(ServerLocation serverLocation) {
        replacedert affinityServerLocation.get() == null;
        affinityServerLocation.set(serverLocation);
    }

    public ServerLocation getNextOpServerLocation() {
        Connection conn = connectionManager.borrowConnection(serverTimeout);
        try {
            return conn.getServer();
        } finally {
            connectionManager.returnConnection(conn);
        }
    }

    /*
   * (non-Javadoc)
   *
   * @see org.apache.geode.cache.client.internal.OpExecutor#executeOn(org.apache.geode.distributed.
   * internal.ServerLocation, org.apache.geode.cache.client.internal.Op)
   */
    @Override
    public Object executeOn(ServerLocation server, Op op) {
        return executeOn(server, op, true, false);
    }

    @Override
    public Object executeOn(ServerLocation p_server, Op op, boolean accessed, boolean onlyUseExistingCnx) {
        ServerLocation server = p_server;
        if (serverAffinity.get()) {
            ServerLocation affinityserver = affinityServerLocation.get();
            if (affinityserver != null) {
                server = affinityserver;
            } else {
                affinityServerLocation.set(server);
            }
            // redirect to executeWithServerAffinity so that we
            // can send a TXFailoverOp.
            return executeWithServerAffinity(server, op);
        }
        return executeOnServer(server, op, accessed, onlyUseExistingCnx);
    }

    protected Object executeOnServer(ServerLocation p_server, Op op, boolean accessed, boolean onlyUseExistingCnx) {
        boolean returnCnx = true;
        boolean pingOp = (op instanceof PingOp.PingOpImpl);
        Connection conn = null;
        if (pingOp) {
            // currently for pings we prefer to queue clientToServer cnx so that we will
            // not create a pooled cnx when all we have is queue cnxs.
            if (queueManager != null) {
                // see if our QueueManager has a connection to this server that we can send
                // the ping on.
                Endpoint ep = endpointManager.getEndpointMap().get(p_server);
                if (ep != null) {
                    QueueConnections qcs = queueManager.getAllConnectionsNoWait();
                    conn = qcs.getConnection(ep);
                    if (conn != null) {
                        // we found one to do the ping on
                        returnCnx = false;
                    }
                }
            }
        }
        if (conn == null) {
            conn = connectionManager.borrowConnection(p_server, onlyUseExistingCnx);
        }
        try {
            return executeWithPossibleReAuthentication(conn, op);
        } catch (Exception e) {
            handleException(e, conn, 0, true);
            // this shouldn't actually be reached, handle exception will throw something
            throw new ServerConnectivityException("Received error connecting to server", e);
        } finally {
            if (serverAffinity.get() && affinityServerLocation.get() == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("setting server affinity to {} server:{}", conn.getEndpoint().getMemberId(), conn.getServer());
                }
                affinityServerLocation.set(conn.getServer());
            }
            if (returnCnx) {
                connectionManager.returnConnection(conn, accessed);
            }
        }
    }

    /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.geode.cache.client.internal.ExecutablePool#executeOnPrimary(org.apache.geode.cache.
   * client.internal.Op)
   */
    @Override
    public Object executeOnPrimary(Op op) {
        if (queueManager == null) {
            throw new SubscriptionNotEnabledException();
        }
        HashSet<ServerLocation> attemptedPrimaries = new HashSet<>();
        while (true) {
            Connection primary = queueManager.getAllConnections().getPrimary();
            try {
                return executeWithPossibleReAuthentication(primary, op);
            } catch (Exception e) {
                boolean finalAttempt = !attemptedPrimaries.add(primary.getServer());
                handleException(e, primary, 0, finalAttempt);
                // we shouldn't reach this code, but just in case
                if (finalAttempt) {
                    throw new ServerConnectivityException("Tried the same primary server twice.", e);
                }
            }
        }
    }

    @Override
    public void executeOnAllQueueServers(Op op) {
        if (queueManager == null) {
            throw new SubscriptionNotEnabledException();
        }
        RuntimeException lastException = null;
        QueueConnections connections = queueManager.getAllConnectionsNoWait();
        Connection primary = connections.getPrimary();
        if (primary != null) {
            try {
                executeWithPossibleReAuthentication(primary, op);
            } catch (Exception e) {
                try {
                    handleException(e, primary, 0, false);
                } catch (RuntimeException e2) {
                    lastException = e2;
                }
            }
        }
        List<Connection> backups = connections.getBackups();
        for (Connection conn : backups) {
            try {
                executeWithPossibleReAuthentication(conn, op);
            } catch (Exception e) {
                try {
                    handleException(e, conn, 0, false);
                } catch (RuntimeException e2) {
                    lastException = e2;
                }
            }
        }
        if (lastException != null) {
            throw lastException;
        }
    }

    /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.geode.cache.client.internal.ExecutablePool#executeOnAllQueueServers(org.apache.geode
   * .cache.client.internal.Op)
   */
    @Override
    public Object executeOnQueuesAndReturnPrimaryResult(Op op) {
        if (queueManager == null) {
            throw new SubscriptionNotEnabledException();
        }
        QueueConnections connections = queueManager.getAllConnections();
        List backups = connections.getBackups();
        if (logger.isTraceEnabled(LogMarker.BRIDGE_SERVER_VERBOSE)) {
            logger.trace(LogMarker.BRIDGE_SERVER_VERBOSE, "sending {} to backups: {}", op, backups);
        }
        for (int i = backups.size() - 1; i >= 0; i--) {
            Connection conn = (Connection) backups.get(i);
            try {
                executeWithPossibleReAuthentication(conn, op);
            } catch (Exception e) {
                handleException(e, conn, 0, false);
            }
        }
        Connection primary = connections.getPrimary();
        HashSet<ServerLocation> attemptedPrimaries = new HashSet<>();
        while (true) {
            try {
                if (logger.isTraceEnabled(LogMarker.BRIDGE_SERVER_VERBOSE)) {
                    logger.trace(LogMarker.BRIDGE_SERVER_VERBOSE, "sending {} to primary: {}", op, primary);
                }
                return executeWithPossibleReAuthentication(primary, op);
            } catch (Exception e) {
                if (logger.isTraceEnabled(LogMarker.BRIDGE_SERVER_VERBOSE)) {
                    logger.trace(LogMarker.BRIDGE_SERVER_VERBOSE, "caught exception sending to primary {}", e.getMessage(), e);
                }
                boolean finalAttempt = !attemptedPrimaries.add(primary.getServer());
                handleException(e, primary, 0, finalAttempt);
                primary = queueManager.getAllConnections().getPrimary();
                // we shouldn't reach this code, but just in case
                if (finalAttempt) {
                    throw new ServerConnectivityException("Tried the same primary server twice.", e);
                }
            }
        }
    }

    /**
     * Used by GatewayBatchOp
     */
    @Override
    public Object executeOn(Connection conn, Op op, boolean timeoutFatal) {
        try {
            return executeWithPossibleReAuthentication(conn, op);
        } catch (Exception e) {
            handleException(op, e, conn, 0, true, timeoutFatal);
            // this shouldn't actually be reached, handle exception will throw something
            throw new ServerConnectivityException("Received error connecting to server", e);
        }
    }

    /**
     * This is used by unit tests
     */
    @Override
    public Object executeOn(Connection conn, Op op) {
        return executeOn(conn, op, false);
    }

    @Override
    public RegisterInterestTracker getRITracker() {
        return riTracker;
    }

    /**
     * This method will throw an exception if we need to stop the connection manager if there are
     * failures.
     */
    protected void handleException(Throwable e, Connection conn, int retryCount, boolean finalAttempt) {
        handleException(e, conn, retryCount, finalAttempt, false);
    }

    protected void handleException(Op op, Throwable e, Connection conn, int retryCount, boolean finalAttempt, boolean timeoutFatal) throws CacheRuntimeException {
        if (op instanceof AuthenticateUserOp.AuthenticateUserOpImpl) {
            if (e instanceof GemFireSecurityException) {
                throw (GemFireSecurityException) e;
            } else if (e instanceof ServerRefusedConnectionException) {
                throw (ServerRefusedConnectionException) e;
            }
        }
        handleException(e, conn, retryCount, finalAttempt, timeoutFatal);
    }

    protected void handleException(Throwable e, Connection conn, int retryCount, boolean finalAttempt, boolean timeoutFatal) throws CacheRuntimeException {
        GemFireException exToThrow = null;
        String replacedle;
        boolean invalidateServer = true;
        boolean warn = true;
        boolean forceThrow = false;
        Throwable cause = e;
        cancelCriterion.checkCancelInProgress(e);
        if (logger.isDebugEnabled() && !(e instanceof java.io.EOFException)) {
            if (e instanceof java.net.SocketTimeoutException) {
                logger.debug("OpExecutor.handleException on Connection to {} read timed out", conn.getServer());
            } else {
                logger.debug("OpExecutor.handleException on Connection to {}", conn.getServer(), e);
            }
        }
        // first take care of all exceptions that should not invalidate the
        // connection and do not need to be logged
        if (e instanceof MessageTooLargeException) {
            replacedle = null;
            exToThrow = new GemFireIOException("message is too large to transmit", e);
        } else if (e instanceof NotSerializableException) {
            // no message
            replacedle = null;
            exToThrow = new SerializationException("Pool message failure", e);
        } else if (e instanceof BatchException || e instanceof BatchException70) {
            // no message
            replacedle = null;
            exToThrow = new ServerOperationException(e);
        } else if (e instanceof RegionDestroyedException) {
            invalidateServer = false;
            replacedle = null;
            exToThrow = (RegionDestroyedException) e;
        } else if (e instanceof GemFireSecurityException) {
            replacedle = null;
            exToThrow = new ServerOperationException(e);
        } else if (e instanceof SerializationException) {
            // no message
            replacedle = null;
            exToThrow = new ServerOperationException(e);
        } else if (e instanceof CopyException) {
            // no message
            replacedle = null;
            exToThrow = new ServerOperationException(e);
        } else if (e instanceof ClreplacedNotFoundException) {
            // no message
            replacedle = null;
            exToThrow = new ServerOperationException(e);
        } else if (e instanceof TransactionException) {
            // no message
            replacedle = null;
            exToThrow = (TransactionException) e;
            invalidateServer = false;
        } else if (e instanceof SynchronizationCommitConflictException) {
            replacedle = null;
            exToThrow = (SynchronizationCommitConflictException) e;
            invalidateServer = false;
        } else if (e instanceof SocketException) {
            if ("Socket closed".equals(e.getMessage()) || "Connection reset".equals(e.getMessage()) || "Connection refused: connect".equals(e.getMessage()) || "Connection refused".equals(e.getMessage())) {
                replacedle = e.getMessage();
            } else {
                replacedle = "SocketException";
            }
        } else if (e instanceof SocketTimeoutException) {
            invalidateServer = timeoutFatal;
            replacedle = "socket timed out on client";
            cause = null;
        } else if (e instanceof ConnectionDestroyedException) {
            invalidateServer = false;
            replacedle = "connection was asynchronously destroyed";
            cause = null;
        } else if (e instanceof java.io.EOFException) {
            replacedle = "closed socket on server";
        } else if (e instanceof IOException) {
            replacedle = "IOException";
        } else if (e instanceof BufferUnderflowException) {
            replacedle = "buffer underflow reading from server";
        } else if (e instanceof CancelException) {
            replacedle = "Cancelled";
            warn = false;
        } else if (e instanceof InternalFunctionInvocationTargetException) {
            // In this case, function will be re executed
            replacedle = null;
            exToThrow = (InternalFunctionInvocationTargetException) e;
        } else if (e instanceof FunctionInvocationTargetException) {
            // in this case function will not be re executed
            replacedle = null;
            exToThrow = (GemFireException) e;
        } else if (e instanceof PutAllPartialResultException) {
            replacedle = null;
            exToThrow = (PutAllPartialResultException) e;
            invalidateServer = false;
        } else {
            Throwable t = e.getCause();
            if ((t instanceof IOException) || (t instanceof SerializationException) || (t instanceof CopyException) || (t instanceof GemFireSecurityException) || (t instanceof ServerOperationException) || (t instanceof TransactionException) || (t instanceof CancelException)) {
                handleException(t, conn, retryCount, finalAttempt, timeoutFatal);
                return;
            } else if (e instanceof ServerOperationException) {
                // no message
                replacedle = null;
                exToThrow = (ServerOperationException) e;
                // fix for bug #42225
                invalidateServer = false;
            } else if (e instanceof FunctionException) {
                if (t instanceof InternalFunctionInvocationTargetException) {
                    // Client server to re-execute for node failure
                    handleException(t, conn, retryCount, finalAttempt, timeoutFatal);
                    return;
                } else {
                    // no message
                    replacedle = null;
                    exToThrow = (FunctionException) e;
                }
            } else if (e instanceof ServerConnectivityException && e.getMessage().equals("Connection error while authenticating user")) {
                replacedle = null;
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                }
            } else {
                replacedle = e.toString();
                forceThrow = true;
            }
        }
        if (replacedle != null) {
            conn.destroy();
            if (invalidateServer) {
                endpointManager.serverCrashed(conn.getEndpoint());
            }
            boolean logEnabled = warn ? logger.isWarnEnabled() : logger.isDebugEnabled();
            boolean msgNeeded = logEnabled || finalAttempt;
            if (msgNeeded) {
                final StringBuffer sb = getExceptionMessage(replacedle, retryCount, finalAttempt, conn);
                final String msg = sb.toString();
                if (logEnabled) {
                    if (warn) {
                        logger.warn(msg);
                    } else {
                        logger.debug(msg, e);
                    }
                }
                if (forceThrow || finalAttempt) {
                    exToThrow = new ServerConnectivityException(msg, cause);
                }
            }
        }
        if (exToThrow != null) {
            throw exToThrow;
        }
    }

    private StringBuffer getExceptionMessage(String exceptionName, int retryCount, boolean finalAttempt, Connection connection) {
        StringBuffer message = new StringBuffer(200);
        message.append("Pool unexpected ").append(exceptionName);
        if (connection != null) {
            message.append(" connection=").append(connection);
        }
        if (retryCount > 0) {
            message.append(" attempt=").append(retryCount + 1);
        }
        message.append(')');
        if (finalAttempt) {
            message.append(". Server unreachable: could not connect after ").append(retryCount + 1).append(" attempts");
        }
        return message;
    }

    private void authenticateIfRequired(Connection conn, Op op) {
        if (!conn.getServer().getRequiresCredentials()) {
            return;
        }
        if (pool == null) {
            PoolImpl poolImpl = (PoolImpl) PoolManagerImpl.getPMI().find(endpointManager.getPoolName());
            if (poolImpl == null) {
                return;
            }
            pool = poolImpl;
        }
        if (pool.getMultiuserAuthentication()) {
            if (((AbstractOp) op).needsUserId()) {
                UserAttributes ua = UserAttributes.userAttributes.get();
                if (ua != null) {
                    if (!ua.getServerToId().containsKey(conn.getServer())) {
                        authenticateMultiuser(pool, conn, ua);
                    }
                }
            }
        } else if (((AbstractOp) op).needsUserId()) {
            // This should not be reached, but keeping this code here in case it is
            // reached.
            if (conn.getServer().getUserId() == -1) {
                Connection connImpl = conn.getWrappedConnection();
                conn.getServer().setUserId((Long) AuthenticateUserOp.executeOn(connImpl, pool));
                if (logger.isDebugEnabled()) {
                    logger.debug("OpExecutorImpl.execute() - single user mode - authenticated this user on {}", conn);
                }
            }
        }
    }

    private void authenticateMultiuser(PoolImpl pool, Connection conn, UserAttributes ua) {
        try {
            Long userId = (Long) AuthenticateUserOp.executeOn(conn.getServer(), pool, ua.getCredentials());
            if (userId != null) {
                ua.setServerToId(conn.getServer(), userId);
                if (logger.isDebugEnabled()) {
                    logger.debug("OpExecutorImpl.execute() - multiuser mode - authenticated this user on {}", conn);
                }
            }
        } catch (ServerConnectivityException sce) {
            Throwable cause = sce.getCause();
            if (cause instanceof IOException || cause instanceof BufferUnderflowException || cause instanceof CancelException || (sce.getMessage() != null && (sce.getMessage().contains("Could not create a new connection to server") || sce.getMessage().contains("socket timed out on client") || sce.getMessage().contains("connection was asynchronously destroyed")))) {
                throw new ServerConnectivityException("Connection error while authenticating user");
            } else {
                throw sce;
            }
        }
    }

    private Object executeWithPossibleReAuthentication(Connection conn, Op op) throws Exception {
        try {
            return conn.execute(op);
        } catch (ServerConnectivityException sce) {
            Throwable cause = sce.getCause();
            if ((cause instanceof AuthenticationRequiredException && "User authorization attributes not found.".equals(cause.getMessage())) || sce.getMessage().contains("Connection error while authenticating user")) {
                // (ashetkar) Need a cleaner way of doing above check.
                // 2nd exception-message above is from AbstractOp.sendMessage()
                PoolImpl pool = (PoolImpl) PoolManagerImpl.getPMI().find(endpointManager.getPoolName());
                if (!pool.getMultiuserAuthentication()) {
                    Connection connImpl = conn.getWrappedConnection();
                    conn.getServer().setUserId((Long) AuthenticateUserOp.executeOn(connImpl, this));
                    return conn.execute(op);
                } else {
                    UserAttributes ua = UserAttributes.userAttributes.get();
                    if (ua != null) {
                        authenticateMultiuser(pool, conn, ua);
                    }
                    return conn.execute(op);
                }
            } else {
                throw sce;
            }
        }
    }
}

17 View Complete Implementation : ConnectionManagerImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Manages client to server connections for the connection pool. This clreplaced contains all of the
 * pooling logic to checkout/checkin connections.
 *
 * @since GemFire 5.7
 */
public clreplaced ConnectionManagerImpl implements ConnectionManager {

    private static final Logger logger = LogService.getLogger();

    private static final int NOT_WAITING = -1;

    public static final String BORROW_CONN_ERROR_MSG = "Could not create a new connection to server ";

    public static final String UNEXPECTED_SOCKET_CLOSED_MSG = "Pool unexpected closed socket on server";

    public static final String SOCKET_TIME_OUT_MSG = "socket timed out on client";

    private final String poolName;

    private final PoolStats poolStats;

    // ms
    private final long prefillRetry;

    private final AvailableConnectionManager availableConnectionManager = new AvailableConnectionManager();

    protected final ConnectionMap allConnectionsMap = new ConnectionMap();

    private final EndpointManager endpointManager;

    // make this an int
    private final long idleTimeout;

    private final long idleTimeoutNanos;

    private final int lifetimeTimeout;

    private final long lifetimeTimeoutNanos;

    private final InternalLogWriter securityLogWriter;

    protected final CancelCriterion cancelCriterion;

    private final ConnectionAccounting connectionAccounting;

    private ScheduledExecutorService backgroundProcessor;

    private ScheduledExecutorService loadConditioningProcessor;

    private ConnectionFactory connectionFactory;

    private boolean haveIdleExpireConnectionsTask;

    private final AtomicBoolean havePrefillTask = new AtomicBoolean(false);

    private boolean keepAlive = false;

    protected final AtomicBoolean shuttingDown = new AtomicBoolean(false);

    private EndpointManager.EndpointListenerAdapter endpointListener;

    /**
     * Adds an arbitrary variance to a positive temporal interval. Where possible, 10% of the interval
     * is added or subtracted from the interval. Otherwise, 1 is added or subtracted from the
     * interval. For all positive intervals, the returned value will <bold>not</bold> equal the
     * supplied interval.
     *
     * @param interval Positive temporal interval.
     * @return Adjusted interval including the variance for positive intervals; the unmodified
     *         interval for non-positive intervals.
     */
    static int addVarianceToInterval(int interval) {
        if (1 <= interval) {
            final SplittableRandom random = new SplittableRandom();
            final int variance = (interval < 10) ? 1 : (1 + random.nextInt((interval / 10) - 1));
            final int sign = random.nextBoolean() ? 1 : -1;
            return interval + (sign * variance);
        }
        return interval;
    }

    /**
     * Create a connection manager
     *
     * @param poolName the name of the pool that owns us
     * @param factory the factory for new connections
     * @param maxConnections The maximum number of connections that can exist
     * @param minConnections The minimum number of connections that can exist
     * @param idleTimeout The amount of time to wait to expire idle connections. -1 means that idle
     *        connections are never expired.
     * @param lifetimeTimeout the lifetimeTimeout in ms.
     */
    public ConnectionManagerImpl(String poolName, ConnectionFactory factory, EndpointManager endpointManager, int maxConnections, int minConnections, long idleTimeout, int lifetimeTimeout, InternalLogWriter securityLogger, long pingInterval, CancelCriterion cancelCriterion, PoolStats poolStats) {
        this.poolName = poolName;
        this.poolStats = poolStats;
        if (maxConnections < minConnections && maxConnections != -1) {
            throw new IllegalArgumentException("Max connections " + maxConnections + " is less than minConnections " + minConnections);
        }
        if (maxConnections <= 0 && maxConnections != -1) {
            throw new IllegalArgumentException("Max connections " + maxConnections + " must be greater than 0");
        }
        if (minConnections < 0) {
            throw new IllegalArgumentException("Min connections " + minConnections + " must be greater than or equals to 0");
        }
        connectionFactory = factory;
        this.endpointManager = endpointManager;
        connectionAccounting = new ConnectionAccounting(minConnections, maxConnections == -1 ? Integer.MAX_VALUE : maxConnections);
        this.lifetimeTimeout = addVarianceToInterval(lifetimeTimeout);
        lifetimeTimeoutNanos = MILLISECONDS.toNanos(this.lifetimeTimeout);
        if (this.lifetimeTimeout != -1) {
            if (idleTimeout > this.lifetimeTimeout || idleTimeout == -1) {
                // lifetimeTimeout takes precedence over longer idle timeouts
                idleTimeout = this.lifetimeTimeout;
            }
        }
        this.idleTimeout = idleTimeout;
        idleTimeoutNanos = MILLISECONDS.toNanos(this.idleTimeout);
        securityLogWriter = securityLogger;
        prefillRetry = pingInterval;
        this.cancelCriterion = cancelCriterion;
        endpointListener = new EndpointManager.EndpointListenerAdapter() {

            @Override
            public void endpointCrashed(Endpoint endpoint) {
                invalidateServer(endpoint);
            }
        };
    }

    private void destroyAndMaybePrefill() {
        destroyAndMaybePrefill(1);
    }

    private void destroyAndMaybePrefill(int count) {
        if (connectionAccounting.destroyAndIsUnderMinimum(count)) {
            startBackgroundPrefill();
        }
    }

    private PooledConnection createPooledConnection() throws NoAvailableServersException, ServerOperationException {
        return createPooledConnection(Collections.emptySet());
    }

    private PooledConnection createPooledConnection(Set<ServerLocation> excludedServers) throws NoAvailableServersException, ServerOperationException {
        try {
            return addConnection(connectionFactory.createClientToServerConnection(excludedServers));
        } catch (GemFireSecurityException e) {
            throw new ServerOperationException(e);
        } catch (ServerRefusedConnectionException e) {
            throw new NoAvailableServersException(e);
        }
    }

    private PooledConnection createPooledConnection(ServerLocation serverLocation) throws ServerRefusedConnectionException, GemFireSecurityException {
        return addConnection(connectionFactory.createClientToServerConnection(serverLocation, false));
    }

    /**
     * Always creates a connection and may cause {@link ConnectionAccounting} to exceed maximum.
     */
    private PooledConnection forceCreateConnection(ServerLocation serverLocation) throws ServerRefusedConnectionException, ServerOperationException {
        connectionAccounting.create();
        try {
            return createPooledConnection(serverLocation);
        } catch (GemFireSecurityException e) {
            throw new ServerOperationException(e);
        }
    }

    /**
     * Always creates a connection and may cause {@link ConnectionAccounting} to exceed maximum.
     */
    private PooledConnection forceCreateConnection(Set<ServerLocation> excludedServers) throws NoAvailableServersException, ServerOperationException {
        connectionAccounting.create();
        return createPooledConnection(excludedServers);
    }

    private boolean checkShutdownInterruptedOrTimeout(final long timeout) throws PoolCancelledException {
        if (shuttingDown.get()) {
            throw new PoolCancelledException();
        }
        if (Thread.currentThread().isInterrupted()) {
            return true;
        }
        return timeout < System.nanoTime();
    }

    private long beginConnectionWaitStatIfNotStarted(final long waitStart) {
        if (NOT_WAITING == waitStart) {
            return getPoolStats().beginConnectionWait();
        }
        return waitStart;
    }

    private void endConnectionWaitStatIfStarted(final long waitStart) {
        if (NOT_WAITING != waitStart) {
            getPoolStats().endConnectionWait(waitStart);
        }
    }

    @Override
    public Connection borrowConnection(long acquireTimeout) throws AllConnectionsInUseException, NoAvailableServersException, ServerOperationException {
        long waitStart = NOT_WAITING;
        try {
            long timeout = System.nanoTime() + MILLISECONDS.toNanos(acquireTimeout);
            while (true) {
                PooledConnection connection = availableConnectionManager.useFirst();
                if (null != connection) {
                    return connection;
                }
                if (connectionAccounting.tryCreate()) {
                    try {
                        connection = createPooledConnection();
                        if (null != connection) {
                            return connection;
                        }
                        throw new NoAvailableServersException();
                    } finally {
                        if (connection == null) {
                            connectionAccounting.cancelTryCreate();
                            if (connectionAccounting.isUnderMinimum()) {
                                startBackgroundPrefill();
                            }
                        }
                    }
                }
                if (checkShutdownInterruptedOrTimeout(timeout)) {
                    break;
                }
                waitStart = beginConnectionWaitStatIfNotStarted(waitStart);
                Thread.yield();
            }
        } finally {
            endConnectionWaitStatIfStarted(waitStart);
        }
        cancelCriterion.checkCancelInProgress(null);
        throw new AllConnectionsInUseException();
    }

    /**
     * Borrow a connection to a specific server. This task currently allows us to break the connection
     * limit, because it is used by tasks from the background thread that shouldn't be constrained by
     * the limit. They will only violate the limit by 1 connection, and that connection will be
     * destroyed when returned to the pool.
     */
    @Override
    public PooledConnection borrowConnection(ServerLocation server, boolean onlyUseExistingCnx) throws AllConnectionsInUseException, NoAvailableServersException {
        PooledConnection connection = availableConnectionManager.useFirst((c) -> c.getServer().equals(server));
        if (null != connection) {
            return connection;
        }
        if (onlyUseExistingCnx) {
            throw new AllConnectionsInUseException();
        }
        connection = forceCreateConnection(server);
        if (null != connection) {
            return connection;
        }
        throw new ServerConnectivityException(BORROW_CONN_ERROR_MSG + server);
    }

    @Override
    public Connection exchangeConnection(final Connection oldConnection, final Set<ServerLocation> excludedServers) throws AllConnectionsInUseException {
        try {
            PooledConnection connection = availableConnectionManager.useFirst((c) -> !excludedServers.contains(c.getServer()));
            if (null != connection) {
                return connection;
            }
            connection = forceCreateConnection(excludedServers);
            if (null != connection) {
                return connection;
            }
            throw new NoAvailableServersException();
        } finally {
            returnConnection(oldConnection, true, true);
        }
    }

    protected String getPoolName() {
        return poolName;
    }

    private PooledConnection addConnection(Connection conn) {
        if (conn == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to create a connection in the allowed time");
            }
            return null;
        }
        PooledConnection pooledConn = new PooledConnection(this, conn);
        allConnectionsMap.addConnection(pooledConn);
        if (logger.isDebugEnabled()) {
            logger.debug("Created a new connection. {} Connection count is now {}", pooledConn, connectionAccounting.getCount());
        }
        return pooledConn;
    }

    private void destroyConnection(PooledConnection connection) {
        if (allConnectionsMap.removeConnection(connection)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Invalidating connection {} connection count is now {}", connection, connectionAccounting.getCount());
            }
            destroyAndMaybePrefill();
        }
        connection.internalDestroy();
    }

    private void invalidateServer(Endpoint endpoint) {
        Set<PooledConnection> badConnections = allConnectionsMap.removeEndpoint(endpoint);
        if (badConnections == null) {
            return;
        }
        if (shuttingDown.get()) {
            return;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Invalidating {} connections to server {}", badConnections.size(), endpoint);
        }
        for (PooledConnection conn : badConnections) {
            if (conn.internalDestroy()) {
                destroyAndMaybePrefill();
                availableConnectionManager.remove(conn);
            }
        }
    }

    @Override
    public void returnConnection(Connection connection) {
        returnConnection(connection, true);
    }

    @Override
    public void returnConnection(Connection connection, boolean accessed) {
        returnConnection(connection, accessed, false);
    }

    private void returnConnection(Connection connection, boolean accessed, boolean addLast) {
        replacedert connection instanceof PooledConnection;
        PooledConnection pooledConn = (PooledConnection) connection;
        if (pooledConn.isDestroyed()) {
            return;
        }
        if (pooledConn.shouldDestroy()) {
            destroyConnection(pooledConn);
        } else if (!destroyIfOverLimit(pooledConn)) {
            if (addLast) {
                availableConnectionManager.addLast(pooledConn, accessed);
            } else {
                availableConnectionManager.addFirst(pooledConn, accessed);
            }
        }
    }

    /**
     * Destroys connection if and only if {@link ConnectionAccounting} exceeds maximum.
     *
     * @return true if connection is destroyed, otherwise false.
     */
    private boolean destroyIfOverLimit(PooledConnection connection) {
        if (connectionAccounting.tryDestroy()) {
            if (allConnectionsMap.removeConnection(connection)) {
                try {
                    PoolImpl localpool = (PoolImpl) PoolManagerImpl.getPMI().find(poolName);
                    boolean durable = false;
                    if (localpool != null) {
                        durable = localpool.isDurableClient();
                    }
                    connection.internalClose(durable || keepAlive);
                } catch (Exception e) {
                    logger.warn(String.format("Error closing connection %s", connection), e);
                }
            } else {
                // Not a pooled connection so undo the decrement.
                connectionAccounting.cancelTryDestroy();
            }
            return true;
        }
        return false;
    }

    @Override
    public void start(ScheduledExecutorService backgroundProcessor) {
        this.backgroundProcessor = backgroundProcessor;
        String name = "poolLoadConditioningMonitor-" + getPoolName();
        loadConditioningProcessor = LoggingExecutors.newScheduledThreadPool(name, 1, false);
        endpointManager.addListener(endpointListener);
        startBackgroundPrefill();
    }

    @Override
    public void close(boolean keepAlive) {
        if (logger.isDebugEnabled()) {
            logger.debug("Shutting down connection manager with keepAlive {}", keepAlive);
        }
        this.keepAlive = keepAlive;
        endpointManager.removeListener(endpointListener);
        if (!shuttingDown.compareAndSet(false, true)) {
            return;
        }
        try {
            if (loadConditioningProcessor != null) {
                loadConditioningProcessor.shutdown();
                if (!loadConditioningProcessor.awaitTermination(PoolImpl.SHUTDOWN_TIMEOUT, MILLISECONDS)) {
                    logger.warn("Timeout waiting for load conditioning tasks to complete");
                }
            }
        } catch (RuntimeException e) {
            logger.error("Error stopping loadConditioningProcessor", e);
        } catch (InterruptedException e) {
            logger.error("Interrupted stopping loadConditioningProcessor", e);
        }
        allConnectionsMap.close(keepAlive);
    }

    @Override
    public void emergencyClose() {
        shuttingDown.set(true);
        if (loadConditioningProcessor != null) {
            loadConditioningProcessor.shutdown();
        }
        allConnectionsMap.emergencyClose();
    }

    private void startBackgroundExpiration() {
        if (idleTimeout >= 0) {
            synchronized (allConnectionsMap) {
                if (!haveIdleExpireConnectionsTask) {
                    haveIdleExpireConnectionsTask = true;
                    try {
                        backgroundProcessor.schedule(new IdleExpireConnectionsTask(), idleTimeout, MILLISECONDS);
                    } catch (RejectedExecutionException e) {
                    // ignore, the timer has been cancelled, which means we're shutting
                    // down.
                    }
                }
            }
        }
    }

    protected void startBackgroundPrefill() {
        if (havePrefillTask.compareAndSet(false, true)) {
            try {
                backgroundProcessor.execute(new PrefillConnectionsTask());
            } catch (RejectedExecutionException e) {
            // ignore, the timer has been cancelled, which means we're shutting
            // down.
            }
        }
    }

    private void prefill() {
        try {
            while (connectionAccounting.isUnderMinimum()) {
                if (cancelCriterion.isCancelInProgress()) {
                    return;
                }
                boolean createdConnection = prefillConnection();
                if (!createdConnection) {
                    return;
                }
            }
        } catch (Throwable t) {
            cancelCriterion.checkCancelInProgress(t);
            if (t.getCause() != null) {
                t = t.getCause();
            }
            logInfo("Error prefilling connections", t);
        }
    }

    @Override
    public int getConnectionCount() {
        return connectionAccounting.getCount();
    }

    protected PoolStats getPoolStats() {
        return poolStats;
    }

    private boolean prefillConnection() {
        if (shuttingDown.get()) {
            return false;
        }
        if (connectionAccounting.tryPrefill()) {
            PooledConnection connection = null;
            try {
                connection = createPooledConnection();
                if (connection == null) {
                    return false;
                }
                getPoolStats().incPrefillConnect();
                availableConnectionManager.addLast(connection, false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Prefilled connection {} connection count is now {}", connection, connectionAccounting.getCount());
                }
                return true;
            } catch (ServerConnectivityException ex) {
                logger.info(String.format("Unable to prefill pool to minimum because: %s", ex.getMessage()));
                return false;
            } finally {
                if (connection == null) {
                    connectionAccounting.cancelTryPrefill();
                    if (logger.isDebugEnabled()) {
                        logger.debug("Unable to prefill pool to minimum, connection count is now {}", this::getConnectionCount);
                    }
                }
            }
        }
        return false;
    }

    protected clreplaced LifetimeExpireConnectionsTask implements Runnable {

        @Override
        public void run() {
            try {
                allConnectionsMap.checkLifetimes();
            } catch (CancelException ignore) {
            } catch (VirtualMachineError e) {
                SystemFailure.initiateFailure(e);
                throw e;
            } catch (Throwable t) {
                SystemFailure.checkFailure();
                logger.warn(String.format("LoadConditioningTask <%s> encountered exception", this), t);
            // Don't rethrow, it will just get eaten and kill the timer
            }
        }
    }

    protected clreplaced IdleExpireConnectionsTask implements Runnable {

        @Override
        public void run() {
            try {
                getPoolStats().incIdleCheck();
                allConnectionsMap.expireIdleConnections();
            } catch (CancelException ignore) {
            } catch (VirtualMachineError e) {
                SystemFailure.initiateFailure(e);
                // NOTREACHED
                // for safety
                throw e;
            } catch (Throwable t) {
                SystemFailure.checkFailure();
                logger.warn(String.format("IdleExpireConnectionsTask <%s> encountered exception", this), t);
            // Don't rethrow, it will just get eaten and kill the timer
            }
        }
    }

    protected clreplaced PrefillConnectionsTask extends PoolTask {

        @Override
        public void run2() {
            if (logger.isTraceEnabled()) {
                logger.trace("Prefill Connections task running");
            }
            prefill();
            if (connectionAccounting.isUnderMinimum() && !cancelCriterion.isCancelInProgress()) {
                try {
                    backgroundProcessor.schedule(new PrefillConnectionsTask(), prefillRetry, MILLISECONDS);
                } catch (RejectedExecutionException ignored) {
                // ignore, the timer has been cancelled, which means we're shutting down.
                }
            } else {
                havePrefillTask.set(false);
            }
        }
    }

    /**
     * Offer the replacement "con" to any cnx currently connected to "currentServer".
     */
    private void offerReplacementConnection(Connection con, ServerLocation currentServer) {
        boolean retry;
        do {
            retry = false;
            PooledConnection target = allConnectionsMap.findReplacementTarget(currentServer);
            if (target != null) {
                final Endpoint targetEP = target.getEndpoint();
                boolean interrupted = false;
                try {
                    if (target.switchConnection(con)) {
                        getPoolStats().incLoadConditioningDisconnect();
                        allConnectionsMap.addReplacedCnx(target, targetEP);
                        return;
                    } else {
                        retry = true;
                    }
                } catch (InterruptedException e) {
                    // thrown by switchConnection
                    interrupted = true;
                    cancelCriterion.checkCancelInProgress(e);
                    retry = false;
                } finally {
                    if (interrupted) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        } while (retry);
        getPoolStats().incLoadConditioningReplaceTimeouts();
        con.destroy();
    }

    /**
     * An existing connections lifetime has expired. We only want to create one replacement connection
     * at a time so this should block until this connection replaces an existing one. Note that if
     * a connection is created here it must not count against the pool max and its idle time and
     * lifetime must not begin until it actually replaces the existing one.
     *
     * @param currentServer the server the candidate connection is connected to
     * @return true if caller should recheck for expired lifetimes; false if a background check was
     *         scheduled or no expirations are possible.
     */
    private boolean createLifetimeReplacementConnection(ServerLocation currentServer) {
        HashSet<ServerLocation> excludedServers = new HashSet<>();
        while (true) {
            ServerLocation sl = connectionFactory.findBestServer(currentServer, excludedServers);
            if (sl == null || sl.equals(currentServer)) {
                // we didn't find a server to create a replacement cnx on so
                // extends the currentServers life
                allConnectionsMap.extendLifeOfCnxToServer(currentServer);
                break;
            }
            if (!allConnectionsMap.hasExpiredCnxToServer(currentServer)) {
                break;
            }
            Connection con;
            try {
                con = connectionFactory.createClientToServerConnection(sl, false);
                if (con != null) {
                    getPoolStats().incLoadConditioningConnect();
                    if (allConnectionsMap.hasExpiredCnxToServer(currentServer)) {
                        offerReplacementConnection(con, currentServer);
                    } else {
                        getPoolStats().incLoadConditioningReplaceTimeouts();
                        con.destroy();
                    }
                    break;
                }
            } catch (GemFireSecurityException e) {
                securityLogWriter.warning(String.format("Security exception connecting to server '%s': %s", sl, e));
            } catch (ServerRefusedConnectionException srce) {
                logger.warn("Server '{}' refused new connection: {}", sl, srce.getMessage());
            }
            excludedServers.add(sl);
        }
        return allConnectionsMap.checkForReschedule(true);
    }

    protected clreplaced ConnectionMap {

        private final Map<Endpoint, Set<PooledConnection>> map = new HashMap<>();

        private List<PooledConnection> allConnections = new LinkedList<>();

        private boolean haveLifetimeExpireConnectionsTask;

        volatile boolean closing;

        synchronized boolean isIdleExpirePossible() {
            return allConnections.size() > connectionAccounting.getMinimum();
        }

        @Override
        public synchronized String toString() {
            final long now = System.nanoTime();
            StringBuilder sb = new StringBuilder();
            sb.append("<");
            for (Iterator it = allConnections.iterator(); it.hasNext(); ) {
                PooledConnection pc = (PooledConnection) it.next();
                sb.append(pc.getServer());
                if (pc.shouldDestroy()) {
                    sb.append("-DESTROYED");
                } else if (pc.hasIdleExpired(now, idleTimeoutNanos)) {
                    sb.append("-IDLE");
                } else if (pc.remainingLife(now, lifetimeTimeoutNanos) <= 0) {
                    sb.append("-EOL");
                }
                if (it.hasNext()) {
                    sb.append(",");
                }
            }
            sb.append(">");
            return sb.toString();
        }

        synchronized void addConnection(PooledConnection connection) {
            if (closing) {
                throw new CacheClosedException("This pool is closing");
            }
            getPoolStats().incPoolConnections(1);
            // we want the smallest birthDate (e.g. oldest cnx) at the front of the list
            allConnections.add(connection);
            addToEndpointMap(connection);
            if (isIdleExpirePossible()) {
                startBackgroundExpiration();
            }
            if (lifetimeTimeout != -1 && !haveLifetimeExpireConnectionsTask) {
                if (checkForReschedule(true)) {
                    // something has already expired so start processing with no delay
                    startBackgroundLifetimeExpiration(0);
                }
            }
        }

        synchronized void addReplacedCnx(PooledConnection con, Endpoint oldEndpoint) {
            if (closing) {
                throw new CacheClosedException("This pool is closing");
            }
            if (allConnections.remove(con)) {
                // otherwise someone else has removed it and closed it
                removeFromEndpointMap(oldEndpoint, con);
                addToEndpointMap(con);
                allConnections.add(con);
                if (isIdleExpirePossible()) {
                    startBackgroundExpiration();
                }
            }
        }

        synchronized Set<PooledConnection> removeEndpoint(Endpoint endpoint) {
            final Set<PooledConnection> endpointConnections = map.remove(endpoint);
            if (endpointConnections != null) {
                int count = 0;
                for (Iterator<PooledConnection> it = allConnections.iterator(); it.hasNext(); ) {
                    if (endpointConnections.contains(it.next())) {
                        count++;
                        it.remove();
                    }
                }
                if (count != 0) {
                    getPoolStats().incPoolConnections(-count);
                }
            }
            return endpointConnections;
        }

        synchronized boolean removeConnection(PooledConnection connection) {
            boolean result = allConnections.remove(connection);
            if (result) {
                getPoolStats().incPoolConnections(-1);
            }
            removeFromEndpointMap(connection);
            return result;
        }

        private synchronized void addToEndpointMap(PooledConnection connection) {
            Set<PooledConnection> endpointConnections = map.computeIfAbsent(connection.getEndpoint(), k -> new HashSet<>());
            endpointConnections.add(connection);
        }

        private void removeFromEndpointMap(PooledConnection connection) {
            removeFromEndpointMap(connection.getEndpoint(), connection);
        }

        private synchronized void removeFromEndpointMap(Endpoint endpoint, PooledConnection connection) {
            Set<PooledConnection> endpointConnections = map.get(endpoint);
            if (endpointConnections != null) {
                endpointConnections.remove(connection);
                if (endpointConnections.size() == 0) {
                    map.remove(endpoint);
                }
            }
        }

        public void close(boolean keepAlive) {
            List<PooledConnection> connections;
            int count = 0;
            synchronized (this) {
                if (closing) {
                    return;
                }
                closing = true;
                map.clear();
                connections = allConnections;
                allConnections = new ClosedPoolConnectionList();
            }
            for (PooledConnection pc : connections) {
                count++;
                if (!pc.isDestroyed()) {
                    try {
                        pc.internalClose(keepAlive);
                    } catch (SocketException se) {
                        logger.info("Error closing connection to server " + pc.getServer(), se);
                    } catch (Exception e) {
                        logger.warn("Error closing connection to server " + pc.getServer(), e);
                    }
                }
            }
            if (count != 0) {
                getPoolStats().incPoolConnections(-count);
            }
        }

        public synchronized void emergencyClose() {
            closing = true;
            map.clear();
            while (!allConnections.isEmpty()) {
                PooledConnection pc = allConnections.remove(0);
                pc.emergencyClose();
            }
        }

        /**
         * Returns a pooled connection that can have its underlying cnx to currentServer replaced by a
         * new connection.
         *
         * @return null if a target could not be found
         */
        synchronized PooledConnection findReplacementTarget(ServerLocation currentServer) {
            final long now = System.nanoTime();
            for (PooledConnection pc : allConnections) {
                if (currentServer.equals(pc.getServer())) {
                    if (!pc.shouldDestroy() && pc.remainingLife(now, lifetimeTimeoutNanos) <= 0) {
                        removeFromEndpointMap(pc);
                        return pc;
                    }
                }
            }
            return null;
        }

        /**
         * Return true if we have a connection to the currentServer whose lifetime has expired.
         * Otherwise return false;
         */
        synchronized boolean hasExpiredCnxToServer(ServerLocation currentServer) {
            if (!allConnections.isEmpty()) {
                final long now = System.nanoTime();
                for (PooledConnection pc : allConnections) {
                    if (pc.shouldDestroy()) {
                    // this con has already been destroyed so ignore it
                    } else if (currentServer.equals(pc.getServer())) {
                        {
                            long life = pc.remainingLife(now, lifetimeTimeoutNanos);
                            if (life <= 0) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

        /**
         * Returns true if caller should recheck for expired lifetimes Returns false if a background
         * check was scheduled or no expirations are possible.
         */
        synchronized boolean checkForReschedule(boolean rescheduleOk) {
            if (!allConnections.isEmpty()) {
                final long now = System.nanoTime();
                for (PooledConnection pc : allConnections) {
                    if (pc.hasIdleExpired(now, idleTimeoutNanos)) {
                        // this con has already idle expired so ignore it
                        continue;
                    } else if (pc.shouldDestroy()) {
                        // this con has already been destroyed so ignore it
                        continue;
                    } else {
                        long life = pc.remainingLife(now, lifetimeTimeoutNanos);
                        if (life > 0) {
                            if (rescheduleOk) {
                                startBackgroundLifetimeExpiration(life);
                                return false;
                            } else {
                                return false;
                            }
                        } else {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        /**
         * Extend the life of the first expired connection to sl.
         */
        synchronized void extendLifeOfCnxToServer(ServerLocation sl) {
            if (!allConnections.isEmpty()) {
                final long now = System.nanoTime();
                for (Iterator<PooledConnection> it = allConnections.iterator(); it.hasNext(); ) {
                    PooledConnection pc = it.next();
                    if (pc.remainingLife(now, lifetimeTimeoutNanos) > 0) {
                        // no more connections whose lifetime could have expired
                        break;
                    // note don't ignore idle connections because they are still connected
                    // } else if (pc.remainingIdle(now, idleTimeoutNanos) <= 0) {
                    // // this con has already idle expired so ignore it
                    } else if (pc.shouldDestroy()) {
                    // this con has already been destroyed so ignore it
                    } else if (sl.equals(pc.getEndpoint().getLocation())) {
                        // we found a connection to whose lifetime we can extend
                        it.remove();
                        pc.setBirthDate(now);
                        getPoolStats().incLoadConditioningExtensions();
                        allConnections.add(pc);
                        // break so we only do this to the oldest connection
                        break;
                    }
                }
            }
        }

        synchronized void startBackgroundLifetimeExpiration(long delay) {
            if (!haveLifetimeExpireConnectionsTask) {
                haveLifetimeExpireConnectionsTask = true;
                try {
                    LifetimeExpireConnectionsTask task = new LifetimeExpireConnectionsTask();
                    loadConditioningProcessor.schedule(task, delay, TimeUnit.NANOSECONDS);
                } catch (RejectedExecutionException e) {
                // ignore, the timer has been cancelled, which means we're shutting down.
                }
            }
        }

        void expireIdleConnections() {
            int expireCount = 0;
            List<PooledConnection> toClose;
            synchronized (this) {
                haveIdleExpireConnectionsTask = false;
                if (shuttingDown.get()) {
                    return;
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Looking for connections to expire");
                }
                // find connections which have idle expired
                if (!connectionAccounting.isOverMinimum()) {
                    return;
                }
                long minRemainingIdle = Long.MAX_VALUE;
                int conCount = connectionAccounting.getCount();
                toClose = new ArrayList<>(conCount - connectionAccounting.getMinimum());
                for (Iterator<PooledConnection> it = allConnections.iterator(); it.hasNext() && conCount > connectionAccounting.getMinimum(); ) {
                    PooledConnection pc = it.next();
                    if (pc.shouldDestroy()) {
                        // ignore these connections
                        conCount--;
                    } else {
                        long remainingIdle = pc.doIdleTimeout(System.nanoTime(), idleTimeoutNanos);
                        if (remainingIdle >= 0) {
                            if (remainingIdle == 0) {
                                // someone else already destroyed pc so ignore it
                                conCount--;
                            } else if (remainingIdle < minRemainingIdle) {
                                minRemainingIdle = remainingIdle;
                            }
                        } else /* (remainingIdle < 0) */
                        {
                            // this means that we idleExpired the connection
                            expireCount++;
                            conCount--;
                            removeFromEndpointMap(pc);
                            toClose.add(pc);
                            it.remove();
                        }
                    }
                }
                if (conCount > connectionAccounting.getMinimum() && minRemainingIdle < Long.MAX_VALUE) {
                    try {
                        backgroundProcessor.schedule(new IdleExpireConnectionsTask(), minRemainingIdle, TimeUnit.NANOSECONDS);
                    } catch (RejectedExecutionException e) {
                    // ignore, the timer has been cancelled, which means we're shutting down.
                    }
                    haveIdleExpireConnectionsTask = true;
                }
            }
            if (expireCount > 0) {
                getPoolStats().incIdleExpire(expireCount);
                getPoolStats().incPoolConnections(-expireCount);
                destroyAndMaybePrefill(expireCount);
            }
            // now destroy all of the connections, outside the sync
            final boolean isDebugEnabled = logger.isDebugEnabled();
            for (PooledConnection connection : toClose) {
                if (isDebugEnabled) {
                    logger.debug("Idle connection detected. Expiring connection {}", connection);
                }
                try {
                    connection.internalClose(false);
                } catch (Exception e) {
                    logger.warn("Error expiring connection {}", connection);
                }
            }
        }

        void checkLifetimes() {
            boolean done;
            synchronized (this) {
                haveLifetimeExpireConnectionsTask = false;
                if (shuttingDown.get()) {
                    return;
                }
            }
            do {
                getPoolStats().incLoadConditioningCheck();
                long firstLife = -1;
                ServerLocation candidate = null;
                boolean idlePossible;
                synchronized (this) {
                    if (shuttingDown.get()) {
                        return;
                    }
                    // find a connection whose lifetime has expired
                    // and who is not already being replaced
                    long now = System.nanoTime();
                    long life = 0;
                    idlePossible = isIdleExpirePossible();
                    for (Iterator<PooledConnection> it = allConnections.iterator(); it.hasNext() && life <= 0 && (candidate == null); ) {
                        PooledConnection pc = it.next();
                        // skip over idle expired and destroyed
                        life = pc.remainingLife(now, lifetimeTimeoutNanos);
                        if (life <= 0) {
                            boolean idleTimedOut = idlePossible && pc.hasIdleExpired(now, idleTimeoutNanos);
                            boolean destroyed = pc.shouldDestroy();
                            if (!idleTimedOut && !destroyed) {
                                candidate = pc.getServer();
                            }
                        } else {
                            firstLife = life;
                        }
                    }
                }
                if (candidate != null) {
                    done = !createLifetimeReplacementConnection(candidate);
                } else {
                    if (firstLife >= 0) {
                        // reschedule
                        startBackgroundLifetimeExpiration(firstLife);
                    }
                    done = true;
                }
            } while (!done);
            // If a lifetimeExpire task is not scheduled at this point then
            // schedule one that will do a check in our configured lifetimeExpire.
            // this should not be needed but seems to currently help.
            startBackgroundLifetimeExpiration(lifetimeTimeoutNanos);
        }
    }

    private void logInfo(String message, Throwable t) {
        if (t instanceof GemFireSecurityException) {
            securityLogWriter.info(String.format("%s : %s", message, t), t);
        } else {
            logger.info(String.format("%s : %s", message, t), t);
        }
    }

    private static clreplaced ClosedPoolConnectionList extends ArrayList<PooledConnection> {

        @Override
        public PooledConnection set(int index, PooledConnection element) {
            throw new CacheClosedException("This pool has been closed");
        }

        @Override
        public boolean add(PooledConnection element) {
            throw new CacheClosedException("This pool has been closed");
        }

        @Override
        public void add(int index, PooledConnection element) {
            throw new CacheClosedException("This pool has been closed");
        }

        @Override
        public PooledConnection remove(int index) {
            throw new CacheClosedException("This pool has been closed");
        }

        @Override
        public boolean addAll(Collection c) {
            throw new CacheClosedException("This pool has been closed");
        }

        @Override
        public boolean addAll(int index, Collection c) {
            throw new CacheClosedException("This pool has been closed");
        }
    }
}

17 View Complete Implementation : HostStatSampler.java
Copyright Apache License 2.0
Author : apache
/**
 * HostStatSampler implements a thread which will monitor, sample, and archive statistics. It only
 * has the common functionality that any sampler needs.
 */
public abstract clreplaced HostStatSampler implements Runnable, StatisticsSampler, StatArchiveHandlerConfig {

    private static final Logger logger = LogService.getLogger();

    public static final String TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY = GeodeGlossary.GEMFIRE_PREFIX + "stats.test.fileSizeLimitInKB";

    public static final String OS_STATS_DISABLED_PROPERTY = "osStatsDisabled";

    protected static final String INITIALIZATION_TIMEOUT_PROPERTY = GeodeGlossary.GEMFIRE_PREFIX + "statSamplerInitializationTimeout";

    protected static final int INITIALIZATION_TIMEOUT_DEFAULT = 30000;

    protected static final long INITIALIZATION_TIMEOUT_MILLIS = Long.getLong(INITIALIZATION_TIMEOUT_PROPERTY, INITIALIZATION_TIMEOUT_DEFAULT);

    /**
     * Used to check if the sampler thread wake-up is delayed, and log a warning if it is delayed by
     * longer than the amount of milliseconds specified by this property. The value of 0 disables the
     * check.
     */
    private static final long STAT_SAMPLER_DELAY_THRESHOLD = Long.getLong(GeodeGlossary.GEMFIRE_PREFIX + "statSamplerDelayThreshold", 3000);

    private static final long STAT_SAMPLER_DELAY_THRESHOLD_NANOS = NanoTimer.millisToNanos(STAT_SAMPLER_DELAY_THRESHOLD);

    private static final int MIN_MS_SLEEP = 1;

    private static final int WAIT_FOR_SLEEP_INTERVAL = 10;

    private Thread statThread = null;

    private volatile boolean stopRequested = false;

    private final boolean osStatsDisabled = Boolean.getBoolean(OS_STATS_DISABLED_PROPERTY);

    private final boolean fileSizeLimitInKB;

    private final StatSamplerStats samplerStats;

    private VMStatsContract vmStats;

    private SampleCollector sampleCollector;

    /**
     * Used to signal thread that are waiting for the stat sampler to be initialized.
     */
    private final StoppableCountDownLatch statSamplerInitializedLatch;

    private final CancelCriterion stopper;

    private final CallbackSampler callbackSampler;

    private final NanoTimer timer;

    private final LogFile logFile;

    protected HostStatSampler(CancelCriterion stopper, StatSamplerStats samplerStats) {
        this(stopper, samplerStats, new NanoTimer());
    }

    protected HostStatSampler(CancelCriterion stopper, StatSamplerStats samplerStats, NanoTimer timer) {
        this(stopper, samplerStats, timer, null);
    }

    protected HostStatSampler(CancelCriterion stopper, StatSamplerStats samplerStats, LogFile logFile) {
        this(stopper, samplerStats, new NanoTimer(), logFile);
    }

    HostStatSampler(CancelCriterion stopper, StatSamplerStats samplerStats, NanoTimer timer, LogFile logFile) {
        this.stopper = stopper;
        this.statSamplerInitializedLatch = new StoppableCountDownLatch(this.stopper, 1);
        this.samplerStats = samplerStats;
        this.fileSizeLimitInKB = Boolean.getBoolean(TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY);
        this.callbackSampler = new CallbackSampler(stopper, samplerStats);
        this.timer = timer;
        this.logFile = logFile;
    }

    public StatSamplerStats getStatSamplerStats() {
        return this.samplerStats;
    }

    /**
     * Returns the number of times a statistics resource has been add or deleted.
     */
    @Override
    public int getStatisticsModCount() {
        return getStatisticsManager().getStatListModCount();
    }

    /**
     * Returns an array of all the current statistic resource instances.
     */
    @Override
    public Statistics[] getStatistics() {
        return getStatisticsManager().getStatistics();
    }

    /**
     * Returns the time this sampler's system was started.
     */
    @Override
    public long getSystemStartTime() {
        return getStatisticsManager().getStartTime();
    }

    /**
     * Returns the path to this sampler's system directory; if it has one.
     */
    @Override
    public String getSystemDirectoryPath() {
        try {
            return SocketCreator.getHostName(LocalHostUtil.getLocalHost());
        } catch (UnknownHostException ignore) {
            return "";
        }
    }

    @Override
    public Optional<LogFile> getLogFile() {
        return Optional.ofNullable(logFile);
    }

    @Override
    public boolean waitForSample(long timeout) throws InterruptedException {
        final long endTime = System.currentTimeMillis() + timeout;
        final int startSampleCount = this.samplerStats.getSampleCount();
        while (System.currentTimeMillis() < endTime && this.samplerStats.getSampleCount() <= startSampleCount) {
            Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
        }
        return this.samplerStats.getSampleCount() > startSampleCount;
    }

    @Override
    public SampleCollector waitForSampleCollector(long timeout) throws InterruptedException {
        final long endTime = System.currentTimeMillis() + timeout;
        while (System.currentTimeMillis() < endTime && this.sampleCollector == null || !this.sampleCollector.isInitialized()) {
            Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
        }
        return this.sampleCollector;
    }

    /**
     * This service's main loop
     */
    @Override
    public void run() {
        final boolean isDebugEnabled_STATISTICS = logger.isTraceEnabled(LogMarker.STATISTICS_VERBOSE);
        if (isDebugEnabled_STATISTICS) {
            logger.trace(LogMarker.STATISTICS_VERBOSE, "HostStatSampler started");
        }
        boolean latchCountedDown = false;
        try {
            initSpecialStats();
            this.sampleCollector = new SampleCollector(this);
            this.sampleCollector.initialize(this, timer.getTime(), new MainWithChildrenRollingFileHandler());
            this.statSamplerInitializedLatch.countDown();
            latchCountedDown = true;
            timer.reset();
            // subtract getNanoRate from lastTS to force a quick initial sample
            long nanosLastTimeStamp = timer.getLastResetTime() - getNanoRate();
            while (!stopRequested()) {
                SystemFailure.checkFailure();
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
                final long nanosBeforeSleep = timer.getLastResetTime();
                final long nanosToDelay = nanosLastTimeStamp + getNanoRate();
                delay(nanosToDelay);
                nanosLastTimeStamp = timer.getLastResetTime();
                if (!stopRequested() && isSamplingEnabled()) {
                    final long nanosTimeStamp = timer.getLastResetTime();
                    final long nanosElapsedSleeping = nanosTimeStamp - nanosBeforeSleep;
                    checkElapsedSleepTime(nanosElapsedSleeping);
                    if (stopRequested())
                        break;
                    sampleSpecialStats(false);
                    if (stopRequested())
                        break;
                    checkListeners();
                    if (stopRequested())
                        break;
                    this.sampleCollector.sample(nanosTimeStamp);
                    final long nanosSpentWorking = timer.reset();
                    accountForTimeSpentWorking(nanosSpentWorking, nanosElapsedSleeping);
                } else if (!stopRequested() && !isSamplingEnabled()) {
                    // fixes bug 42527
                    sampleSpecialStats(true);
                }
            }
        } catch (InterruptedException | CancelException ex) {
        // Silently exit
        } catch (RuntimeException ex) {
            logger.fatal(LogMarker.STATISTICS_MARKER, ex.getMessage(), ex);
            throw ex;
        } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // If this ever returns, rethrow the error. We're poisoned
            // now, so don't let this thread continue.
            throw err;
        } catch (Error ex) {
            // Whenever you catch Error or Throwable, you must also
            // catch VirtualMachineError (see above). However, there is
            // _still_ a possibility that you are dealing with a cascading
            // error condition, so you also need to check to see if the JVM
            // is still usable:
            SystemFailure.checkFailure();
            logger.fatal(LogMarker.STATISTICS_MARKER, ex.getMessage(), ex);
            throw ex;
        } finally {
            try {
                closeSpecialStats();
                if (this.sampleCollector != null) {
                    this.sampleCollector.close();
                }
            } finally {
                if (!latchCountedDown) {
                    // Make sure the latch gets counted down since
                    // other threads wait for this to indicate that
                    // the sampler is initialized.
                    this.statSamplerInitializedLatch.countDown();
                }
            }
            if (isDebugEnabled_STATISTICS) {
                logger.trace(LogMarker.STATISTICS_VERBOSE, "HostStatSampler stopped");
            }
        }
    }

    /**
     * Starts the main thread for this service.
     *
     * @throws IllegalStateException if an instance of the {@link #statThread} is still running from a
     *         previous DistributedSystem.
     */
    public void start() {
        synchronized (HostStatSampler.clreplaced) {
            if (statThread != null) {
                try {
                    int msToWait = getSampleRate() + 100;
                    statThread.join(msToWait);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
                if (statThread.isAlive()) {
                    throw new IllegalStateException("Statistics sampling thread is already running, indicating an incomplete shutdown of a previous cache.");
                }
            }
            this.callbackSampler.start(getStatisticsManager(), getSampleRate(), TimeUnit.MILLISECONDS);
            statThread = new LoggingThread("StatSampler", this);
            statThread.setPriority(Thread.MAX_PRIORITY);
            statThread.start();
            // fix #46310 (race between management and sampler init) by waiting for init here
            try {
                waitForInitialization(INITIALIZATION_TIMEOUT_MILLIS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * Tell this service's main thread to terminate.
     */
    public void stop() {
        stop(true);
    }

    private void stop(boolean interruptIfAlive) {
        synchronized (HostStatSampler.clreplaced) {
            this.callbackSampler.stop();
            if (statThread == null) {
                return;
            }
            this.stopRequested = true;
            synchronized (this) {
                this.notifyAll();
            }
            try {
                statThread.join(5000);
            } catch (InterruptedException ignore) {
                // It is important that we shutdown so we'll continue trying for another 2 seconds
                try {
                    statThread.join(2000);
                } catch (InterruptedException ex) {
                } finally {
                    Thread.currentThread().interrupt();
                }
            } finally {
                if (statThread.isAlive()) {
                    if (interruptIfAlive) {
                        // It is still alive so interrupt the thread
                        statThread.interrupt();
                        stop(false);
                    } else {
                        logger.warn(LogMarker.STATISTICS_MARKER, "HostStatSampler thread could not be stopped during shutdown.");
                    }
                } else {
                    this.stopRequested = false;
                    statThread = null;
                }
            }
        }
    }

    public boolean isAlive() {
        synchronized (HostStatSampler.clreplaced) {
            return statThread != null && statThread.isAlive();
        }
    }

    /**
     * Waits for the special statistics to be initialized. For tests, please use
     * {@link #waitForInitialization(long)} instead.
     *
     * @see #initSpecialStats
     * @since GemFire 3.5
     */
    public void waitForInitialization() throws InterruptedException {
        this.statSamplerInitializedLatch.await();
    }

    /**
     * Waits for the special statistics to be initialized. This overridden version of
     * {@link #waitForInitialization()} should always be used within tests.
     *
     * @see #initSpecialStats
     * @since GemFire 7.0
     */
    public boolean waitForInitialization(long ms) throws InterruptedException {
        return awaitInitialization(ms, TimeUnit.MILLISECONDS);
    }

    /**
     * Awaits the initialization of special statistics.
     *
     * @see #initSpecialStats
     */
    public boolean awaitInitialization(final long timeout, final TimeUnit unit) throws InterruptedException {
        return this.statSamplerInitializedLatch.await(timeout, unit);
    }

    public void changeArchive(File newFile) {
        this.sampleCollector.changeArchive(newFile, timer.getTime());
    }

    /**
     * Returns the <code>VMStatsContract</code> for this VM.
     *
     * @since GemFire 3.5
     */
    public VMStatsContract getVMStats() {
        return this.vmStats;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder(getClreplaced().getName());
        sb.append("@").append(System.idenreplacedyHashCode(this));
        return sb.toString();
    }

    protected abstract void checkListeners();

    /**
     * Gets the sample rate in milliseconds
     */
    protected abstract int getSampleRate();

    /**
     * Returns true if sampling is enabled.
     */
    public abstract boolean isSamplingEnabled();

    /**
     * Returns the statistics manager using this sampler.
     */
    protected abstract StatisticsManager getStatisticsManager();

    protected OsStatisticsFactory getOsStatisticsFactory() {
        return null;
    }

    protected void initProcessStats(long id) {
    // do nothing by default
    }

    protected void sampleProcessStats(boolean prepareOnly) {
    // do nothing by default
    }

    protected void closeProcessStats() {
    // do nothing by default
    }

    protected long getSpecialStatsId() {
        try {
            int pid = getStatisticsManager().getPid();
            if (pid > 0) {
                return pid;
            }
        } catch (UncheckedPidUnavailableException ignored) {
        // ignore and fall through
        }
        return getSystemId();
    }

    protected boolean fileSizeLimitInKB() {
        return this.fileSizeLimitInKB;
    }

    protected boolean osStatsDisabled() {
        return this.osStatsDisabled;
    }

    protected boolean stopRequested() {
        return stopper.isCancelInProgress() || this.stopRequested;
    }

    public SampleCollector getSampleCollector() {
        return this.sampleCollector;
    }

    /**
     * Initialize any special sampler stats
     */
    private synchronized void initSpecialStats() {
        // add a vm resource
        long id = getSpecialStatsId();
        this.vmStats = VMStatsContractFactory.create(getStatisticsManager(), id);
        initProcessStats(id);
    }

    /**
     * Closes down anything initialied by initSpecialStats.
     */
    private synchronized void closeSpecialStats() {
        if (this.vmStats != null) {
            this.vmStats.close();
        }
        closeProcessStats();
    }

    /**
     * Called when this sampler has spent some time working and wants it to be accounted for.
     */
    private void accountForTimeSpentWorking(long nanosSpentWorking, long nanosSpentSleeping) {
        this.samplerStats.tookSample(nanosSpentWorking, getStatisticsManager().getStatisticsCount(), nanosSpentSleeping);
    }

    /**
     * @param nanosToDelay the timestamp to delay until it is the current time
     */
    private void delay(final long nanosToDelay) throws InterruptedException {
        timer.reset();
        long now = timer.getLastResetTime();
        long remainingNanos = nanosToDelay - now;
        if (remainingNanos <= 0) {
            remainingNanos = NanoTimer.millisToNanos(MIN_MS_SLEEP);
        }
        while (remainingNanos > 0 && !stopRequested()) {
            long ms = NanoTimer.nanosToMillis(remainingNanos);
            if (ms <= 0) {
                Thread.yield();
            } else {
                if (ms > MIN_MS_SLEEP) {
                    ms -= MIN_MS_SLEEP;
                }
                synchronized (this) {
                    if (stopRequested()) {
                        // check stopRequested inside the sync to prevent a race in which the wait misses the
                        // stopper's notify.
                        return;
                    }
                    // spurious wakeup ok
                    this.wait(ms);
                }
            }
            timer.reset();
            now = timer.getLastResetTime();
            remainingNanos = nanosToDelay - now;
        }
    }

    private long getNanoRate() {
        return NanoTimer.millisToNanos(getSampleRate());
    }

    /**
     * Collect samples of any operating system statistics
     *
     * @param prepareOnly set to true if you only want to call prepareForSample
     */
    private void sampleSpecialStats(boolean prepareOnly) {
        List<Statistics> statsList = getStatisticsManager().getStatsList();
        for (Statistics s : statsList) {
            if (stopRequested())
                return;
            if (s instanceof StatisticsImpl) {
                ((StatisticsImpl) s).prepareForSample();
            }
        }
        if (!prepareOnly && this.vmStats != null) {
            if (stopRequested())
                return;
            this.vmStats.refresh();
        }
        sampleProcessStats(prepareOnly);
    }

    /**
     * Check the elapsed sleep time upon wakeup, and log a warning if it is longer than the delay
     * threshold.
     *
     * @param elapsedSleepTime duration of sleep in nanoseconds
     */
    private void checkElapsedSleepTime(long elapsedSleepTime) {
        if (STAT_SAMPLER_DELAY_THRESHOLD > 0) {
            final long wakeupDelay = elapsedSleepTime - getNanoRate();
            if (wakeupDelay > STAT_SAMPLER_DELAY_THRESHOLD_NANOS) {
                this.samplerStats.incJvmPauses();
                logger.warn(LogMarker.STATISTICS_MARKER, "Statistics sampling thread detected a wakeup delay of {} ms, indicating a possible resource issue. Check the GC, memory, and CPU statistics.", NanoTimer.nanosToMillis(wakeupDelay));
            }
        }
    }
}

17 View Complete Implementation : ConnectionFactoryJUnitTest.java
Copyright Apache License 2.0
Author : apache
@Test(expected = CancelException.clreplaced)
public void connectionFactoryThrowsCancelException() throws CancelException, IOException {
    ServerLocation serverLocation = mock(ServerLocation.clreplaced);
    doReturn(false).when(serverLocation).getRequiresCredentials();
    ConnectionConnector connector = mock(ConnectionConnector.clreplaced);
    doReturn(mock(ConnectionImpl.clreplaced)).when(connector).connectClientToServer(serverLocation, false);
    ConnectionSource connectionSource = mock(ConnectionSource.clreplaced);
    doReturn(serverLocation).when(connectionSource).findServer(any(Set.clreplaced));
    // mocks don't seem to work well with CancelCriterion so let's create a real one
    CancelCriterion cancelCriterion = new CancelCriterion() {

        @Override
        public String cancelInProgress() {
            return "shutting down for test";
        }

        @Override
        public RuntimeException generateCancelledException(Throwable throwable) {
            return new PoolCancelledException(cancelInProgress(), throwable);
        }
    };
    ConnectionFactoryImpl connectionFactory = new ConnectionFactoryImpl(connector, connectionSource, 60000, mock(PoolImpl.clreplaced), cancelCriterion);
    connectionFactory.createClientToServerConnection(Collections.emptySet());
}

17 View Complete Implementation : ParallelGatewaySenderQueueJUnitTest.java
Copyright Apache License 2.0
Author : apache
@Before
public void createParallelGatewaySenderQueue() {
    cache = mock(GemFireCacheImpl.clreplaced);
    sender = mock(AbstractGatewaySender.clreplaced);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(sender.getCancelCriterion()).thenReturn(cancelCriterion);
    when(sender.getCache()).thenReturn(cache);
    when(sender.getMaximumQueueMemory()).thenReturn(100);
    when(sender.getLifeCycleLock()).thenReturn(new ReentrantReadWriteLock());
    metaRegionFactory = mock(MetaRegionFactory.clreplaced);
    queue = new ParallelGatewaySenderQueue(sender, Collections.emptySet(), 0, 1, metaRegionFactory);
}

17 View Complete Implementation : CallbackSamplerTest.java
Copyright Apache License 2.0
Author : apache
/**
 * Unit tests for {@link CallbackSampler}.
 */
@RunWith(MockitoJUnitRunner.clreplaced)
public clreplaced CallbackSamplerTest {

    @Mock
    CancelCriterion cancelCriterion;

    @Mock
    StatSamplerStats statSamplerStats;

    @Mock
    StatisticsManager statisticsManager;

    @Mock
    ScheduledExecutorService executorService;

    private CallbackSampler sampler;

    @Before
    public void createSampler() {
        sampler = new CallbackSampler(cancelCriterion, statSamplerStats);
    }

    @Test
    public void taskShouldSampleStatistics() {
        Runnable sampleTask = invokeStartAndGetTask();
        StatisticsImpl stats1 = mock(StatisticsImpl.clreplaced);
        StatisticsImpl stats2 = mock(StatisticsImpl.clreplaced);
        when(stats1.updateSuppliedValues()).thenReturn(3);
        when(stats2.updateSuppliedValues()).thenReturn(2);
        when(stats1.getSupplierCount()).thenReturn(7);
        when(stats2.getSupplierCount()).thenReturn(8);
        when(statisticsManager.getStatsList()).thenReturn(Arrays.asList(stats1, stats2));
        sampleTask.run();
        verify(statSamplerStats).setSampleCallbacks(eq(15));
        verify(statSamplerStats).incSampleCallbackErrors(5);
        verify(statSamplerStats).incSampleCallbackDuration(anyLong());
    }

    @Test
    public void stopShouldStopExecutor() {
        sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
        sampler.stop();
        verify(executorService).shutdown();
    }

    @Test
    public void cancelCriterionShouldStopExecutor() {
        Runnable sampleTask = invokeStartAndGetTask();
        when(cancelCriterion.isCancelInProgress()).thenReturn(Boolean.TRUE);
        sampleTask.run();
        verify(executorService).shutdown();
    }

    private Runnable invokeStartAndGetTask() {
        sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
        ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClreplaced(Runnable.clreplaced);
        verify(executorService).scheduleAtFixedRate(runnableCaptor.capture(), eq(1L), eq(1L), eq(TimeUnit.MILLISECONDS));
        return runnableCaptor.getValue();
    }
}

16 View Complete Implementation : EndpointManagerImpl.java
Copyright Apache License 2.0
Author : apache
public clreplaced EndpointManagerImpl implements EndpointManager {

    private static final Logger logger = LogService.getLogger();

    private volatile Map<ServerLocation, Endpoint> endpointMap = Collections.emptyMap();

    private final Map<ServerLocation, ConnectionStats> statMap = new HashMap<>();

    private final DistributedSystem ds;

    private final String poolName;

    private final EndpointListenerBroadcaster listener = new EndpointListenerBroadcaster();

    protected final CancelCriterion cancelCriterion;

    private final PoolStats poolStats;

    public EndpointManagerImpl(String poolName, DistributedSystem ds, CancelCriterion cancelCriterion, PoolStats poolStats) {
        this.ds = ds;
        this.poolName = poolName;
        this.cancelCriterion = cancelCriterion;
        this.poolStats = poolStats;
        listener.addListener(new EndpointListenerForBridgeMembership());
    }

    @Override
    public Endpoint referenceEndpoint(ServerLocation server, DistributedMember memberId) {
        Endpoint endpoint = endpointMap.get(server);
        boolean addedEndpoint = false;
        if (endpoint == null || endpoint.isClosed()) {
            synchronized (this) {
                endpoint = endpointMap.get(server);
                if (endpoint == null || endpoint.isClosed()) {
                    ConnectionStats stats = getStats(server);
                    Map<ServerLocation, Endpoint> endpointMapTemp = new HashMap<>(endpointMap);
                    endpoint = new Endpoint(this, ds, server, stats, memberId);
                    listener.clearPdxRegistry(endpoint);
                    endpointMapTemp.put(server, endpoint);
                    endpointMap = Collections.unmodifiableMap(endpointMapTemp);
                    addedEndpoint = true;
                    poolStats.setServerCount(endpointMap.size());
                }
            }
        }
        endpoint.addReference();
        if (addedEndpoint) {
            listener.endpointNowInUse(endpoint);
        }
        return endpoint;
    }

    @Override
    public void serverCrashed(Endpoint endpoint) {
        removeEndpoint(endpoint, true);
    }

    void endpointNotInUse(Endpoint endpoint) {
        removeEndpoint(endpoint, false);
    }

    /**
     * Used by Endpoint only, when the reference count for this endpoint reaches 0
     */
    private void removeEndpoint(Endpoint endpoint, boolean crashed) {
        endpoint.close();
        boolean removedEndpoint = false;
        synchronized (this) {
            Map<ServerLocation, Endpoint> endpointMapTemp = new HashMap<>(endpointMap);
            endpoint = endpointMapTemp.remove(endpoint.getLocation());
            if (endpoint != null) {
                endpointMap = Collections.unmodifiableMap(endpointMapTemp);
                removedEndpoint = true;
            }
            poolStats.setServerCount(endpointMap.size());
        }
        if (removedEndpoint) {
            PoolImpl pool = (PoolImpl) PoolManager.find(poolName);
            if (pool != null && pool.getMultiuserAuthentication()) {
                int size = 0;
                ArrayList<ProxyCache> proxyCaches = pool.getProxyCacheList();
                synchronized (proxyCaches) {
                    for (ProxyCache proxyCache : proxyCaches) {
                        try {
                            Long userId = proxyCache.getUserAttributes().getServerToId().remove(endpoint.getLocation());
                            if (userId != null) {
                                ++size;
                            }
                        } catch (CacheClosedException cce) {
                        // If this call is triggered by a Cache.close(), then this can be
                        // expected.
                        }
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("EndpointManagerImpl.removeEndpoint() Removed server {} from {} user's ProxyCache", endpoint.getLocation(), size);
                    }
                }
                UserAttributes ua = UserAttributes.userAttributes.get();
                if (ua != null) {
                    Long userId = ua.getServerToId().remove(endpoint.getLocation());
                    if (userId != null && logger.isDebugEnabled()) {
                        logger.debug("EndpointManagerImpl.removeEndpoint() Removed server {} from thread local variable", endpoint.getLocation());
                    }
                }
            } else if (pool != null && !pool.getMultiuserAuthentication()) {
                endpoint.getLocation().setUserId(-1);
            }
            if (crashed) {
                listener.endpointCrashed(endpoint);
            } else {
                listener.endpointNoLongerInUse(endpoint);
            }
        }
    }

    @Override
    public Map<ServerLocation, Endpoint> getEndpointMap() {
        return endpointMap;
    }

    @Override
    public synchronized void close() {
        for (ConnectionStats stats : statMap.values()) {
            stats.close();
        }
        statMap.clear();
        endpointMap = Collections.emptyMap();
        listener.clear();
    }

    @Override
    public void addListener(EndpointManager.EndpointListener listener) {
        this.listener.addListener(listener);
    }

    @Override
    public void removeListener(EndpointManager.EndpointListener listener) {
        this.listener.removeListener(listener);
    }

    private synchronized ConnectionStats getStats(ServerLocation location) {
        ConnectionStats stats = statMap.get(location);
        if (stats == null) {
            PoolImpl pool = (PoolImpl) PoolManager.find(poolName);
            if (pool != null) {
                if (pool.getGatewaySender() != null) {
                    String statName = pool.getGatewaySender().getId() + "-" + location.toString();
                    stats = new ConnectionStats(ds, "GatewaySender", statName, this.poolStats);
                }
            }
            if (stats == null) {
                String statName = poolName + "-" + location.toString();
                stats = new ConnectionStats(ds, "Client", statName, poolStats);
            }
            statMap.put(location, stats);
        }
        return stats;
    }

    @Override
    public synchronized Map<ServerLocation, ConnectionStats> getAllStats() {
        return new HashMap<>(statMap);
    }

    @Override
    public int getConnectedServerCount() {
        return getEndpointMap().size();
    }

    protected static clreplaced EndpointListenerBroadcaster implements EndpointManager.EndpointListener {

        private volatile Set<EndpointListener> endpointListeners = Collections.emptySet();

        public synchronized void addListener(EndpointManager.EndpointListener listener) {
            HashSet<EndpointListener> tmpListeners = new HashSet<>(endpointListeners);
            tmpListeners.add(listener);
            endpointListeners = Collections.unmodifiableSet(tmpListeners);
        }

        public synchronized void clear() {
            endpointListeners = Collections.emptySet();
        }

        public void removeListener(EndpointManager.EndpointListener listener) {
            HashSet<EndpointListener> tmpListeners = new HashSet<>(endpointListeners);
            tmpListeners.remove(listener);
            endpointListeners = Collections.unmodifiableSet(tmpListeners);
        }

        @Override
        public void endpointCrashed(Endpoint endpoint) {
            for (EndpointListener listener : endpointListeners) {
                listener.endpointCrashed(endpoint);
            }
        }

        @Override
        public void endpointNoLongerInUse(Endpoint endpoint) {
            for (EndpointListener listener : endpointListeners) {
                listener.endpointNoLongerInUse(endpoint);
            }
        }

        @Override
        public void endpointNowInUse(Endpoint endpoint) {
            for (EndpointListener listener : endpointListeners) {
                if (!(listener instanceof PdxRegistryRecoveryListener)) {
                    listener.endpointNowInUse(endpoint);
                }
            }
        }

        void clearPdxRegistry(Endpoint endpoint) {
            for (EndpointListener listener : endpointListeners) {
                if (listener instanceof PdxRegistryRecoveryListener) {
                    listener.endpointNowInUse(endpoint);
                }
            }
        }
    }

    public clreplaced EndpointListenerForBridgeMembership implements EndpointManager.EndpointListener {

        @Override
        public void endpointCrashed(Endpoint endpoint) {
            if (cancelCriterion.isCancelInProgress()) {
                return;
            }
            InternalClientMembership.notifyServerCrashed(endpoint.getLocation());
        }

        @Override
        public void endpointNoLongerInUse(Endpoint endpoint) {
            if (cancelCriterion.isCancelInProgress()) {
                return;
            }
            InternalClientMembership.notifyServerLeft(endpoint.getLocation());
        }

        @Override
        public void endpointNowInUse(Endpoint endpoint) {
            if (cancelCriterion.isCancelInProgress()) {
                return;
            }
            InternalClientMembership.notifyServerJoined(endpoint.getLocation());
        }
    }

    @Override
    public String getPoolName() {
        return poolName;
    }
}

16 View Complete Implementation : SingleThreadColocationLogger.java
Copyright Apache License 2.0
Author : apache
/**
 * Writes a log entry every SLEEP_PERIOD when there are missing colocated child regions for this
 * region.
 */
private void checkForMissingColocatedRegion(CancelCriterion cancelCriterion) throws InterruptedException {
    synchronized (lock) {
        boolean firstLogIteration = true;
        while (true) {
            long waitMillis = firstLogIteration ? delayMillis : intervalMillis;
            // delay for first log message is half of the interval between subsequent log messages
            if (firstLogIteration) {
                firstLogIteration = false;
            }
            lock.wait(waitMillis);
            PRHARedundancyProvider redundancyProvider = region.getRedundancyProvider();
            if (redundancyProvider != null && redundancyProvider.isPersistentRecoveryComplete()) {
                // Terminate the logging thread
                // isPersistentRecoveryComplete is true only when there are no missing colocated regions
                break;
            }
            if (missingChildren.isEmpty()) {
                break;
            }
            if (cancelCriterion.isCancelInProgress()) {
                break;
            }
            logMissingRegions(region.getFullPath());
        }
    }
}

16 View Complete Implementation : PoolImplTest.java
Copyright Apache License 2.0
Author : apache
private PoolImpl getPool(int retryAttemptsAttribute) {
    final DistributionConfig distributionConfig = mock(DistributionConfig.clreplaced);
    doReturn(new SecurableCommunicationChannel[] {}).when(distributionConfig).getSecurableCommunicationChannels();
    final Properties properties = new Properties();
    properties.put(DURABLE_CLIENT_ID, "1");
    final Statistics statistics = mock(Statistics.clreplaced);
    final PoolFactoryImpl.PoolAttributes poolAttributes = mock(PoolFactoryImpl.PoolAttributes.clreplaced);
    /*
     * These are the minimum pool attributes required
     * so that basic validation and setup completes successfully. The values of
     * these attributes have no importance to the replacedertions of the test itself.
     */
    doReturn(1).when(poolAttributes).getMaxConnections();
    doReturn((long) 10e8).when(poolAttributes).getPingInterval();
    doReturn(retryAttemptsAttribute).when(poolAttributes).getRetryAttempts();
    final CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    final InternalCache internalCache = mock(InternalCache.clreplaced);
    doReturn(cancelCriterion).when(internalCache).getCancelCriterion();
    final InternalDistributedSystem internalDistributedSystem = mock(InternalDistributedSystem.clreplaced);
    doReturn(distributionConfig).when(internalDistributedSystem).getConfig();
    doReturn(properties).when(internalDistributedSystem).getProperties();
    doReturn(statistics).when(internalDistributedSystem).createAtomicStatistics(any(), anyString());
    final PoolManagerImpl poolManager = mock(PoolManagerImpl.clreplaced);
    doReturn(true).when(poolManager).isNormal();
    final ThreadsMonitoring tMonitoring = mock(ThreadsMonitoring.clreplaced);
    return PoolImpl.create(poolManager, "pool", poolAttributes, new LinkedList<LocatorAddress>(), internalDistributedSystem, internalCache, tMonitoring);
}

16 View Complete Implementation : CacheClientUpdaterJUnitTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void failureToConnectClosesStatistics() throws Exception {
    // CacheClientUpdater's constructor takes a lot of parameters that we need to mock
    ServerLocation location = new ServerLocation("localhost", 1234);
    ClientSideHandshake handshake = mock(ClientSideHandshake.clreplaced);
    when(handshake.isDurable()).thenReturn(Boolean.FALSE);
    QueueManager queueManager = null;
    mock(QueueManager.clreplaced);
    EndpointManager endpointManager = mock(EndpointManager.clreplaced);
    Endpoint endpoint = mock(Endpoint.clreplaced);
    // shutdown checks
    DistributedSystem distributedSystem = mock(DistributedSystem.clreplaced);
    CancelCriterion cancelCriterion = mock(CancelCriterion.clreplaced);
    when(distributedSystem.getCancelCriterion()).thenReturn(cancelCriterion);
    when(cancelCriterion.isCancelInProgress()).thenReturn(Boolean.FALSE);
    // engineer a failure to connect via SocketCreator
    SocketCreator socketCreator = mock(SocketCreator.clreplaced);
    when(socketCreator.connectForClient(any(String.clreplaced), any(Integer.clreplaced), any(Integer.clreplaced), any(Integer.clreplaced))).thenThrow(new SocketException("ouch"));
    // mock some stats that we can then use to ensure that they're closed when the problem occurs
    CacheClientUpdater.StatisticsProvider statisticsProvider = mock(CacheClientUpdater.StatisticsProvider.clreplaced);
    CacheClientUpdater.CCUStats ccuStats = mock(CacheClientUpdater.CCUStats.clreplaced);
    when(statisticsProvider.createStatistics(distributedSystem, location)).thenReturn(ccuStats);
    // CCU's constructor fails to connect
    CacheClientUpdater clientUpdater = new CacheClientUpdater("testUpdater", location, false, distributedSystem, handshake, queueManager, endpointManager, endpoint, 10000, socketCreator, statisticsProvider);
    // now introspect to make sure the right actions were taken
    // The updater should not be in a connected state
    replacedertThat(clientUpdater.isConnected()).isFalse();
    // The statistics should be closed
    verify(ccuStats).close();
    // The endpoint should be reported as having crashed
    verify(endpointManager).serverCrashed(endpoint);
}

16 View Complete Implementation : ClientTXStateStubTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced ClientTXStateStubTest {

    private InternalCache cache;

    private DistributionManager dm;

    private TXStateProxy stateProxy;

    private DistributedMember target;

    private LocalRegion region;

    private ServerRegionProxy serverRegionProxy;

    private CancelCriterion cancelCriterion;

    private InternalPool internalPool;

    @Before
    public void setUp() {
        cache = mock(InternalCache.clreplaced);
        dm = mock(DistributionManager.clreplaced);
        stateProxy = mock(TXStateProxy.clreplaced);
        target = mock(DistributedMember.clreplaced);
        region = mock(LocalRegion.clreplaced);
        serverRegionProxy = mock(ServerRegionProxy.clreplaced);
        internalPool = mock(InternalPool.clreplaced);
        cancelCriterion = mock(CancelCriterion.clreplaced);
        when(region.getServerProxy()).thenReturn(serverRegionProxy);
        when(serverRegionProxy.getPool()).thenReturn(internalPool);
        when(stateProxy.getTxId()).thenReturn(mock(TXId.clreplaced));
        when(cache.getCancelCriterion()).thenReturn(cancelCriterion);
        doThrow(new CacheClosedException()).when(cancelCriterion).checkCancelInProgress(any());
    }

    @Test
    public void commitThrowsCancelExceptionIfCacheIsClosed() {
        ClientTXStateStub stub = spy(new ClientTXStateStub(cache, dm, stateProxy, target, region));
        when(stub.createTXLockRequest()).thenReturn(mock(TXLockRequest.clreplaced));
        when(stub.createTXRegionLockRequestImpl(any(), any())).thenReturn(mock(TXRegionLockRequestImpl.clreplaced));
        replacedertThatThrownBy(() -> stub.commit()).isInstanceOf(CancelException.clreplaced);
    }

    @Test
    public void commitReleasesServerAffinityAfterCommit() {
        TXCommitMessage txCommitMessage = mock(TXCommitMessage.clreplaced);
        TXManagerImpl txManager = mock(TXManagerImpl.clreplaced);
        when(cache.getTxManager()).thenReturn(txManager);
        when(serverRegionProxy.commit(anyInt())).thenReturn(txCommitMessage);
        doNothing().when(cancelCriterion).checkCancelInProgress(null);
        doNothing().when(txManager).setTXState(null);
        ClientTXStateStub stub = spy(new ClientTXStateStub(cache, dm, stateProxy, target, region));
        InOrder order = inOrder(serverRegionProxy, internalPool, cancelCriterion);
        stub.commit();
        order.verify(serverRegionProxy).commit(anyInt());
        order.verify(internalPool).releaseServerAffinity();
        order.verify(cancelCriterion).checkCancelInProgress(null);
    }

    @Test
    public void commitReleasesServerAffinity_whenCommitThrowsAnException() {
        TXManagerImpl txManager = mock(TXManagerImpl.clreplaced);
        when(cache.getTxManager()).thenReturn(txManager);
        when(serverRegionProxy.commit(anyInt())).thenThrow(new InternalGemFireError());
        doNothing().when(cancelCriterion).checkCancelInProgress(null);
        doNothing().when(txManager).setTXState(null);
        ClientTXStateStub stub = spy(new ClientTXStateStub(cache, dm, stateProxy, target, region));
        InOrder order = inOrder(serverRegionProxy, internalPool);
        replacedertThatThrownBy(() -> stub.commit()).isInstanceOf(InternalGemFireError.clreplaced);
        order.verify(serverRegionProxy).commit(anyInt());
        order.verify(internalPool).releaseServerAffinity();
    }
}