Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask FutureTask.

Prototype

public FutureTask(Runnable runnable, V result) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Runnable , and arrange that get will return the given result on successful completion.

Usage

From source file:org.eclipse.che.api.builder.internal.SourcesManagerImpl.java

@Override
public void getSources(BuildLogger logger, String workspace, String project, final String sourcesUrl,
        java.io.File workDir) throws IOException {
    // Directory for sources. Keep sources to avoid download whole project before build.
    // This directory is not permanent and may be removed at any time.
    final java.io.File srcDir = new java.io.File(directory, workspace + java.io.File.separatorChar + project);
    // Temporary directory where we copy sources before build.
    final String key = workspace + project;
    try {/*from   w  w w. j a va2 s. c o m*/
        synchronized (this) {
            while (key.equals(projectKeyHolder.get())) {
                wait();
            }
        }
    } catch (InterruptedException e) {
        LOG.error(e.getMessage(), e);
        Thread.currentThread().interrupt();
    }
    // Avoid multiple threads download source of the same project.
    Future<Void> future = tasks.get(key);
    final ValueHolder<IOException> errorHolder = new ValueHolder<>();
    if (future == null) {
        final FutureTask<Void> newFuture = new FutureTask<>(new Runnable() {
            @Override
            public void run() {
                try {
                    download(sourcesUrl, srcDir);
                } catch (IOException e) {
                    LOG.error(e.getMessage(), e);
                    errorHolder.set(e);
                }
            }
        }, null);
        future = tasks.putIfAbsent(key, newFuture);
        if (future == null) {
            future = newFuture;
            try {
                // Need a bit time before to publish sources download start message via websocket
                // as client may not have already subscribed to the channel so early in build task execution
                Thread.sleep(300);
            } catch (InterruptedException e) {
                LOG.error(e.getMessage(), e);
            }
            logger.writeLine("[INFO] Injecting source code into builder...");
            newFuture.run();
            logger.writeLine("[INFO] Source code injection finished"
                    + "\n[INFO] ------------------------------------------------------------------------");
        }
    }
    try {
        future.get(); // Block thread until download is completed.
        final IOException ioError = errorHolder.get();
        if (ioError != null) {
            throw ioError;
        }
        IoUtil.copy(srcDir, workDir, IoUtil.ANY_FILTER);
        for (SourceManagerListener listener : listeners) {
            listener.afterDownload(new SourceManagerEvent(workspace, project, sourcesUrl, workDir));
        }
        if (!srcDir.setLastModified(System.currentTimeMillis())) {
            LOG.error("Unable update modification date of {} ", srcDir);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        // Runnable does not throw checked exceptions.
        final Throwable cause = e.getCause();
        if (cause instanceof Error) {
            throw (Error) cause;
        } else {
            throw (RuntimeException) cause;
        }
    } finally {
        tasks.remove(key);
    }
}

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 * /*  www . j a va  2 s . co m*/
 * 
 * @param latch
 * @param jobId
 * @param argsFinalList
 * @param execution
 * @param isExecutionTracking
 * @return
 */
private FutureTask executeGraph(final CountDownLatch latch, final String jobId, final String[] argsFinalList,
        final HydrographService execution, final boolean isExecutionTracking) {
    logger.trace("Creating executor thread");

    return new FutureTask(new Runnable() {
        public void run() {
            try {
                logger.debug("Executing the job from execute graph");
                execution.executeGraph(argsFinalList);
                if (isExecutionTracking) {
                    latch.await();
                }

            } catch (Exception e) {
                logger.error("JOB FAILED :", e);
                if (isExecutionTracking) {
                    try {
                        latch.await();
                    } catch (InterruptedException e1) {
                        logger.error("job fail :", e1);
                    }
                }
                throw new RuntimeException(e);
            }
        }
    }, null);

}

From source file:com.netflix.nicobar.cassandra.CassandraArchiveRepositoryTest.java

@Test
@SuppressWarnings("unchecked")
public void testGetRows() throws Exception {
    EnumSet<Columns> columns = EnumSet.of(Columns.module_id, Columns.module_name);
    Rows<String, String> mockRows = mock(Rows.class);
    Row<String, String> row1 = mock(Row.class);
    Row<String, String> row2 = mock(Row.class);
    List<Row<String, String>> rowList = Arrays.asList(row1, row2);

    when(mockRows.iterator()).thenReturn(rowList.iterator());

    FutureTask<Rows<String, String>> future = new FutureTask<Rows<String, String>>(new Runnable() {
        @Override/*from w  ww.  j  ava  2  s. c  o  m*/
        public void run() {
        }
    }, mockRows);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(future);
    when(gateway.selectAsync(anyString())).thenReturn(future);

    repository.getRows(columns);
    List<String> selectList = new ArrayList<String>();
    for (int shardNum = 0; shardNum < config.getShardCount(); shardNum++) {
        selectList.add(repository.generateSelectByShardCql(columns, shardNum));
    }

    InOrder inOrder = inOrder(gateway);
    for (int shardNum = 0; shardNum < config.getShardCount(); shardNum++) {
        inOrder.verify(gateway).selectAsync(selectList.get(shardNum));
    }
}

From source file:com.googlecode.networklog.ExportDialog.java

public FutureTask showProgressDialog(final Context context) {
    FutureTask futureTask = new FutureTask(new Runnable() {
        public void run() {
            progressDialog = new ProgressDialog(context);
            progressDialog.setIndeterminate(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMax(progress_max);
            progressDialog.setCancelable(false);
            progressDialog.setTitle("");
            progressDialog.setMessage(context.getResources().getString(R.string.exporting_log));

            progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                    context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            canceled = true;
                        }//from   www .  j a  va 2  s .c o  m
                    });

            progressDialog.show();
            progressDialog.setProgress(progress);
        }
    }, null);

    NetworkLog.handler.post(futureTask);
    return futureTask;
}

From source file:org.smssecure.smssecure.contacts.ContactSelectionListAdapter.java

public void loadBitmap(String number, ImageView imageView) {
    if (cancelPotentialWork(number, imageView)) {
        final BitmapWorkerRunnable runnable = new BitmapWorkerRunnable(context, imageView, number,
                scaledPhotoSize);/*  w  ww . ja  v  a2  s .com*/
        final TaggedFutureTask<?> task = new TaggedFutureTask<Void>(runnable, null, number);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(task);

        imageView.setImageDrawable(asyncDrawable);
        if (!task.isCancelled())
            photoResolver.execute(new FutureTask<Void>(task, null));
    }
}

From source file:com.securecomcode.text.contacts.ContactSelectionListAdapter.java

public void loadBitmap(String number, ImageView imageView) {
    if (cancelPotentialWork(number, imageView)) {
        final BitmapWorkerRunnable runnable = new BitmapWorkerRunnable(context, imageView, defaultPhoto, number,
                scaledPhotoSize);//from   w  ww  . j  av  a2  s.  co m
        final TaggedFutureTask<?> task = new TaggedFutureTask<Void>(runnable, null, number);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(context.getResources(), defaultCroppedPhoto,
                task);

        imageView.setImageDrawable(asyncDrawable);
        if (!task.isCancelled())
            photoResolver.execute(new FutureTask<Void>(task, null));
    }
}

From source file:org.apache.cassandra.db.index.SecondaryIndex.java

/**
 * Builds the index using the data in the underlying CF, non blocking
 *
 *
 * @return A future object which the caller can block on (optional)
 *///from  w w  w . ja  v  a  2  s  . co m
public final Future<?> buildIndexAsync() {
    // if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done
    boolean allAreBuilt = true;
    for (ColumnDefinition cdef : columnDefs) {
        if (!SystemKeyspace.isIndexBuilt(baseCfs.keyspace.getName(),
                getNameForSystemKeyspace(cdef.name.bytes))) {
            allAreBuilt = false;
            break;
        }
    }

    if (allAreBuilt) {
        queryable = true;
        return null;
    }

    // If the base table is empty we can directly mark the index as built.
    if (baseCfs.isEmpty()) {
        setIndexBuilt();
        return null;
    }

    // build it asynchronously; addIndex gets called by CFS open and schema update, neither of which
    // we want to block for a long period.  (actual build is serialized on CompactionManager.)
    Runnable runnable = new Runnable() {
        public void run() {
            baseCfs.forceBlockingFlush();
            buildIndexBlocking();
        }
    };
    FutureTask<?> f = new FutureTask<Object>(runnable, null);

    new Thread(f, "Creating index: " + getIndexName()).start();
    return f;
}

From source file:io.selendroid.ServerInstrumentation.java

private void runSynchronouslyOnUiThread(Runnable action) {
    FutureTask<Void> uiTask = new FutureTask<Void>(action, null);
    mainThreadExecutor.execute(uiTask);/*from   w  ww . j a v a 2s.c  o  m*/
    try {
        uiTask.get();
    } catch (Exception e) {
        throw new AppCrashedException("Unhandled exception from application under test.", e);
    }
}

From source file:org.apache.cassandra.db.ColumnFamilyStore.java

public Future<?> addIndex(final ColumnDefinition info) {
    assert info.getIndexType() != null;

    // create the index CFS
    IPartitioner rowPartitioner = StorageService.getPartitioner();
    AbstractType columnComparator = (rowPartitioner instanceof OrderPreservingPartitioner
            || rowPartitioner instanceof ByteOrderedPartitioner) ? BytesType.instance
                    : new LocalByPartionerType(StorageService.getPartitioner());
    final CFMetaData indexedCfMetadata = CFMetaData.newIndexMetadata(metadata, info, columnComparator);
    ColumnFamilyStore indexedCfs = ColumnFamilyStore.createColumnFamilyStore(table, indexedCfMetadata.cfName,
            new LocalPartitioner(metadata.getColumn_metadata().get(info.name).getValidator()),
            indexedCfMetadata);/*from  w  ww . ja  v a2 s  . com*/

    // link in indexedColumns.  this means that writes will add new data to the index immediately,
    // so we don't have to lock everything while we do the build.  it's up to the operator to wait
    // until the index is actually built before using in queries.
    if (indexedColumns.putIfAbsent(info.name, indexedCfs) != null)
        return null;

    // if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done
    if (indexedCfs.isIndexBuilt())
        return null;

    // build it asynchronously; addIndex gets called by CFS open and schema update, neither of which
    // we want to block for a long period.  (actual build is serialized on CompactionManager.)
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                forceBlockingFlush();
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new AssertionError(e);
            }
            buildSecondaryIndexes(getSSTables(), FBUtilities.singleton(info.name));
            SystemTable.setIndexBuilt(table.name, indexedCfMetadata.cfName);
        }
    };
    FutureTask<?> f = new FutureTask<Object>(runnable, null);
    new Thread(f, "Create index " + indexedCfMetadata.cfName).start();
    return f;
}

From source file:org.cloudifysource.rest.controllers.DeploymentsController.java

/**
 * /*w w w .j  av  a2s  . c  o  m*/
 * @param appName
 *            The application name.
 * @param timeoutInMinutes
 *            The timeout in minutes.
 * @return uninstall response.
 * @throws RestErrorException .
 */
@RequestMapping(value = "/{appName}", method = RequestMethod.DELETE)
@PreAuthorize("isFullyAuthenticated()")
public UninstallApplicationResponse uninstallApplication(@PathVariable final String appName,
        @RequestParam(required = false, defaultValue = "15") final Integer timeoutInMinutes)
        throws RestErrorException {

    validateUninstallApplication(appName);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    // Check that Application exists
    final org.openspaces.admin.application.Application app = this.restConfig.getAdmin().getApplications()
            .waitFor(appName, 10, TimeUnit.SECONDS);

    final ProcessingUnit[] pus = app.getProcessingUnits().getProcessingUnits();

    if (pus.length > 0) {
        if (permissionEvaluator != null) {
            final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication);
            // all the application PUs are supposed to have the same auth-groups setting
            final String puAuthGroups = pus[0].getBeanLevelProperties().getContextProperties()
                    .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS);
            permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy");
        }
    }

    final StringBuilder sb = new StringBuilder();
    final List<ProcessingUnit> uninstallOrder = createUninstallOrder(pus, appName);
    final String deploymentId = uninstallOrder.get(0).getBeanLevelProperties().getContextProperties()
            .getProperty(CloudifyConstants.CONTEXT_PROPERTY_DEPLOYMENT_ID);
    // TODO: Add timeout.
    FutureTask<Boolean> undeployTask = null;
    logger.log(Level.INFO, "Starting to poll for" + appName + " uninstall lifecycle events.");
    if (uninstallOrder.size() > 0) {

        undeployTask = new FutureTask<Boolean>(new Runnable() {
            private final long startTime = System.currentTimeMillis();

            @Override
            public void run() {

                for (final ProcessingUnit processingUnit : uninstallOrder) {
                    if (permissionEvaluator != null) {
                        final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(
                                authentication);
                        final String puAuthGroups = processingUnit.getBeanLevelProperties()
                                .getContextProperties()
                                .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS);
                        permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy");
                    }

                    final long undeployTimeout = TimeUnit.MINUTES.toMillis(timeoutInMinutes)
                            - (System.currentTimeMillis() - startTime);
                    try {
                        // TODO: move this to constant
                        if (processingUnit.waitForManaged(WAIT_FOR_MANAGED_TIMEOUT_SECONDS,
                                TimeUnit.SECONDS) == null) {
                            logger.log(Level.WARNING, "Failed to locate GSM that is managing Processing Unit "
                                    + processingUnit.getName());
                        } else {
                            logger.log(Level.INFO, "Undeploying Processing Unit " + processingUnit.getName());
                            populateEventsCache(deploymentId, processingUnit);
                            processingUnit.undeployAndWait(undeployTimeout, TimeUnit.MILLISECONDS);
                            final String serviceName = ServiceUtils
                                    .getApplicationServiceName(processingUnit.getName(), appName);
                            logger.info(
                                    "Removing application service scope attributes for service " + serviceName);
                            deleteServiceAttributes(appName, serviceName);
                        }
                    } catch (final Exception e) {
                        final String msg = "Failed to undeploy processing unit: " + processingUnit.getName()
                                + " while uninstalling application " + appName
                                + ". Uninstall will continue, but service " + processingUnit.getName()
                                + " may remain in an unstable state";

                        logger.log(Level.SEVERE, msg, e);
                    }
                }
                DeploymentEvent undeployFinishedEvent = new DeploymentEvent();
                undeployFinishedEvent.setDescription(CloudifyConstants.UNDEPLOYED_SUCCESSFULLY_EVENT);
                eventsCache.add(new EventsCacheKey(deploymentId), undeployFinishedEvent);
                logger.log(Level.INFO, "Application " + appName + " undeployment complete");
            }
        }, Boolean.TRUE);

        ((InternalAdmin) this.restConfig.getAdmin()).scheduleAdminOperation(undeployTask);
    }

    final String errors = sb.toString();
    if (errors.length() == 0) {
        logger.info("Removing all application scope attributes for application " + appName);
        deleteApplicationScopeAttributes(appName);
        final UninstallApplicationResponse response = new UninstallApplicationResponse();
        response.setDeploymentID(deploymentId);
        return response;
    }
    throw new RestErrorException(errors);
}