Example usage for java.util.concurrent.locks Condition signal

List of usage examples for java.util.concurrent.locks Condition signal

Introduction

In this page you can find the example usage for java.util.concurrent.locks Condition signal.

Prototype

void signal();

Source Link

Document

Wakes up one waiting thread.

Usage

From source file:io.fabric8.maven.core.service.PortForwardService.java

/**
 * Forwards a port to the newest pod matching the given selector.
 * If another pod is created, it forwards connections to the new pod once it's ready.
 *//*www  . j  a v  a  2  s  . c o  m*/
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector,
        final int remotePort, final int localPort) throws Fabric8ServiceException {

    final Lock monitor = new ReentrantLock(true);
    final Condition podChanged = monitor.newCondition();
    final Pod[] nextForwardedPod = new Pod[1];

    final Thread forwarderThread = new Thread() {
        @Override
        public void run() {

            Pod currentPod = null;
            Closeable currentPortForward = null;

            try {
                monitor.lock();

                while (true) {
                    if (podEquals(currentPod, nextForwardedPod[0])) {
                        podChanged.await();
                    } else {
                        Pod nextPod = nextForwardedPod[0]; // may be null
                        try {
                            monitor.unlock();
                            // out of critical section

                            if (currentPortForward != null) {
                                log.info("Closing port-forward from pod %s",
                                        KubernetesHelper.getName(currentPod));
                                currentPortForward.close();
                                currentPortForward = null;
                            }

                            if (nextPod != null) {
                                log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
                                currentPortForward = forwardPortAsync(externalProcessLogger,
                                        KubernetesHelper.getName(nextPod), remotePort, localPort);
                            } else {
                                log.info("Waiting for a pod to become ready before starting port-forward");
                            }
                            currentPod = nextPod;
                        } finally {
                            monitor.lock();
                        }
                    }

                }

            } catch (InterruptedException e) {
                log.debug("Port-forwarding thread interrupted", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.warn("Error while port-forwarding to pod", e);
            } finally {
                monitor.unlock();

                if (currentPortForward != null) {
                    try {
                        currentPortForward.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    // Switching forward to the current pod if present
    Pod newPod = getNewestPod(podSelector);
    nextForwardedPod[0] = newPod;

    final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log)
            .watch(new Watcher<Pod>() {

                @Override
                public void eventReceived(Action action, Pod pod) {
                    monitor.lock();
                    try {
                        List<Pod> candidatePods;
                        if (nextForwardedPod[0] != null) {
                            candidatePods = new LinkedList<>();
                            candidatePods.add(nextForwardedPod[0]);
                            candidatePods.add(pod);
                        } else {
                            candidatePods = Collections.singletonList(pod);
                        }
                        Pod newPod = getNewestPod(candidatePods); // may be null
                        if (!podEquals(nextForwardedPod[0], newPod)) {
                            nextForwardedPod[0] = newPod;
                            podChanged.signal();
                        }
                    } finally {
                        monitor.unlock();
                    }
                }

                @Override
                public void onClose(KubernetesClientException e) {
                    // don't care
                }
            });

    forwarderThread.start();

    final Closeable handle = new Closeable() {
        @Override
        public void close() throws IOException {
            try {
                watch.close();
            } catch (Exception e) {
            }
            try {
                forwarderThread.interrupt();
                forwarderThread.join(15000);
            } catch (Exception e) {
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                handle.close();
            } catch (Exception e) {
                // suppress
            }
        }
    });

    return handle;
}

From source file:org.commoncrawl.util.S3InputStream.java

@Override
public boolean contentAvailable(NIOHttpConnection theConnection, int itemId, String itemKey,
        NIOBufferList contentBuffer) {/*from  w  w  w  . j a v a  2  s  . c  o m*/

    ByteBuffer buffer = null;
    IOException exception = null;
    //int receivedBytes = 0;
    try {
        while ((buffer = contentBuffer.read()) != null) {
            if (buffer.position() != 0) {
                buffer = buffer.slice();
            }
            //receivedBytes += buffer.remaining();
            buffer.position(buffer.limit());
            _bufferQueue.write(buffer);
        }
        _bufferQueue.flush();
    } catch (IOException e) {
        LOG.error(CCStringUtils.stringifyException(e));
        exception = e;
    }
    if (_bufferQueue.available() >= MAX_BUFFER_SIZE) {
        LOG.info("*** PAUSING DOWNLOADS FOR:" + theConnection.getURL());
        theConnection.disableReads();
        pausedConnection.set(theConnection);
    }
    //long nanoTimeStart = System.nanoTime();
    _writeLock.lock();
    //long nanoTimeEnd = System.nanoTime();
    //System.out.println("Received: " + receivedBytes + "for URI:" + uri + " Lock took:" + (nanoTimeEnd-nanoTimeStart));
    try {
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (exception != null) {
            _eofCondition.set(true);
            _exception.set(exception);
        }
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
    return true;
}

From source file:org.commoncrawl.util.S3InputStream.java

@Override
public void downloadFailed(NIOHttpConnection connection, int itemId, String itemKey, String errorCode) {
    LOG.error("Download Failed for URI:" + S3InputStream.this.uri);
    _writeLock.lock();//from  w  ww  .  j  a va2s. c  om
    try {
        _exception.set(new IOException(errorCode));
        _eofCondition.set(true);
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
    downloader.getEventLoop().cancelTimer(timeoutTimer);
    activeConnection.set(null);
}

From source file:org.commoncrawl.util.S3InputStream.java

@Override
public void downloadComplete(NIOHttpConnection connection, int itemId, String itemKey) {
    LOG.info("Download Complete for URI:" + S3InputStream.this.uri);
    _writeLock.lock();/*  w  w  w .  j  a v  a  2  s  . c  om*/
    try {
        _exception.set(null);
        _eofCondition.set(true);
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
    downloader.getEventLoop().cancelTimer(timeoutTimer);
    activeConnection.set(null);
}

From source file:org.commoncrawl.util.shared.S3InputStream.java

@Override
public boolean contentAvailable(NIOHttpConnection theConnection, int itemId, String itemKey,
        NIOBufferList contentBuffer) {//from   ww  w. j  ava2 s . c  om

    ByteBuffer buffer = null;
    IOException exception = null;
    //int receivedBytes = 0;
    try {
        while ((buffer = contentBuffer.read()) != null) {
            if (buffer.position() != 0) {
                buffer = buffer.slice();
            }
            //receivedBytes += buffer.remaining();
            buffer.position(buffer.limit());
            _bufferQueue.write(buffer);
        }
        _bufferQueue.flush();
    } catch (IOException e) {
        LOG.error(CCStringUtils.stringifyException(e));
        exception = e;
    }
    if (_bufferQueue.available() >= MAX_BUFFER_SIZE) {
        theConnection.disableReads();
        pausedConnection.set(theConnection);
    }
    //long nanoTimeStart = System.nanoTime();
    _writeLock.lock();
    //long nanoTimeEnd = System.nanoTime();
    //System.out.println("Received: " + receivedBytes + "for URI:" + uri + " Lock took:" + (nanoTimeEnd-nanoTimeStart));
    try {
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (exception != null) {
            _eofCondition.set(true);
            _exception.set(exception);
        }
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
    return true;
}

From source file:org.commoncrawl.util.shared.S3InputStream.java

@Override
public void downloadFailed(int itemId, String itemKey, String errorCode) {
    LOG.error("Download Failed for URI:" + S3InputStream.this.uri);
    _writeLock.lock();/*from www.ja  v a  2s.c  o m*/
    try {
        _exception.set(new IOException(errorCode));
        _eofCondition.set(true);
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
}

From source file:org.commoncrawl.util.shared.S3InputStream.java

@Override
public void downloadComplete(int itemId, String itemKey) {
    LOG.info("Download Complete for URI:" + S3InputStream.this.uri);
    _writeLock.lock();//from   ww w .  j a v a 2s .c o  m
    try {
        _exception.set(null);
        _eofCondition.set(true);
        Condition writeCondition = _writeEvent.getAndSet(null);
        if (writeCondition != null) {
            writeCondition.signal();
        }
    } finally {
        _writeLock.unlock();
    }
}