Example usage for com.google.common.util.concurrent ListenableFutureTask get

List of usage examples for com.google.common.util.concurrent ListenableFutureTask get

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListenableFutureTask get.

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.afewmoreamps.util.PrefetchingInputStream.java

public PrefetchingInputStream(final FileChannel channel, final int prefetchSize, final int prefetchCount)
        throws IOException {
    buffers = new ByteBuffer[prefetchCount];
    for (int ii = 0; ii < prefetchCount; ii++) {
        buffers[ii] = ByteBuffer.allocateDirect(prefetchSize);
        availableBuffers.offer(buffers[ii]);
    }/*from   w  w w  .  j  a v  a2 s.co m*/

    int currentReadPosition = (int) channel.position();
    final long channelSize = channel.size();
    while (currentReadPosition != channelSize) {
        final int readStartingAt = currentReadPosition;
        final int limit = (int) Math.min(currentReadPosition + prefetchSize, channelSize);
        currentReadPosition += limit;
        readTasks.add(ListenableFutureTask.create(new Callable<ByteBuffer>() {
            @Override
            public ByteBuffer call() throws Exception {
                final ByteBuffer buffer = availableBuffers.take();
                buffer.clear();
                buffer.limit(limit);
                while (buffer.hasRemaining()) {
                    int read = channel.read(buffer, readStartingAt);
                    if (read == -1) {
                        throw new EOFException();
                    }
                }
                buffer.flip();
                return buffer;
            }
        }));
    }
    es.execute(new Runnable() {
        @Override
        public void run() {
            for (ListenableFutureTask<?> task : readTasks) {
                task.run();
                try {
                    try {
                        task.get();
                    } catch (InterruptedException e) {
                        return;
                    }
                } catch (ExecutionException e) {
                    if (e.getCause() instanceof InterruptedException) {
                        return;
                    }
                }
            }
        }
    });
    m_taskIterator = readTasks.iterator();
}

From source file:org.trinity.shellplugin.widget.impl.view.qt.AbstractQWidgetViewProvider.java

@Override
public T get() {//w w  w .  j a  va 2  s  . c  o  m
    final ListenableFutureTask<T> futureTask = ListenableFutureTask.create(new Callable<T>() {
        @Override
        public T call() {
            final T view = createView();
            view.setWindowFlags(WindowType.X11BypassWindowManagerHint);
            view.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
            view.setAttribute(WidgetAttribute.WA_DontCreateNativeAncestors, true);
            return view;
        }
    });
    QApplication.invokeLater(futureTask);
    try {
        return futureTask.get();
    } catch (final InterruptedException e) {
        throw new Error(e);
    } catch (final ExecutionException e) {
        throw new Error(e);
    }
}

From source file:org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.java

/**
 * Checks for the DataStore consistency and reports the number of missing blobs still referenced.
 * //  w w w . j  av a  2 s .c  o m
 * @return the missing blobs
 * @throws Exception
 */
@Override
public long checkConsistency() throws Exception {
    boolean threw = true;
    GarbageCollectorFileState fs = new GarbageCollectorFileState(root);
    long candidates = 0;

    try {
        LOG.info("Starting blob consistency check");

        // Find all blobs available in the blob store
        ListenableFutureTask<Integer> blobIdRetriever = ListenableFutureTask.create(new BlobIdRetriever(fs));
        executor.execute(blobIdRetriever);

        // Mark all used blob references
        iterateNodeTree(fs);

        try {
            blobIdRetriever.get();
        } catch (ExecutionException e) {
            LOG.warn("Error occurred while fetching all the blobIds from the BlobStore");
            threw = false;
            throw e;
        }

        LOG.trace("Starting difference phase of the consistency check");
        FileLineDifferenceIterator iter = new FileLineDifferenceIterator(fs.getAvailableRefs(),
                fs.getMarkedRefs(), transformer);
        candidates = calculateDifference(fs, iter);
        LOG.trace("Ending difference phase of the consistency check");

        LOG.info("Consistency check found [{}] missing blobs", candidates);
        if (candidates > 0) {
            LOG.warn(
                    "Consistency check failure in the the blob store : {}, check missing candidates in file {}",
                    blobStore, fs.getGcCandidates().getAbsolutePath());
        }
    } finally {
        if (!LOG.isTraceEnabled() && candidates == 0) {
            Closeables.close(fs, threw);
        }
    }
    return candidates;
}

From source file:org.voltdb.ClientInterface.java

public ListenableFutureTask<?> processFinishedCompilerWork(final AsyncCompilerResult result) {
    /*//w ww.  j a va2s.co  m
     * Do the task in the network thread associated with the connection
     * so that access to the CIHM can be lock free for fast path work.
     * Can't access the CIHM from this thread without adding locking.
     */
    final Connection c = (Connection) result.clientData;
    final ListenableFutureTask<?> ft = ListenableFutureTask.create(new Runnable() {
        @Override
        public void run() {
            if (result.errorMsg == null) {
                if (result instanceof AdHocPlannedStmtBatch) {
                    final AdHocPlannedStmtBatch plannedStmtBatch = (AdHocPlannedStmtBatch) result;
                    // assume all stmts have the same catalog version
                    if ((plannedStmtBatch.getPlannedStatementCount() > 0) && (plannedStmtBatch
                            .getPlannedStatement(0).catalogVersion != m_catalogContext.get().catalogVersion)) {

                        /* The adhoc planner learns of catalog updates after the EE and the
                           rest of the system. If the adhoc sql was planned against an
                           obsolete catalog, re-plan. */
                        LocalObjectMessage work = new LocalObjectMessage(new AdHocPlannerWork(m_siteId, false,
                                plannedStmtBatch.clientHandle, plannedStmtBatch.connectionId,
                                plannedStmtBatch.hostname, plannedStmtBatch.adminConnection,
                                plannedStmtBatch.clientData, plannedStmtBatch.sqlBatchText,
                                plannedStmtBatch.getSQLStatements(), plannedStmtBatch.partitionParam, null,
                                false, true, m_adhocCompletionHandler));

                        m_mailbox.send(m_plannerSiteId, work);
                    } else {
                        createAdHocTransaction(plannedStmtBatch);
                    }
                } else if (result instanceof CatalogChangeResult) {
                    final CatalogChangeResult changeResult = (CatalogChangeResult) result;
                    // create the execution site task
                    StoredProcedureInvocation task = new StoredProcedureInvocation();
                    task.procName = "@UpdateApplicationCatalog";
                    task.setParams(changeResult.encodedDiffCommands, changeResult.catalogBytes,
                            changeResult.expectedCatalogVersion, changeResult.deploymentString,
                            changeResult.deploymentCRC);
                    task.clientHandle = changeResult.clientHandle;

                    /*
                     * Round trip the invocation to initialize it for command logging
                     */
                    FastSerializer fs = new FastSerializer();
                    try {
                        fs.writeObject(task);
                        ByteBuffer source = fs.getBuffer();
                        ByteBuffer copy = ByteBuffer.allocate(source.remaining());
                        copy.put(source);
                        copy.flip();
                        FastDeserializer fds = new FastDeserializer(copy);
                        task = new StoredProcedureInvocation();
                        task.readExternal(fds);
                    } catch (Exception e) {
                        hostLog.fatal(e);
                        VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
                    }

                    // initiate the transaction. These hard-coded values from catalog
                    // procedure are horrible, horrible, horrible.
                    createTransaction(changeResult.connectionId, changeResult.hostname,
                            changeResult.adminConnection, task, false, true, true, m_allPartitions,
                            m_allPartitions.length, changeResult.clientData, 0, EstTime.currentTimeMillis(),
                            false);
                } else {
                    throw new RuntimeException(
                            "Should not be able to get here (ClientInterface.checkForFinishedCompilerWork())");
                }
            } else {
                ClientResponseImpl errorResponse = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                        new VoltTable[0], result.errorMsg, result.clientHandle);
                ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
                buf.putInt(buf.capacity() - 4);
                errorResponse.flattenToBuffer(buf);
                buf.flip();
                c.writeStream().enqueue(buf);
            }
        }
    }, null);
    if (c != null) {
        c.queueTask(ft);
    }

    /*
     * Add error handling in case of an unexpected exception
     */
    ft.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                ft.get();
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                pw.flush();
                ClientResponseImpl errorResponse = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                        new VoltTable[0], result.errorMsg, result.clientHandle);
                ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
                buf.putInt(buf.capacity() - 4);
                errorResponse.flattenToBuffer(buf);
                buf.flip();
                c.writeStream().enqueue(buf);
            }
        }
    }, MoreExecutors.sameThreadExecutor());

    //Return the future task for test code
    return ft;
}