Example usage for java.lang InterruptedException getCause

List of usage examples for java.lang InterruptedException getCause

Introduction

In this page you can find the example usage for java.lang InterruptedException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.apache.distributedlog.auditor.DLAuditor.java

/**
 * Find leak ledgers phase 1: collect ledgers set.
 *//*from  w  w w  . j  ava 2 s  .  c  om*/
private Set<Long> collectLedgersFromBK(BookKeeperClient bkc, final ExecutorService executorService)
        throws IOException {
    LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get());

    final Set<Long> ledgers = new HashSet<Long>();
    final CompletableFuture<Void> doneFuture = FutureUtils.createFuture();

    BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() {
        @Override
        public void process(Long lid, final AsyncCallback.VoidCallback cb) {
            synchronized (ledgers) {
                ledgers.add(lid);
                if (0 == ledgers.size() % 1000) {
                    logger.info("Collected {} ledgers", ledgers.size());
                }
            }
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    cb.processResult(BKException.Code.OK, null, null);
                }
            });

        }
    };
    AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (BKException.Code.OK == rc) {
                doneFuture.complete(null);
            } else {
                doneFuture.completeExceptionally(BKException.create(rc));
            }
        }
    };
    lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException);
    try {
        doneFuture.get();
        logger.info("Collected total {} ledgers", ledgers.size());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new DLInterruptedException("Interrupted on collecting ledgers : ", e);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) (e.getCause());
        } else {
            throw new IOException("Failed to collect ledgers : ", e.getCause());
        }
    }
    return ledgers;
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public Future<Dataset> transform(Dataset dataset, Algorithm algorithm, Map<String, Object> parameters,
        String predictionFeature, MetaInfo datasetMeta, String taskId) {
    try {//w  ww. j a  va 2 s.c  o  m
        Model model = this.train(dataset, algorithm, parameters, predictionFeature, datasetMeta, taskId).get();
        return this.predict(dataset, model, datasetMeta, taskId);
    } catch (InterruptedException ex) {
        throw new RuntimeException(
                "Error while transforming Dataset:" + dataset.getId() + " with Algorithm:" + algorithm.getId(),
                ex);
    } catch (ExecutionException ex) {
        throw new RuntimeException(
                "Error while transforming Dataset:" + dataset.getId() + " with Algorithm:" + algorithm.getId(),
                ex.getCause());
    }
}

From source file:de.digiway.rapidbreeze.server.model.download.DownloadManager.java

private <T> T handleFutureException(Future<T> future) {
    try {//from   ww  w. java 2 s.  c  o m
        return future.get();
    } catch (InterruptedException ex) {
        throw new IllegalStateException(DownloadManager.class.getSimpleName() + " action was interrupted.", ex);
    } catch (ExecutionException ex) {
        throw new IllegalStateException(
                "Exception during execution of " + DownloadManager.class.getSimpleName() + " action.",
                ex.getCause());
    }
}

From source file:net.solarnetwork.node.io.serial.rxtx.SerialPortConnection.java

private <T> T performIOTaskWithMaxWait(AbortableCallable<T> task) throws IOException {
    T result = null;//from   w  w w  .ja v a2s.  c o  m
    Future<T> future = executor.submit(task);
    final long maxMs = Math.max(1, serialParams.getMaxWait());
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted communicating with serial port", e);
        throw new IOException("Interrupted communicating with serial port", e);
    } catch (ExecutionException e) {
        log.debug("Exception thrown communicating with serial port", e.getCause());
        throw new IOException("Exception thrown communicating with serial port", e.getCause());
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting operation", maxMs);
        future.cancel(true);
        throw new LockTimeoutException("Timeout waiting " + serialParams.getMaxWait() + "ms for serial data");
    } finally {
        task.abort();
    }
    return result;
}

From source file:com.twitter.distributedlog.auditor.DLAuditor.java

private long calculateLedgerSpaceUsage(BookKeeperClient bkc, final ExecutorService executorService)
        throws IOException {
    final AtomicLong totalBytes = new AtomicLong(0);
    final AtomicLong totalEntries = new AtomicLong(0);
    final AtomicLong numLedgers = new AtomicLong(0);

    LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get());

    final SettableFuture<Void> doneFuture = SettableFuture.create();
    final BookKeeper bk = bkc.get();

    BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() {
        @Override//  w  ww .  ja va2 s  .  c  o  m
        public void process(final Long lid, final AsyncCallback.VoidCallback cb) {
            numLedgers.incrementAndGet();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    bk.asyncOpenLedgerNoRecovery(lid, BookKeeper.DigestType.CRC32,
                            conf.getBKDigestPW().getBytes(UTF_8),
                            new org.apache.bookkeeper.client.AsyncCallback.OpenCallback() {
                                @Override
                                public void openComplete(int rc, LedgerHandle lh, Object ctx) {
                                    final int cbRc;
                                    if (BKException.Code.OK == rc) {
                                        totalBytes.addAndGet(lh.getLength());
                                        totalEntries.addAndGet(lh.getLastAddConfirmed() + 1);
                                        cbRc = rc;
                                    } else {
                                        cbRc = BKException.Code.ZKException;
                                    }
                                    executorService.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            cb.processResult(cbRc, null, null);
                                        }
                                    });
                                }
                            }, null);
                }
            });
        }
    };
    AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (BKException.Code.OK == rc) {
                doneFuture.set(null);
            } else {
                doneFuture.setException(BKException.create(rc));
            }
        }
    };
    lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException);
    try {
        doneFuture.get();
        logger.info("calculated {} ledgers\n\ttotal bytes = {}\n\ttotal entries = {}",
                new Object[] { numLedgers.get(), totalBytes.get(), totalEntries.get() });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new DLInterruptedException("Interrupted on calculating ledger space : ", e);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) (e.getCause());
        } else {
            throw new IOException("Failed to calculate ledger space : ", e.getCause());
        }
    }
    return totalBytes.get();
}

From source file:org.apache.distributedlog.auditor.DLAuditor.java

private long calculateLedgerSpaceUsage(BookKeeperClient bkc, final ExecutorService executorService)
        throws IOException {
    final AtomicLong totalBytes = new AtomicLong(0);
    final AtomicLong totalEntries = new AtomicLong(0);
    final AtomicLong numLedgers = new AtomicLong(0);

    LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get());

    final CompletableFuture<Void> doneFuture = FutureUtils.createFuture();
    final BookKeeper bk = bkc.get();

    BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() {
        @Override//from w w  w.  java2 s  . c  o  m
        public void process(final Long lid, final AsyncCallback.VoidCallback cb) {
            numLedgers.incrementAndGet();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    bk.asyncOpenLedgerNoRecovery(lid, BookKeeper.DigestType.CRC32,
                            conf.getBKDigestPW().getBytes(UTF_8),
                            new org.apache.bookkeeper.client.AsyncCallback.OpenCallback() {
                                @Override
                                public void openComplete(int rc, LedgerHandle lh, Object ctx) {
                                    final int cbRc;
                                    if (BKException.Code.OK == rc) {
                                        totalBytes.addAndGet(lh.getLength());
                                        totalEntries.addAndGet(lh.getLastAddConfirmed() + 1);
                                        cbRc = rc;
                                    } else {
                                        cbRc = BKException.Code.ZKException;
                                    }
                                    executorService.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            cb.processResult(cbRc, null, null);
                                        }
                                    });
                                }
                            }, null);
                }
            });
        }
    };
    AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (BKException.Code.OK == rc) {
                doneFuture.complete(null);
            } else {
                doneFuture.completeExceptionally(BKException.create(rc));
            }
        }
    };
    lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException);
    try {
        doneFuture.get();
        logger.info("calculated {} ledgers\n\ttotal bytes = {}\n\ttotal entries = {}",
                new Object[] { numLedgers.get(), totalBytes.get(), totalEntries.get() });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new DLInterruptedException("Interrupted on calculating ledger space : ", e);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) (e.getCause());
        } else {
            throw new IOException("Failed to calculate ledger space : ", e.getCause());
        }
    }
    return totalBytes.get();
}

From source file:org.rhq.core.pc.inventory.AvailabilityProxy.java

/**
 * Returns the current or most currently reported availability. If
 * {@link AvailabilityType#UNKNOWN} is returned, then the availability is
 * being computed.//from ww w.java 2s .c o m
 *
 * @throws TimeoutException
 *             if an async check exceeds AVAIL_ASYNC_TIMEOUT
 */
@Override
public AvailabilityType getAvailability() {
    AvailabilityType avail = UNKNOWN;

    try {
        // If the avail check timed out, or if we are not attempting synchronous checks (due to
        // exceeding the consecutive timeout limit) then the future will exist.
        if (availabilityFuture != null) {
            if (availabilityFuture.isDone()) {
                // hold onto and report the last known value if necessary
                avail = availabilityFuture.get();

            } else {
                // We are still waiting on the previously submitted async avail check - let's just return
                // the last one we got. Note that if the future is not done after a large amount of time,
                // then it means this thread could somehow be hung or otherwise stuck and not returning. Not good.
                // In this case, throw a detailed exception to the avail checker.
                long elapsedTime = System.currentTimeMillis() - lastSubmitTime;
                if (elapsedTime > getAsyncTimeout()) {

                    Throwable t = new Throwable();
                    if (current != null) {
                        t.setStackTrace(current.getStackTrace());
                    }
                    String msg = "Availability check ran too long [" + elapsedTime + "ms], canceled for ["
                            + this.resourceContainer
                            + "]; Stack trace includes the timed out thread's stack trace.";
                    availabilityFuture.cancel(true);

                    // try again, maybe the situation will resolve in time for the next check
                    availabilityFuture = this.resourceContainer.submitAvailabilityCheck(this);
                    lastSubmitTime = System.currentTimeMillis();

                    throw new TimeoutException(msg, t);
                } else {
                    return getLastAvailabilityType();
                }
            }
        }

        // request a thread to do an avail check
        availabilityFuture = this.resourceContainer.submitAvailabilityCheck(this);
        lastSubmitTime = System.currentTimeMillis();

        // if we have exceeded the timeout too many times in a row assume that this is a slow
        // resource and stop performing synchronous checks, which would likely fail to return fast enough anyway.
        if (availSyncConsecutiveTimeouts < getSyncTimeoutLimit()) {
            // attempt to get availability synchronously
            avail = availabilityFuture.get(getSyncTimeout(), TimeUnit.MILLISECONDS);

            // success (failure will throw exception)
            availSyncConsecutiveTimeouts = 0;
            availabilityFuture = null;

        } else if (availSyncConsecutiveTimeouts == getSyncTimeoutLimit()) {
            // log one time that we are disabling synchronous checks for this resource
            ++availSyncConsecutiveTimeouts;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Disabling synchronous availability collection for [" + resourceContainer + "]; ["
                        + getSyncTimeoutLimit() + "] consecutive timeouts exceeding [" + getSyncTimeout()
                        + "ms]");
            }
        }
    } catch (InterruptedException e) {
        LOG.debug("InterruptedException; shut down is (likely) in progress.");
        availabilityFuture.cancel(true);
        availabilityFuture = null;
        Thread.currentThread().interrupt();
        return UNKNOWN;

    } catch (ExecutionException e) {
        availabilityFuture = null; // undefine, so in next run new (no longer failed) instance is scheduled
        throw new RuntimeException("Availability check failed : " + e.getCause().getMessage(), e.getCause());

    } catch (java.util.concurrent.TimeoutException e) {
        // failed to get avail synchronously. next call to the future will return availability (we hope)
        ++availSyncConsecutiveTimeouts;
    }

    return processAvail(avail);
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

/**
 * Handle a SerialEvent, looking for "magic" data.
 * /*w  ww  .j  ava 2 s.  c o m*/
 * <p>
 * <b>Note</b> that the <em>magic</em> bytes are <em>not</em> returned by
 * this method, they are stripped from the output buffer.
 * </p>
 * 
 * @param event
 *        the event
 * @param in
 *        the InputStream to read data from
 * @param sink
 *        the output buffer to store the collected bytes
 * @param magicBytes
 *        the "magic" bytes to look for in the event stream
 * @param readLength
 *        the number of bytes, excluding the magic bytes, to read from the
 *        stream
 * @return <em>true</em> if the data has been found
 * @throws TimeoutException
 *         if {@code maxWait} is configured and that amount of time passes
 *         before the requested serial data is read
 */
protected boolean handleSerialEvent(final SerialPortEvent event, final InputStream in,
        final ByteArrayOutputStream sink, final byte[] magicBytes, final int readLength)
        throws TimeoutException, InterruptedException, ExecutionException {
    if (timeout < 1) {
        return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, readLength);
    }

    Callable<Boolean> task = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, readLength);
        }
    };
    Future<Boolean> future = executor.submit(task);
    boolean result = false;
    final long maxMs = Math.max(1, this.maxWait - System.currentTimeMillis() + timeout);
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted waiting for serial data");
        throw e;
    } catch (ExecutionException e) {
        // log stack trace in DEBUG
        log.debug("Exception thrown reading from serial port", e.getCause());
        throw e;
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting read", maxMs);
        future.cancel(true);
        throw e;
    }
    return result;
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

/**
 * Handle a SerialEvent, looking for "magic" start and end data markers.
 * //  w w w.j a  va 2 s. c om
 * <p>
 * <b>Note</b> that the <em>magic</em> bytes <em>are</em> returned by this
 * method.
 * </p>
 * 
 * @param event
 *        the event
 * @param in
 *        the InputStream to read data from
 * @param sink
 *        the output buffer to store the collected bytes
 * @param magicBytes
 *        the "magic" bytes to look for in the event stream
 * @param eofBytes
 *        the "end of file" bytes, that signals the end of the message to
 *        read
 * @return <em>true</em> if the data has been found
 * @throws TimeoutException
 *         if {@code maxWait} is configured and that amount of time passes
 *         before the requested serial data is read
 */
protected boolean handleSerialEvent(final SerialPortEvent event, final InputStream in,
        final ByteArrayOutputStream sink, final byte[] magicBytes, final byte[] eofBytes)
        throws TimeoutException, InterruptedException, ExecutionException {
    if (timeout < 1) {
        return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, eofBytes);
    }

    Callable<Boolean> task = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return handleSerialEventWithoutTimeout(event, in, sink, magicBytes, eofBytes);
        }
    };
    Future<Boolean> future = executor.submit(task);
    boolean result = false;
    final long maxMs = Math.max(1, this.maxWait - System.currentTimeMillis() + timeout);
    eventLog.trace("Waiting at most {}ms for data", maxMs);
    try {
        result = future.get(maxMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.debug("Interrupted waiting for serial data");
        throw e;
    } catch (ExecutionException e) {
        // log stack trace in DEBUG
        log.debug("Exception thrown reading from serial port", e.getCause());
        throw e;
    } catch (TimeoutException e) {
        log.warn("Timeout waiting {}ms for serial data, aborting read", maxMs);
        future.cancel(true);
        throw e;
    }
    return result;
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

@SuppressWarnings("unchecked")
@Override//from w w w .  j a  v a  2 s.c  o m
protected void poll() throws InterruptedException {
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(),
            ConnectionStatusEventType.POLLING));
    Object result = null;

    try {
        result = delegate.poll();

        if (isTerminated()) {
            return;
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.READING));

        // the result object will be a ResultSet or if JavaScript is used, we also allow the user to return a List<Map<String, Object>>
        if (result instanceof ResultSet) {
            processResultSet((ResultSet) result);
        } else if (result instanceof List) {
            // if the result object is a List, then assume it is a list of maps representing a row to process
            processResultList((List<Map<String, Object>>) result);
        } else {
            throw new DatabaseReceiverException("Unrecognized result: " + result.toString());
        }
    } catch (InterruptedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to poll for messages from the database in channel \""
                + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\"", e);
        eventController.dispatchEvent(
                new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                        getSourceName(), connectorProperties.getName(), null, e.getCause()));
        return;
    } finally {
        if (result instanceof ResultSet) {
            DbUtils.closeQuietly((ResultSet) result);
        }

        try {
            delegate.afterPoll();
        } catch (DatabaseReceiverException e) {
            logger.error("Error in channel \""
                    + ChannelController.getInstance().getDeployedChannelById(getChannelId()).getName() + "\": "
                    + e.getMessage(), ExceptionUtils.getRootCause(e));
            eventController.dispatchEvent(
                    new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.SOURCE_CONNECTOR,
                            getSourceName(), connectorProperties.getName(), null, e.getCause()));
        }

        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.IDLE));
    }
}