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(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:org.jactr.eclipse.runtime.launching.norm.AbstractACTRLaunchConfiguration.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {
    _session = null;/*  ww w  . j  a  v a  2 s. c  o m*/
    boolean shouldCleanUp = false;

    verify(configuration);

    SessionTracker tracker = getSessionTracker();
    if (tracker != null && tracker.hasActiveSessions()) {
        /*
         * prompt the user. should we defer?
         */
        FutureTask<Integer> response = new FutureTask<Integer>(new Callable<Integer>() {
            public Integer call() {
                String[] buttons = new String[] { "Cancel", "Run Now", "Run Later" };
                MessageDialog prompt = new MessageDialog(Display.getDefault().getActiveShell(), "Run when?",
                        null, "A session is already running. Run now or queue for later?",
                        MessageDialog.QUESTION, buttons, 2);

                return prompt.open();
            }
        });

        Display.getDefault().syncExec(response);

        try {
            switch (response.get()) {
            case 0:
                return;
            case 2:
                tracker.addDeferredLaunch(configuration, mode);
                return;
            }
        } catch (Exception e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, RuntimePlugin.PLUGIN_ID, 0, "Could not launch runtime", e));
        }
    }

    ILaunchConfigurationWorkingCopy workingCopy = null;
    try {

        /*
         * this is needed to correctly resolve the data and config directories..
         */
        ACTRProjectVariableResolver.setCurrentProject(ACTRLaunchConfigurationUtils.getProject(configuration));

        /*
         * we create the reference to the configuration file, which is needed in
         * order to set working directories and commandline parameters for the run
         */
        IFile envFile = EnvironmentConfigurator.createRuntimeEnvironmentFile(configuration, mode, monitor);

        workingCopy = createActualConfiguration(configuration, mode, envFile, monitor);

        _session = createSession(workingCopy, launch, mode, envFile, monitor);
    } catch (CoreException ce) {
        throw ce;
    }

    try {
        configuration = workingCopy.doSave();

        super.launch(configuration, mode, launch, monitor);

        shouldCleanUp = monitor.isCanceled();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Launched shouldCleanUp:" + shouldCleanUp);
    } catch (CoreException ce) {
        shouldCleanUp = true;
        throw ce;
    } finally {
        if (_session != null && shouldCleanUp)
            stopSession(_session);

        try {
            configuration.delete();
        } catch (CoreException ce) {
            CorePlugin.error("Could not delete temporary launch config", ce);
        }
    }
}

From source file:ubic.gemma.core.loader.expression.geo.GeoFamilyParser.java

@Override
public void parse(InputStream is) throws IOException {
    if (is == null) {
        throw new IOException("Inputstream was null");
    }/*from www  .j  a v a  2  s  .c  o  m*/

    if (is.available() == 0) {
        throw new IOException("No bytes to read from the input stream.");
    }

    try (final BufferedReader dis = new BufferedReader(new InputStreamReader(is))) {

        GeoFamilyParser.log.debug("Parsing....");

        final ExecutorService executor = Executors.newSingleThreadExecutor();

        FutureTask<Exception> future = new FutureTask<>(new Callable<Exception>() {
            @Override
            public Exception call() {
                try {
                    GeoFamilyParser.this.doParse(dis);
                    dis.close();
                    return null;
                } catch (Exception e) {
                    GeoFamilyParser.log.error(e, e);
                    return e;
                }
            }
        });

        executor.execute(future);
        executor.shutdown();

        while (!future.isDone() && !future.isCancelled()) {
            try {
                TimeUnit.SECONDS.sleep(5L);
            } catch (InterruptedException e) {
                // probably cancelled.
                dis.close();
                return;
            }
            GeoFamilyParser.log.info(parsedLines + " lines parsed.");
        }

        try {
            Exception e = future.get();
            if (e != null) {
                GeoFamilyParser.log.error(e.getMessage());
                throw new RuntimeException(e.getCause());
            }
        } catch (ExecutionException e) {
            throw new RuntimeException("Parse failed", e.getCause());
        } catch (java.util.concurrent.CancellationException e) {
            throw new RuntimeException("Parse was cancelled", e.getCause());
        } catch (InterruptedException e) {
            throw new RuntimeException("Parse was interrupted", e.getCause());
        }

        executor.shutdownNow();

        assert future.isDone();
        // assert executor.isTerminated();

        GeoFamilyParser.log.info("Done parsing.");
    }
}

From source file:org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.java

public void invokeOneWay(MessageContext request) {
    if (log.isDebugEnabled()) {
        log.debug("Invoking service endpoint: " + serviceImplClass.getName());
        log.debug("Invocation pattern: one way");
    }//from   w  w  w.  j a v a2 s . co m

    initialize(request);

    OperationDescription operationDesc = Utils.getOperationDescription(request);

    Object[] methodInputParams = createRequestParameters(request);

    Method target = getJavaMethod(request, serviceImplClass);
    if (log.isDebugEnabled()) {
        // At this point, the OpDesc includes everything we know, including the actual method
        // on the service impl we will delegate to; it was set by getJavaMethod(...) above.
        log.debug("JavaBeanDispatcher about to invoke using OperationDesc: " + operationDesc.toString());
    }

    EndpointInvocationContext eic = (EndpointInvocationContext) request.getInvocationContext();
    ClassLoader cl = getContextClassLoader();

    AsyncInvocationWorker worker = new AsyncInvocationWorker(target, methodInputParams, cl, eic);
    FutureTask task = new FutureTask<AsyncInvocationWorker>(worker);

    ExecutorFactory ef = (ExecutorFactory) FactoryRegistry.getFactory(ExecutorFactory.class);
    Executor executor = ef.getExecutorInstance(ExecutorFactory.SERVER_EXECUTOR);

    // If the property has been set to disable thread switching, then we can 
    // do so by using a SingleThreadedExecutor instance to continue processing
    // work on the existing thread.
    Boolean disable = (Boolean) request.getProperty(ServerConstants.SERVER_DISABLE_THREAD_SWITCH);
    if (disable != null && disable.booleanValue()) {
        if (log.isDebugEnabled()) {
            log.debug("Server side thread switch disabled.  "
                    + "Setting Executor to the SingleThreadedExecutor.");
        }
        executor = new SingleThreadedExecutor();
    }

    executor.execute(task);
    return;
}

From source file:ddf.services.schematron.SchematronValidationService.java

private void updateValidators() throws SchematronInitializationException {
    validators.clear();//  www  .  j  ava  2  s  .  co  m
    for (String schematronFileName : schematronFileNames) {
        FutureTask<Templates> task = new FutureTask<Templates>(() -> {
            return compileSchematronRules(schematronFileName);
        });
        validators.add(task);
        pool.submit(task);
    }
}

From source file:org.nuxeo.runtime.jtajca.management.CanMonitorTransactions.java

@Test
@LogCaptureFeature.FilterWith(value = CanMonitorTransactions.LogRollbackTraceFilter.class)
public void logContainsRollbackTrace()
        throws InterruptedException, ExecutionException, NoLogCaptureFilterException {
    FutureTask<Boolean> task = new FutureTask<Boolean>(new TestLogRollbackTrace());
    executor.execute(task);//from   w ww .  ja  v a2s .co m
    assertThat(task.get(), is(true));
    logCaptureResults.assertHasEvent();
}

From source file:ubic.gemma.loader.util.fetcher.FtpArchiveFetcher.java

/**
 * @param newDir//  ww w.j  a va2  s.  c om
 * @param seekFile
 */
protected void unPack(final File toUnpack) {
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        @SuppressWarnings("synthetic-access")
        public Boolean call() {
            File extractedFile = new File(FileTools.chompExtension(toUnpack.getAbsolutePath()));
            /*
             * Decide if an existing file is plausibly usable. Err on the side of caution.
             */
            if (allowUseExisting && extractedFile.canRead() && extractedFile.length() >= toUnpack.length()
                    && !FileUtils.isFileNewer(toUnpack, extractedFile)) {
                log.warn("Expanded file exists, skipping re-expansion: " + extractedFile);
                return Boolean.TRUE;
            }

            if (expander != null) {
                expander.setSrc(toUnpack);
                expander.setDest(toUnpack.getParentFile());
                expander.perform();
            } else if (toUnpack.getAbsolutePath().toLowerCase().endsWith("zip")) {
                try {
                    FileTools.unZipFiles(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            } else { // gzip.
                try {
                    FileTools.unGzipFile(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return Boolean.TRUE;
        }

    });
    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(future);
    executor.shutdown();

    StopWatch s = new StopWatch();
    s.start();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            future.cancel(true);
            return;
        }
        log.info("Unpacking archive ... " + Math.floor(s.getTime() / 1000.0) + " seconds elapsed");
    }
}

From source file:org.apache.hadoop.corona.TestMiniCoronaRunJob.java

private FutureTask<Boolean> submitSleepJobFutureTask(final JobConf conf) {
    FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() throws IOException {
            try {
                runSleepJob(conf, 1, 1);
            } catch (Exception e) {
                LOG.error("Sleep Job Failed", e);
                return false;
            }//from   w  w  w .  j a v  a2s .co  m
            return true;
        }
    });
    new Thread(task).start();
    return task;
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Sets a username for a user in the server
 *
 * @param username The username to be set
 * @return <b>true</b> if the request passes, <b>false</b> if it doesn't
 * @throws IOException/*from w  ww . jav  a  2s .co  m*/
 * @throws ExecutionException
 * @throws InterruptedException
 */
public boolean setUsername(final String username) throws IOException, ExecutionException, InterruptedException {
    Callable<Boolean> booleanCallable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            HttpURLConnection httpURLConnection;
            URL setUsernameUrl = new URL(
                    "http://www.balticapp.fi/lukeA/user/set-username?username=" + username);
            httpURLConnection = (HttpURLConnection) setUsernameUrl.openConnection();
            httpURLConnection.setRequestProperty(context.getString(R.string.authorization),
                    context.getString(R.string.bearer) + SessionSingleton.getInstance().getIdToken());
            httpURLConnection.setRequestProperty(context.getString(R.string.acstoken),
                    SessionSingleton.getInstance().getAccessToken());

            return httpURLConnection.getResponseCode() == 200;
        }
    };
    FutureTask<Boolean> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread t = new Thread(booleanFutureTask);
    t.start();
    return booleanFutureTask.get();
}

From source file:com.test.test.ClientServerTest.java

@Test
public void testMutliThreaded() throws Exception {

    // Number of threads
    final int size = 10;

    LOG.debug("clientSimple1:" + clientSimple);

    IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
    LOG.debug("proxyService:" + proxyService);

    List<ClientCallable> clientCallableList = new ArrayList<ClientCallable>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallable(proxyService, i));
    }/*from   w  w  w.  j av  a2s  .co  m*/

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallable clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");
}

From source file:de.elomagic.mag.AbstractTest.java

protected Future<Boolean> createPutServletFuture(ServletMock putServlet) {

    ExecutorService executor = Executors.newFixedThreadPool(2);

    FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
        while (!putServlet.received) {
            Thread.sleep(100);//from   w  ww .  j  a  v  a 2  s.c o  m
        }

        return putServlet.received;
    });

    executor.execute(futureTask);

    return futureTask;
}