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.gytheio.messaging.camel.CamelRequestReplyMessageProducer.java

@Override
public Future<RP> asyncRequest(RQ request) {
    send(request);//from  ww w . j a v a  2 s. co  m
    pendingRequests.put(request.getRequestId(), null);

    FutureTask<RP> future = new FutureTask<>(new ReplyCallable(request.getRequestId()));
    executorService.execute(future);
    return future;
}

From source file:org.apache.cxf.dosgi.systests.common.AbstractListenerHookServiceListenerTest.java

public void testBasicInvocation() throws Exception {

    Thread.currentThread().setContextClassLoader(ClientProxyFactoryBean.class.getClassLoader());

    Server server1 = null;//w w w  . j av  a  2 s.  co m
    Server server2 = null;
    ServiceTracker tracker = null;
    try {
        server1 = startServer(ADDRESS1, GreeterService.class, new GreeterServiceImpl());

        server2 = startServer(ADDRESS2, GreeterService.class, new GreeterServiceImpl());
        tracker = new ServiceTracker(bundleContext, GreeterService.class.getName(), null) {
            @Override
            public Object addingService(final ServiceReference reference) {
                Object result = super.addingService(reference);

                FutureTask<Map<GreetingPhrase, String>> future = new FutureTask<Map<GreetingPhrase, String>>(
                        new Callable<Map<GreetingPhrase, String>>() {
                            public Map<GreetingPhrase, String> call() {
                                return useService(reference);
                            }
                        });
                future.run();
                synchronized (mutex1) {
                    synchronized (mutex2) {
                        if (task1 == null) {
                            task1 = future;
                            mutex1.notify();
                        } else if (task2 == null) {
                            task2 = future;
                            mutex2.notify();
                        }
                    }
                }
                return result;
            }
        };
        tracker.open();
        // sleep for a bit
        Thread.sleep(2000);

        installDswIfNeeded();

        verifyGreeterResponse(task1, mutex1);
        verifyGreeterResponse(task2, mutex2);
    } finally {
        if (tracker != null) {
            tracker.close();
        }

        if (server1 != null) {
            server1.getDestination().shutdown();
            server1.stop();
        }

        if (server2 != null) {
            server2.getDestination().shutdown();
            server2.stop();
        }

    }
}

From source file:plugin.chartboost.hasCachedMoreApps.java

/**
 * This method is called when the Lua function is called.
 * <p>//ww  w  . jav a 2  s. co  m
 * Warning! This method is not called on the main UI thread.
 * @param luaState Reference to the Lua state.
 *                 Needed to retrieve the Lua function's parameters and to return values back to Lua.
 * @return Returns the number of values to be returned by the Lua function.
 */
@Override
public int invoke(LuaState luaState) {
    try {
        // Corona Activity
        CoronaActivity coronaActivity = null;
        if (CoronaEnvironment.getCoronaActivity() != null) {
            coronaActivity = CoronaEnvironment.getCoronaActivity();
        }

        // The lua state
        final LuaState L = luaState;

        // See if the more apps page is cached
        FutureTask<Boolean> isCachedResult = new FutureTask<Boolean>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                // Is more apps cached?
                boolean result = false;

                // If the chartboost instance is valid - could be invalid by calling this method before init invokes
                if (chartboostHelper.chartboostInstance != null) {
                    result = chartboostHelper.chartboostInstance.hasCachedMoreApps();
                }
                // Push the result
                L.pushBoolean(result);
                // Return the result
                return result;
            }
        });

        // Run the activity on the uiThread
        if (coronaActivity != null) {
            coronaActivity.runOnUiThread(isCachedResult);
            // Get the value of isCached
            boolean returnValue = isCachedResult.get();
        }
    } catch (Exception ex) {
        // An exception will occur if given an invalid argument or no argument. Print the error.
        ex.printStackTrace();
    }

    return 1;
}

From source file:org.nuxeo.ecm.core.management.jtajca.CanMonitorTransactionsTest.java

@Test
public void isTotalRollbacksCorrect() throws InterruptedException, ExecutionException {
    assertThat(monitor.getActiveCount(), is(1L));
    FutureTask<Boolean> rollback = new FutureTask<Boolean>(new TestTotalRollbacks());
    executor.execute(rollback);/*from  w  w w.ja v  a2  s. c om*/
    assertThat(rollback.get(), is(true));
}

From source file:org.punksearch.util.RenewableMemoizer.java

private FutureTask<V> makeFutureTask(final A arg) {
    return new FutureTask<V>(makeCallable(arg));
}

From source file:com.ciphertool.genetics.algorithms.ConcurrentBasicGeneticAlgorithm.java

@Override
public int crossover(int initialPopulationSize) {
    if (this.population.size() < 2) {
        log.info(//from  w  ww .ja v a2s  .  co  m
                "Unable to perform crossover because there is only 1 individual in the population. Returning.");

        return 0;
    }

    long pairsToCrossover = Math.min((long) (initialPopulationSize * strategy.getCrossoverRate()),
            ((long) (this.population.size() / 2)));

    log.debug("Pairs to crossover: " + pairsToCrossover);

    Chromosome mom = null;
    Chromosome dad = null;
    int momIndex = -1;
    int dadIndex = -1;

    List<Chromosome> moms = new ArrayList<Chromosome>();
    List<Chromosome> dads = new ArrayList<Chromosome>();

    /*
     * We first remove all the parent Chromosomes since the children are
     * guaranteed to be at least as fit. This also prevents parents from
     * reproducing more than one time per generation.
     */
    for (int i = 0; i < pairsToCrossover; i++) {
        momIndex = this.population.selectIndex();
        moms.add(this.population.getIndividuals().get(momIndex));
        this.population.makeIneligibleForReproduction(momIndex);

        dadIndex = this.population.selectIndex();
        dads.add(this.population.getIndividuals().get(dadIndex));
        this.population.makeIneligibleForReproduction(dadIndex);
    }

    List<FutureTask<List<Chromosome>>> futureTasks = new ArrayList<FutureTask<List<Chromosome>>>();
    FutureTask<List<Chromosome>> futureTask = null;

    /*
     * Execute each crossover concurrently. Parents should produce two
     * children, but this is not necessarily always guaranteed.
     */
    for (int i = 0; i < pairsToCrossover; i++) {
        mom = moms.get(i);
        dad = dads.get(i);

        futureTask = new FutureTask<List<Chromosome>>(new CrossoverTask(mom, dad));
        futureTasks.add(futureTask);
        this.taskExecutor.execute(futureTask);
    }

    List<Chromosome> childrenToAdd = new ArrayList<Chromosome>();
    /*
     * Add the result of each FutureTask to the population since it
     * represents a new child Chromosome.
     */
    for (FutureTask<List<Chromosome>> future : futureTasks) {
        try {
            /*
             * Add children after all crossover operations are completed so
             * that children are not inadvertently breeding immediately
             * after birth.
             */
            childrenToAdd.addAll(future.get());
        } catch (InterruptedException ie) {
            log.error("Caught InterruptedException while waiting for CrossoverTask ", ie);
        } catch (ExecutionException ee) {
            log.error("Caught ExecutionException while waiting for CrossoverTask ", ee);
        }
    }

    for (Chromosome child : childrenToAdd) {
        this.population.addIndividualAsIneligible(child);
    }

    return (int) pairsToCrossover;
}

From source file:org.jactr.eclipse.runtime.launching.session.SessionTracker.java

protected void launchQueued(boolean queryFirst) {

    if (queryFirst) {
        /*//from w  ww.  j  av  a  2s.c  o  m
         * prompt the user. should we defer?
         */
        FutureTask<Integer> response = new FutureTask<Integer>(new Callable<Integer>() {
            public Integer call() {
                String[] buttons = new String[] { "Cancel All", "Run Queued" };
                MessageDialog prompt = new MessageDialog(Display.getDefault().getActiveShell(), "Runs queued",
                        null, "There are " + _queuedSessions.size() + " runs pending. Cancel them as well?",
                        MessageDialog.QUESTION, buttons, 1);
                return prompt.open();
            }
        });

        Display.getDefault().syncExec(response);

        try {
            if (response.get() == 0) {
                _queuedSessions.clear();
                return;
            }
        } catch (Exception e) {

        }
    }

    Object[] info = _queuedSessions.remove(0);
    ILaunchConfiguration configuration = (ILaunchConfiguration) info[0];
    String mode = (String) info[1];

    try {
        configuration.launch(mode, new NullProgressMonitor());
    } catch (CoreException e) {
        CorePlugin.error("Could not launch deferred execution " + configuration.getName(), e);
    }
}

From source file:plugin.chartboost.hasCachedInterstitial.java

/**
 * This method is called when the Lua function is called.
 * <p>/*from  www  . jav  a2  s  .c o m*/
 * Warning! This method is not called on the main UI thread.
 * @param luaState Reference to the Lua state.
 *                 Needed to retrieve the Lua function's parameters and to return values back to Lua.
 * @return Returns the number of values to be returned by the Lua function.
 */
@Override
public int invoke(LuaState luaState) {
    try {
        // The named location
        final String namedLocation = luaState.checkString(1);

        // Corona Activity
        CoronaActivity coronaActivity = null;
        if (CoronaEnvironment.getCoronaActivity() != null) {
            coronaActivity = CoronaEnvironment.getCoronaActivity();
        }

        // The lua state
        final LuaState L = luaState;

        // See if the more apps page is cached
        FutureTask<Boolean> isCachedResult = new FutureTask<Boolean>(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                // Is more apps cached?
                boolean result = false;

                // If the chartboost instance is valid - could be invalid by calling this method before init invokes
                if (chartboostHelper.chartboostInstance != null) {
                    // Check the result
                    if (namedLocation != null) {
                        result = chartboostHelper.chartboostInstance.hasCachedInterstitial(namedLocation);
                    } else {
                        result = chartboostHelper.chartboostInstance
                                .hasCachedInterstitial("DefaultInterstitial");
                    }
                }
                // Push the result
                L.pushBoolean(result);
                // Return the result
                return result;
            }
        });

        // Run the activity on the uiThread
        if (coronaActivity != null) {
            coronaActivity.runOnUiThread(isCachedResult);

            // Get the value of isCached
            boolean returnValue = isCachedResult.get();
        }
    } catch (Exception ex) {
        // An exception will occur if given an invalid argument or no argument. Print the error.
        ex.printStackTrace();
    }

    return 1;
}

From source file:org.apache.cxf.dosgi.systests.common.rest.AbstractListenerHookServiceListenerTest.java

public void testBasicInvocation() throws Exception {

    Thread.currentThread().setContextClassLoader(JAXRSClientFactoryBean.class.getClassLoader());
    bundleContext.registerService(new String[] { "javax.ws.rs.ext.MessageBodyReader" },
            new AegisElementProvider(), new Hashtable());
    Server server1 = null;//from w w w . jav a  2 s  .co  m
    Server server2 = null;
    ServiceTracker tracker = null;
    try {
        server1 = startServer(ADDRESS1, GreeterService.class, new GreeterServiceImpl());

        server2 = startServer(ADDRESS2, GreeterService.class, new GreeterServiceImpl());
        tracker = new ServiceTracker(bundleContext, GreeterService.class.getName(), null) {
            @Override
            public Object addingService(final ServiceReference reference) {
                Object result = super.addingService(reference);

                FutureTask<GreeterInfo> future = new FutureTask<GreeterInfo>(new Callable<GreeterInfo>() {
                    public GreeterInfo call() {
                        return useService(reference);
                    }
                });
                future.run();
                synchronized (mutex1) {
                    synchronized (mutex2) {
                        if (task1 == null) {
                            task1 = future;
                            mutex1.notify();
                        } else if (task2 == null) {
                            task2 = future;
                            mutex2.notify();
                        }
                    }
                }
                return result;
            }
        };
        tracker.open();
        // sleep for a bit
        Thread.sleep(2000);

        installDswIfNeeded();

        verifyGreeterResponse(task1, mutex1);
        verifyGreeterResponse(task2, mutex2);
    } finally {
        if (tracker != null) {
            tracker.close();
        }

        if (server1 != null) {
            server1.getDestination().shutdown();
            server1.stop();
        }

        if (server2 != null) {
            server2.getDestination().shutdown();
            server2.stop();
        }

    }
}

From source file:org.sakaiproject.tool.impl.SessionComponentRegressionTest.java

/**
 * Identical to {@link #testGetSessionReturnsSessionCreatedByStartSession()}
 * except that it tests the overload of <code>startSession()</code>
 * ({@link SessionComponent#startSession(String)}.
 * //from ww w  . ja  va 2 s . c om
 * @throws TimeoutException 
 * @throws ExecutionException 
 * @throws InterruptedException 
 */
public void testGetSessionAlwaysReturnsSessionStartedWithClientSpecifiedId()
        throws InterruptedException, ExecutionException, TimeoutException {
    final Session startedSession = sessionComponent.startSession("9876543210");
    assertSame(startedSession, sessionComponent.getSession(startedSession.getId()));
    assertSame(startedSession, sessionComponent.getSession(startedSession.getId())); // intentional duplicate
    // all threads should get the same Session obj for a given key
    FutureTask<Session> asynchGet = new FutureTask<Session>(new Callable<Session>() {
        public Session call() {
            return sessionComponent.getSession(startedSession.getId());
        }
    });
    new Thread(asynchGet).start();
    assertSame(startedSession, asynchGet.get(1, TimeUnit.SECONDS));
}