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:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java

/**
 * @param statement       statement handle to use for execution
 * @param validationQuery query to use to check the connection
 * @param timeout         time, in seconds, to wait for the query to complete
 * @return true if query had to be timed out, false otherwise.
 *//* ww w . j  av  a 2  s .  co m*/
private synchronized boolean validateQueryWithTimeout(final Statement statement, final String validationQuery,
        int timeout) throws SQLException {
    log.info("perform validation query in RefreshableDatasource.executeWithTimeout()");
    final Stopwatch timer = Stopwatch.createStarted();
    try {
        executor.submit(() -> statement.execute(validationQuery)).get(timeout, TimeUnit.SECONDS);
        log.info("validation query returned from RefreshableDatasource.executeWithTimeout() in {}",
                timer.stop());
        return true;
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        log.warn("Unlikely scenario that query thread was interrupted. Application going down?", e);
        throw new SQLException(e);
    } catch (final TimeoutException e) {
        return false;
    } catch (final Exception e) {
        Throwables.propagateIfInstanceOf(e.getCause(), SQLException.class);
        throw Throwables.propagate(e.getCause());
    }
}

From source file:edu.uchc.octane.Palm.java

/**
 * Does most of the plotting work//from w w  w .  j  a  v a 2 s.  c o  m
 * @param type The type of PALM image
 * @param selected Trajectories to be included in the PALM plot
 */
void doConstructPALM(final PalmType type, final int[] selected) {

    class MySwingWorker extends SwingWorker<ImagePlus, Void> {

        @Override
        public ImagePlus doInBackground() {
            ImagePlus imp = null;

            for (int i = 0; i < selected.length; i++) {
                Trajectory traj = dataset_.getTrajectoryByIndex(selected[i]);

                switch (type) {
                case HEAD:
                    renderGaussianSpot(traj.get(0));
                    nPlotted_++;
                    break;
                case TAIL:
                    renderGaussianSpot(traj.get(traj.size() - 1));
                    nPlotted_++;
                    break;
                case AVERAGE:
                    renderAverage(traj);
                    break;
                case ALLPOINTS:
                    renderAllPoints(traj);
                    break;
                case TIMELAPSE:
                    renderMovie(traj);
                    break;
                }

                firePropertyChange("Progress", (double) i / selected.length,
                        (double) (i + 1) / selected.length);
            }

            if (bRenderInColor_) {
                processColor();
            } else {
                for (int i = 0; i < ips_.length; i++) {
                    stack_.addSlice("" + i, ips_[i]);
                }
            }

            if (stack_.getSize() > 1) {
                imp = new ImagePlus("PALM-" + imp_.getTitle(), stack_);
            } else {
                imp = new ImagePlus("PALM-" + imp_.getTitle(), stack_.getProcessor(1));
            }

            return imp;

        }

        @Override
        public void done() {
            ImagePlus imp = null;
            try {
                imp = get();
            } catch (InterruptedException e) {
                System.err.println("PALM thread interrupted");
            } catch (ExecutionException e) {
                IJ.log("PALM rendering error:" + e.getCause().getMessage());
                e.printStackTrace();
            }
            if (imp != null) {
                imp.show();
            }

        }
    }

    MySwingWorker task = new MySwingWorker();

    task.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName() == "Progress") {
                IJ.showProgress((Double) evt.getNewValue());
            }
        }
    });

    task.execute();

}

From source file:com.microsoft.azure.keyvault.extensions.test.SymmetricKeyDefaultProviderTest.java

@Test
public void testSymmetricKeyAesKw256() {
    // Arrange//from  www . j a v a 2s. c o m
    byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E,
            0x1F };
    byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA,
            (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF };
    byte[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63,
            (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E,
            0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 };

    /*
     * This test using the default JCE provider depends on whether unlimited security
     * is installed or not. In the unlimited case, the full test should pass but in
     * the limited case, it should fail with InvalidKeyException.
     */
    boolean unlimited = hasUnlimitedCrypto();
    SymmetricKey key = new SymmetricKey("KEK", KEK);

    byte[] encrypted = null;

    try {
        encrypted = key.wrapKeyAsync(CEK, "A256KW").get().getLeft();

        if (!unlimited)
            fail("Expected ExecutionException");
    } catch (InterruptedException e) {
        fail("InterrupedException");
    } catch (ExecutionException e) {
        // In the limited case, the failure should be InvalidKeyException
        // In the unlimited case, this should not fail
        if (!unlimited) {
            Throwable cause = e.getCause();
            if (cause == null || !(cause instanceof InvalidKeyException))
                fail("ExecutionException");
        } else {
            fail("ExecutionException");
        }
    } catch (NoSuchAlgorithmException e) {
        fail("NoSuchAlgorithmException");
    }

    if (unlimited) {
        // Assert
        assertArrayEquals(EK, encrypted);

        byte[] decrypted = null;

        try {
            decrypted = key.unwrapKeyAsync(EK, "A256KW").get();
        } catch (InterruptedException e) {
            fail("InterrupedException");
        } catch (ExecutionException e) {
            fail("ExecutionException");
        } catch (NoSuchAlgorithmException e) {
            fail("NoSuchAlgorithmException");
        }

        // Assert
        assertArrayEquals(CEK, decrypted);
    }

    try {
        key.close();
    } catch (IOException e) {
        fail("Key could not be closed");
    }
}

From source file:com.kenshoo.freemarker.services.FreeMarkerService.java

/**
 * @param templateSourceCode//from  w w  w. ja va 2 s .c  o  m
 *            The FTL to execute; not {@code null}.
 * @param dataModel
 *            The FreeMarker data-model to execute the template with; maybe {@code null}.
 * @param outputFormat
 *            The output format to execute the template with; maybe {@code null}.
 * @param locale
 *            The locale to execute the template with; maybe {@code null}.
 * @param timeZone
 *            The time zone to execute the template with; maybe {@code null}.
 * 
 * @return The result of the template parsing and evaluation. The method won't throw exception if that fails due to
 *         errors in the template provided, instead it indicates this fact in the response object. That's because
 *         this is a service for trying out the template language, so such errors are part of the normal operation.
 * 
 * @throws RejectedExecutionException
 *             If the service is overburden and thus doing the calculation was rejected.
 * @throws FreeMarkerServiceException
 *             If the calculation fails from a reason that's not a mistake in the template and doesn't fit the
 *             meaning of {@link RejectedExecutionException} either.
 */
public FreeMarkerServiceResponse calculateTemplateOutput(String templateSourceCode, Object dataModel,
        OutputFormat outputFormat, Locale locale, TimeZone timeZone) throws RejectedExecutionException {
    Objects.requireNonNull(templateExecutor, "templateExecutor was null - was postConstruct ever called?");

    final CalculateTemplateOutput task = new CalculateTemplateOutput(templateSourceCode, dataModel,
            outputFormat, locale, timeZone);
    Future<FreeMarkerServiceResponse> future = templateExecutor.submit(task);

    synchronized (task) {
        while (!task.isTemplateExecutionStarted() && !task.isTaskEnded() && !future.isDone()) {
            try {
                task.wait(50); // Timeout is needed to periodically check future.isDone()
            } catch (InterruptedException e) {
                throw new FreeMarkerServiceException("Template execution task was interrupted.", e);
            }
        }
    }

    try {
        return future.get(maxTemplateExecutionTime, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw new FreeMarkerServiceException("Template execution task unexpectedly failed", e.getCause());
    } catch (InterruptedException e) {
        throw new FreeMarkerServiceException("Template execution task was interrupted.", e);
    } catch (TimeoutException e) {
        // Exactly one interruption should be enough, and it should abort template processing pretty much
        // immediately. But to be on the safe side we will interrupt in a loop, with a timeout.
        final long abortionLoopStartTime = System.currentTimeMillis();
        long timeLeft = ABORTION_LOOP_TIME_LIMIT;
        boolean templateExecutionEnded = false;
        do {
            synchronized (task) {
                Thread templateExecutorThread = task.getTemplateExecutorThread();
                if (templateExecutorThread == null) {
                    templateExecutionEnded = true;
                } else {
                    FreeMarkerInternalsAccessor.interruptTemplateProcessing(templateExecutorThread);
                    logger.debug(
                            "Trying to interrupt overly long template processing (" + timeLeft + " ms left).");
                }
            }
            if (!templateExecutionEnded) {
                try {
                    timeLeft = ABORTION_LOOP_TIME_LIMIT - (System.currentTimeMillis() - abortionLoopStartTime);
                    if (timeLeft > 0) {
                        Thread.sleep(ABORTION_LOOP_INTERRUPTION_DISTANCE);
                    }
                } catch (InterruptedException eInt) {
                    logger.error("Template execution abortion loop was interrupted", eInt);
                    timeLeft = 0;
                }
            }
        } while (!templateExecutionEnded && timeLeft > 0);

        if (templateExecutionEnded) {
            logger.debug("Long template processing has ended.");
            try {
                return future.get();
            } catch (InterruptedException | ExecutionException e1) {
                throw new FreeMarkerServiceException("Failed to get result from template executor task", e);
            }
        } else {
            throw new FreeMarkerServiceException(
                    "Couldn't stop long running template processing within " + ABORTION_LOOP_TIME_LIMIT
                            + " ms. It's possibly stuck forever. Such problems can exhaust the executor pool. "
                            + "Template (quoted): " + StringEscapeUtils.escapeJava(templateSourceCode));
        }
    }
}

From source file:com.microsoft.azure.keyvault.extensions.test.SymmetricKeyDefaultProviderTest.java

@Test
public void testSymmetricKeyAesKw192() {

    // Arrange/*from  ww  w . j a va2 s .  c  o m*/
    byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA,
            (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF };
    byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B,
            0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8,
            (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D };

    /*
     * This test using the default JCE provider depends on whether unlimited security
     * is installed or not. In the unlimited case, the full test should pass but in
     * the limited case, it should fail with InvalidKeyException.
     */
    boolean unlimited = hasUnlimitedCrypto();
    SymmetricKey key = new SymmetricKey("KEK", KEK);

    byte[] encrypted = null;

    try {
        encrypted = key.wrapKeyAsync(CEK, "A192KW").get().getLeft();

        if (!unlimited)
            fail("Expected ExecutionException");
    } catch (InterruptedException e) {
        fail("InterrupedException");
    } catch (ExecutionException e) {

        // In the limited case, the failure should be InvalidKeyException
        // In the unlimited case, this should not fail
        if (!unlimited) {
            Throwable cause = e.getCause();
            if (cause == null || !(cause instanceof InvalidKeyException))
                fail("ExecutionException");
        } else {
            fail("ExecutionException");
        }
    } catch (NoSuchAlgorithmException e) {
        fail("NoSuchAlgorithmException");
    }

    if (unlimited) {
        // Assert
        assertArrayEquals(EK, encrypted);

        byte[] decrypted = null;

        try {
            decrypted = key.unwrapKeyAsync(EK, "A192KW").get();
        } catch (InterruptedException e) {
            fail("InterrupedException");
        } catch (ExecutionException e) {
            fail("ExecutionException");
        } catch (NoSuchAlgorithmException e) {
            fail("NoSuchAlgorithmException");
        }

        // Assert
        assertArrayEquals(CEK, decrypted);
    }

    try {
        key.close();
    } catch (IOException e) {
        fail("Key could not be closed");
    }
}

From source file:com.microsoft.azure.keyvault.extensions.test.SymmetricKeyDefaultProviderTest.java

@Test
public void testSymmetricKeyDefaultAlgorithmAesKw192() {
    // Arrange/* www.  ja  v a  2s .c o  m*/
    byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA,
            (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF };
    byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B,
            0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8,
            (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D };

    /*
     * This test using the default JCE provider depends on whether unlimited security
     * is installed or not. In the unlimited case, the full test should pass but in
     * the limited case, it should fail with InvalidKeyException.
     */
    boolean unlimited = hasUnlimitedCrypto();
    SymmetricKey key = new SymmetricKey("KEK", KEK);

    byte[] encrypted = null;
    String algorithm = null;

    try {
        Pair<byte[], String> result = key.wrapKeyAsync(CEK, null).get();

        encrypted = result.getLeft();
        algorithm = result.getRight();

        if (!unlimited)
            fail("Expected ExecutionException");
    } catch (InterruptedException e) {
        fail("InterrupedException");
    } catch (ExecutionException e) {
        // In the limited case, the failure should be InvalidKeyException
        // In the unlimited case, this should not fail
        if (!unlimited) {
            Throwable cause = e.getCause();
            if (cause == null || !(cause instanceof InvalidKeyException))
                fail("ExecutionException");
        } else {
            fail("ExecutionException");
        }
    } catch (NoSuchAlgorithmException e) {
        fail("NoSuchAlgorithmException");
    }

    if (unlimited) {
        // Assert
        assertEquals("A192KW", algorithm);
        assertArrayEquals(EK, encrypted);

        byte[] decrypted = null;

        try {
            decrypted = key.unwrapKeyAsync(EK, algorithm).get();
        } catch (InterruptedException e) {
            fail("InterrupedException");
        } catch (ExecutionException e) {
            fail("ExecutionException");
        } catch (NoSuchAlgorithmException e) {
            fail("NoSuchAlgorithmException");
        }

        // Assert
        assertArrayEquals(CEK, decrypted);
    }

    try {
        key.close();
    } catch (IOException e) {
        fail("Key could not be closed");
    }
}

From source file:com.microsoft.azure.keyvault.extensions.test.SymmetricKeyDefaultProviderTest.java

@Test
public void testSymmetricKeyDefaultAlgorithmAesKw256() {
    // Arrange// www.  j  a v  a2 s  .c o m
    byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
            0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E,
            0x1F };
    byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA,
            (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF };
    byte[] EK = { 0x64, (byte) 0xE8, (byte) 0xC3, (byte) 0xF9, (byte) 0xCE, 0x0F, 0x5B, (byte) 0xA2, 0x63,
            (byte) 0xE9, 0x77, 0x79, 0x05, (byte) 0x81, (byte) 0x8A, 0x2A, (byte) 0x93, (byte) 0xC8, 0x19, 0x1E,
            0x7D, 0x6E, (byte) 0x8A, (byte) 0xE7 };

    /*
     * This test using the default JCE provider depends on whether unlimited security
     * is installed or not. In the unlimited case, the full test should pass but in
     * the limited case, it should fail with InvalidKeyException.
     */
    boolean unlimited = hasUnlimitedCrypto();
    SymmetricKey key = new SymmetricKey("KEK", KEK);

    byte[] encrypted = null;
    String algorithm = null;

    try {
        Pair<byte[], String> result = key.wrapKeyAsync(CEK, null).get();
        encrypted = result.getLeft();
        algorithm = result.getRight();

        if (!unlimited)
            fail("Expected ExecutionException");
    } catch (InterruptedException e) {
        fail("InterrupedException");
    } catch (ExecutionException e) {
        // In the limited case, the failure should be InvalidKeyException
        // In the unlimited case, this should not fail
        if (!unlimited) {
            Throwable cause = e.getCause();
            if (cause == null || !(cause instanceof InvalidKeyException))
                fail("ExecutionException");
        } else {
            fail("ExecutionException");
        }
    } catch (NoSuchAlgorithmException e) {
        fail("NoSuchAlgorithmException");
    }

    if (unlimited) {
        // Assert
        assertEquals("A256KW", algorithm);
        assertArrayEquals(EK, encrypted);

        byte[] decrypted = null;

        try {
            decrypted = key.unwrapKeyAsync(EK, algorithm).get();
        } catch (InterruptedException e) {
            fail("InterrupedException");
        } catch (ExecutionException e) {
            fail("ExecutionException");
        } catch (NoSuchAlgorithmException e) {
            fail("NoSuchAlgorithmException");
        }

        // Assert
        assertArrayEquals(CEK, decrypted);
    }

    try {
        key.close();
    } catch (IOException e) {
        fail("Key could not be closed");
    }
}

From source file:com.splicemachine.compactions.SpliceDefaultCompactor.java

@Override
public List<Path> compact(CompactionRequest request, CompactionThroughputController throughputController,
        User user) throws IOException {
    if (!allowSpark || store.getRegionInfo().isSystemTable())
        return super.compact(request, throughputController, user);
    if (LOG.isTraceEnabled())
        SpliceLogUtils.trace(LOG, "compact(): request=%s", request);

    assert request instanceof SpliceCompactionRequest;

    smallestReadPoint = store.getSmallestReadPoint();
    FileDetails fd = getFileDetails(request.getFiles(), request.isAllFiles());
    this.progress = new CompactionProgress(fd.maxKeyCount);
    List<String> files = new ArrayList<>();
    for (StoreFile sf : request.getFiles()) {
        files.add(sf.getPath().toString());
    }/*from  w  w w .  jav a2 s  . c  om*/
    String regionLocation = getRegionLocation(store);
    SConfiguration config = HConfiguration.getConfiguration();
    DistributedCompaction jobRequest = new DistributedCompaction(getCompactionFunction(), files,
            getJobDetails(request), getJobGroup(request, regionLocation), getJobDescription(request),
            getPoolName(), getScope(request), regionLocation, config.getOlapCompactionMaximumWait());
    CompactionResult result = null;
    Future<CompactionResult> futureResult = EngineDriver.driver().getOlapClient().submit(jobRequest);
    while (result == null) {
        try {
            result = futureResult.get(config.getOlapClientTickTime(), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            //we were interrupted processing, so we're shutting down. Nothing to be done, just die gracefully
            Thread.currentThread().interrupt();
            throw new IOException(e);
        } catch (ExecutionException e) {
            if (e.getCause() instanceof RejectedExecutionException) {
                LOG.warn("Spark compaction execution rejected, falling back to RegionServer execution",
                        e.getCause());
                return super.compact(request, throughputController, user);
            }
            throw Exceptions.rawIOException(e.getCause());
        } catch (TimeoutException e) {
            // check region write status
            if (!store.areWritesEnabled()) {
                futureResult.cancel(true);
                progress.cancel();
                // TODO should we cleanup files written by Spark?
                throw new IOException("Region has been closed, compaction aborted");
            }
        }
    }

    List<String> sPaths = result.getPaths();

    if (LOG.isTraceEnabled())
        SpliceLogUtils.trace(LOG, "Paths Returned: %s", sPaths);

    this.progress.complete();
    ScanType scanType = request.isRetainDeleteMarkers() ? ScanType.COMPACT_RETAIN_DELETES
            : ScanType.COMPACT_DROP_DELETES;
    // trigger MemstoreAwareObserver
    postCreateCoprocScanner(request, scanType, null, user);

    SpliceCompactionRequest scr = (SpliceCompactionRequest) request;
    scr.preStorefilesRename();

    List<Path> paths = new ArrayList<>();
    for (String spath : sPaths) {
        paths.add(new Path(spath));
    }
    return paths;
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiver.java

protected void close() throws IOException {
    // Close the output stream.
    try {/*from ww w .  j  a v a 2 s .  co m*/
        if (zipArchiveOutputStream != null) {
            zOut.writeTo(zipArchiveOutputStream);
            zipArchiveOutputStream.close();
        }
    } catch (IOException ex) {
        // If we're in this finally clause because of an
        // exception, we don't really care if there's an
        // exception when closing the stream. E.g. if it
        // throws "ZIP file must have at least one entry",
        // because an exception happened before we added
        // any files, then we must swallow this
        // exception. Otherwise, the error that's reported
        // will be the close() error, which is not the
        // real cause of the problem.
        if (success) {
            throw ex;
        }

    } catch (InterruptedException e) {
        IOException ex = new IOException("InterruptedException exception");
        ex.initCause(e.getCause());
        throw ex;
    } catch (ExecutionException e) {
        IOException ex = new IOException("Execution exception");
        ex.initCause(e.getCause());
        throw ex;
    }
}

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

/**
 * Find leak ledgers phase 1: collect ledgers set.
 *//*  w  w  w  .j av a  2  s.  co  m*/
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 SettableFuture<Void> doneFuture = SettableFuture.create();

    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.set(null);
            } else {
                doneFuture.setException(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;
}