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:com.googlecode.aviator.AviatorEvaluator.java

/**
 * Compile a text expression to Expression object
 *
 * @param expression/*from ww  w .j a  v  a  2  s  .c o m*/
 *            text expression
 * @param cached
 *            Whether to cache the compiled result,make true to cache it.
 * @return
 */
public static Expression compile(final String expression, boolean cached) {
    if (expression == null || expression.trim().length() == 0)
        throw new CompileExpressionErrorException("Blank expression");

    if (cached) {
        FutureTask<Expression> task = cacheExpressions.get(expression);
        if (task != null)
            return getCompiledExpression(expression, task);
        task = new FutureTask<Expression>(new Callable<Expression>() {
            @Override
            public Expression call() throws Exception {
                return innerCompile(expression);
            }

        });
        FutureTask<Expression> existedTask = cacheExpressions.putIfAbsent(expression, task);
        if (existedTask == null) {
            existedTask = task;
            existedTask.run();
        }
        return getCompiledExpression(expression, existedTask);

    } else
        return innerCompile(expression);

}

From source file:com.alibaba.napoli.metamorphosis.client.extension.producer.LocalMessageStorageManager.java

private Store getOrCreateStore0(final String topic, final Partition partition) {
    final String name = this.generateKey(topic, partition);
    FutureTask<Store> task = this.topicStoreMap.get(name);
    if (task != null) {
        return this.getStore(name, task);
    } else {//from w  w w.  jav  a2s .  c o m
        task = new FutureTask<Store>(new Callable<Store>() {

            @Override
            public Store call() throws Exception {
                final File file = new File(
                        LocalMessageStorageManager.this.META_LOCALMESSAGE_PATH + File.separator + name);
                if (!file.exists()) {
                    file.mkdir();
                }
                return this.newStore(name);
            }

            private Store newStore(final String name) throws IOException {
                return LocalMessageStorageManager.this.newStore(name);
            }

        });
        FutureTask<Store> existsTask = this.topicStoreMap.putIfAbsent(name, task);
        if (existsTask == null) {
            task.run();
            existsTask = task;
        }
        return this.getStore(name, existsTask);
    }
}

From source file:com.googlecode.icegem.cacheutils.regioncomparator.CompareTool.java

public void execute(String[] args, boolean debugEnabled, boolean quiet) {
    AdminDistributedSystem adminDs = AdminDistributedSystemFactory
            .getDistributedSystem(AdminDistributedSystemFactory.defineDistributedSystem());
    adminDs.connect();/*from   w ww.  j  av  a2 s  .  c  o  m*/

    parseCommandLineArguments(args);

    List<Pool> poolList = new ArrayList<Pool>();
    if (serversOption != null && serversOption.length() > 0)
        for (String serverOption : serversOption.split(",")) {
            String serverHost = serverOption.substring(0, serverOption.indexOf("["));
            String serverPort = serverOption.substring(serverOption.indexOf("[") + 1,
                    serverOption.indexOf("]"));
            poolList.add(PoolManager.createFactory().addServer(serverHost, Integer.parseInt(serverPort))
                    .create("poolTo" + serverHost + serverPort));
        }
    if (locatorsProperties != null && !locatorsProperties.isEmpty())
        for (Object poolOption : locatorsProperties.keySet()) {
            String locator = (String) locatorsProperties.get(poolOption);
            String serverHost = locator.substring(0, locator.indexOf("["));
            String serverPort = locator.substring(locator.indexOf("[") + 1, locator.indexOf("]"));
            poolList.add(PoolManager.createFactory().addLocator(serverHost, Integer.parseInt(serverPort)) //todo: check when we have two identical locators options: exception a pool name already exist
                    .create("poolTo" + serverHost + serverPort));
        }

    //todo: insert checking that each cluster contains region and one's type is equal (Partitioned, Replicated)

    boolean partitioned = false; //todo: insert CLI usage  + throw exception if real region has another type

    List<ServerLocation> serverFromPool = new ArrayList<ServerLocation>();
    List<Pool> emptyPools = new ArrayList<Pool>(); //contains pool with no available servers
    for (Pool pool : poolList) {
        List<ServerLocation> allServers = null;
        if (!pool.getLocators().isEmpty())
            allServers = ((AutoConnectionSourceImpl) ((PoolImpl) pool).getConnectionSource()).findAllServers(); //todo: ConnectionError if locator doesn't exist
        else if (!pool.getServers().isEmpty())
            allServers = Arrays
                    .asList((((PoolImpl) pool).getConnectionSource()).findServer(Collections.emptySet()));

        if (allServers != null)
            serverFromPool.addAll(allServers);
        else {
            log.info("not found servers on locator {}", pool);
            emptyPools.add(pool);
        }
    }
    poolList.removeAll(emptyPools);

    if (serverFromPool.size() == 0) {
        log.info("no servers available");
        return;
    }

    printServerLocationDetails(serverFromPool);

    //source for comparison //todo: if this node doesn't contain region! it's problem
    Pool sourcePool;
    if (!partitioned) {
        int randomServerLocation = new Random().nextInt(serverFromPool.size());
        sourcePool = PoolManager.createFactory()
                .addServer(serverFromPool.get(randomServerLocation).getHostName(),
                        serverFromPool.get(randomServerLocation).getPort())
                .create("target");
    } else {
        sourcePool = poolList.get(0);
        poolList.remove(0);
    }

    FunctionService.registerFunction(new RegionInfoFunction());
    ResultCollector regionInfoResult = FunctionService.onServers(sourcePool).withArgs(regionName)
            .execute(new RegionInfoFunction());

    Map regionInfo = (HashMap) ((ArrayList) regionInfoResult.getResult()).get(0);
    System.out.println("region info: " + regionInfo);

    int totalNumBuckets = (Integer) regionInfo.get("totalNumBuckets");
    //log.debug("total keys' batch counts is ", totalNumBuckets);
    System.out.println("total keys' batch counts is " + totalNumBuckets);
    KeyExtractor keyExtractor = new KeyExtractor(regionName, sourcePool, partitioned, totalNumBuckets);

    Map<String, Map<String, Set>> clusterDifference = new HashMap<String, Map<String, Set>>(); //key: memeberId list: absent keys, diff values

    List<PoolResult> taskResults = new ArrayList<PoolResult>();
    List<Future<PoolResult>> collectTasks = new ArrayList<Future<PoolResult>>(poolList.size());
    ExecutorService executorService = Executors.newFixedThreadPool(poolList.size());
    while (keyExtractor.hasKeys()) {
        Set keys = keyExtractor.getNextKeysBatch();
        System.out.println("keys to check: " + keys);
        for (Pool nextPool : poolList)
            collectTasks.add(executorService.submit(new CollectorTask(keys, nextPool, regionName)));
        System.out.println("active tasks: " + collectTasks.size());
        try {
            //for (Future<ResultCollector> futureTask : collectTasks) {
            for (Future<PoolResult> futureTask : collectTasks) {
                taskResults.add(futureTask.get());
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } catch (ExecutionException ee) {
            ee.printStackTrace();
        }
        collectTasks.clear();

        System.out.println("compare contents..");
        //getting source contents
        Map sourceData = new HashMap();

        //getting source map
        FutureTask<PoolResult> ft = new FutureTask<PoolResult>(new CollectorTask(keys, sourcePool, regionName));
        ft.run();
        try {
            PoolResult rc = ft.get();
            List poolResult = (List) rc.getResultCollector().getResult();
            for (Object singleResult : poolResult) {
                sourceData.putAll((Map) ((HashMap) singleResult).get("map"));
            }
        } catch (Exception e) {
            throw new RuntimeException("error getting key-hash from pool: " + sourcePool, e);
        }
        //todo: aggregate members' data from one cluster

        System.out.println("source data is: " + sourceData);
        //for (ResultCollector taskResultFromPool : taskResults) {
        for (PoolResult taskResultFromPool : taskResults) {
            List poolResult = (ArrayList) taskResultFromPool.getResultCollector().getResult();
            if (!partitioned) {
                for (Object resultFromMember : poolResult) {
                    Map result = (HashMap) resultFromMember;
                    String memberId = (String) result.get("memberId");
                    if (regionInfo.get("id").equals(result.get("memberId"))) //for replicated region
                        continue;
                    Map<String, Set> aggregationInfo = compareAndAggregate(sourceData,
                            (HashMap) result.get("map"));
                    System.out.println("result of comparing is: " + aggregationInfo);
                    if (!clusterDifference.containsKey(memberId)) {
                        aggregationInfo.put("absentKeys", new HashSet());
                        clusterDifference.put(memberId, aggregationInfo);
                    } else {
                        Map<String, Set> difference = clusterDifference.get(memberId);
                        difference.get("absentKeys").addAll((Set) result.get("absentKeys"));
                        difference.get("diffValues").addAll(aggregationInfo.get("diffValues"));
                        clusterDifference.put(memberId, difference);
                    }
                }
            } else {
                Map targetData = new HashMap();
                Set absentKeysFromPool = new HashSet();

                //aggregate data from different members with partition region
                for (Object resultFromMember : poolResult) {
                    targetData.putAll((Map) ((HashMap) resultFromMember).get("map"));
                    absentKeysFromPool.addAll((Set) ((HashMap) resultFromMember).get("absentKeys"));
                }

                Map<String, Set> aggregationInfo = compareAndAggregate(sourceData, targetData);
                System.out.println("result of comparing is: " + aggregationInfo);
                String keyForPartitionRegionType = taskResultFromPool.getPool().toString();
                if (!clusterDifference.containsKey(keyForPartitionRegionType)) {
                    clusterDifference.put(keyForPartitionRegionType, aggregationInfo);
                } else {
                    Map<String, Set> difference = clusterDifference.get(keyForPartitionRegionType);
                    difference.get("absentKeys").addAll(aggregationInfo.get("absentKeys"));
                    difference.get("diffValues").addAll(aggregationInfo.get("diffValues"));
                    clusterDifference.put(keyForPartitionRegionType, difference);
                }
            }
        }

        taskResults.clear();
    }

    System.out.println("____________________________");
    System.out.println("difference: ");
    System.out.println(clusterDifference);
    executorService.shutdown();
    adminDs.disconnect();
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

@Override
public FutureTask<Message> receiveMessage(final String destinationId, final DestinationType type) {
    FutureTask<Message> futureTask = new FutureTask<Message>(new Callable<Message>() {
        @Override/*from w ww.j  av  a2  s  .c o  m*/
        public Message call() {
            return getMessage(destinationId, type);
        }
    });
    return futureTask;
}

From source file:org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig.java

@Override
protected void readConfig() {
    if (!isModelPopulated) {

        w.lock();/*  ww  w.  j a v a 2s  .  co  m*/
        if (this.isModelPopulated) {
            w.unlock();
            return;
        }

        try {
            if (this.configClass == null) {
                return;
            }

            IBeansProject beansProject = BeansModelUtils.getParentOfClass(this, IBeansProject.class);
            if (beansProject == null) {
                return;
            }

            final ClassLoader cl = JdtUtils.getClassLoader(beansProject.getProject(),
                    ApplicationContext.class.getClassLoader());

            if (cl.getResource(this.configClass.getFullyQualifiedName().replace('.', '/') + ".class") == null) {
                return;
            }

            Callable<Integer> loadBeanDefinitionOperation = new Callable<Integer>() {
                public Integer call() throws Exception {
                    // Obtain thread context classloader and override with the project classloader
                    ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
                    Thread.currentThread().setContextClassLoader(cl);

                    // Create special ReaderEventListener that essentially just passes through component definitions
                    ReaderEventListener eventListener = new BeansConfigPostProcessorReaderEventListener();
                    problemReporter = new BeansConfigProblemReporter();
                    beanNameGenerator = new UniqueBeanNameGenerator(BeansJavaConfig.this);
                    registry = new ScannedGenericBeanDefinitionSuppressingBeanDefinitionRegistry();

                    try {
                        registerAnnotationProcessors(eventListener);
                        registerBean(eventListener, cl);

                        IBeansConfigPostProcessor[] postProcessors = BeansConfigPostProcessorFactory
                                .createPostProcessor(ConfigurationClassPostProcessor.class.getName());
                        for (IBeansConfigPostProcessor postProcessor : postProcessors) {
                            executePostProcessor(postProcessor, eventListener);
                        }
                    } finally {
                        // Reset the context classloader
                        Thread.currentThread().setContextClassLoader(threadClassLoader);
                        LogFactory.release(cl); //Otherwise permgen leak?
                    }
                    return 0;
                }
            };

            FutureTask<Integer> task = new FutureTask<Integer>(loadBeanDefinitionOperation);
            BeansCorePlugin.getExecutorService().submit(task);
            task.get(BeansCorePlugin.getDefault().getPreferenceStore()
                    .getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID), TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR,
                    "Loading of configuration '" + this.configClass.getFullyQualifiedName()
                            + "' took more than "
                            + BeansCorePlugin.getDefault().getPreferenceStore()
                                    .getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID)
                            + "sec",
                    file, 1));
        } catch (Exception e) {
            problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR,
                    String.format("Error occured processing Java config '%s'. See Error Log for more details",
                            e.getCause().getMessage()),
                    getElementResource()));
            BeansCorePlugin.log(new Status(IStatus.INFO, BeansCorePlugin.PLUGIN_ID,
                    String.format("Error occured processing '%s'", this.configClass.getFullyQualifiedName()),
                    e.getCause()));
        } finally {
            // Prepare the internal cache of all children for faster access
            List<ISourceModelElement> allChildren = new ArrayList<ISourceModelElement>(imports);
            allChildren.addAll(aliases.values());
            allChildren.addAll(components);
            allChildren.addAll(beans.values());
            Collections.sort(allChildren, new Comparator<ISourceModelElement>() {
                public int compare(ISourceModelElement element1, ISourceModelElement element2) {
                    return element1.getElementStartLine() - element2.getElementStartLine();
                }
            });
            this.children = allChildren.toArray(new IModelElement[allChildren.size()]);

            this.isModelPopulated = true;
            w.unlock();
        }

    }
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

@Override
public FutureTask<String> receiveString(final String destinationId, final DestinationType type) {
    FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
        @Override//  w w  w  .ja va2 s .  com
        public String call() {
            return getString(destinationId, type);
        }
    });
    return futureTask;
}

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

public void invokeAsync(MessageContext request, EndpointCallback callback) {
    if (log.isDebugEnabled()) {
        log.debug("Preparing to invoke javax.xml.ws.Provider based endpoint");
        log.debug("Invocation pattern: two way, async");
    }//from   ww w  . j  a  v  a 2  s  .  c  om

    initialize(request);

    providerInstance = getProviderInstance();

    Object param = createRequestParameters(request);

    if (log.isDebugEnabled()) {
        Class providerType = getProviderType();
        final Object input = providerType.cast(param);
        log.debug("Invoking Provider<" + providerType.getName() + ">");
        if (input != null) {
            log.debug("Parameter type: " + input.getClass().getName());
        } else {
            log.debug("Parameter is NULL");
        }
    }

    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();
    }

    Method m = getJavaMethod();
    Object[] params = new Object[] { param };

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

    AsyncInvocationWorker worker = new AsyncInvocationWorker(m, params, cl, eic);
    FutureTask task = new FutureTask<AsyncInvocationWorker>(worker);
    executor.execute(task);

    return;
}

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

/**
 * Fetches user data from the backend based on given userId
 *
 * @param userId The ID of the user whose data is fetched
 * @return {@link UserFromServer} object containing the user data
 * @throws ExecutionException//from   www.  jav  a2s  .co  m
 * @throws InterruptedException
 */
public UserFromServer getUserFromUserId(final String userId) throws ExecutionException, InterruptedException {
    Callable<UserFromServer> userFromServerCallable = new Callable<UserFromServer>() {
        @Override
        public UserFromServer call() throws Exception {
            String jsonString;
            jsonString = getMethod("http://www.balticapp.fi/lukeA/user?id=" + userId);

            if (!TextUtils.isEmpty(jsonString)) {
                final JSONObject jsonObject = new JSONObject(jsonString);
                return LukeUtils.parseUserFromJsonObject(jsonObject);
            } else {
                return null;
            }
        }
    };
    FutureTask<UserFromServer> userFromServerFutureTask = new FutureTask<>(userFromServerCallable);
    Thread t = new Thread(userFromServerFutureTask);
    t.start();
    return userFromServerFutureTask.get();

}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

@Override
public FutureTask<byte[]> receiveByteArray(final String destinationId, final DestinationType type) {
    FutureTask<byte[]> futureTask = new FutureTask<byte[]>(new Callable<byte[]>() {
        @Override//from   w w  w . jav a2s. com
        public byte[] call() {
            return getByteArray(destinationId, type);
        }
    });
    return futureTask;
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

@Override
public FutureTask<Serializable> receiveSerializable(final String destinationId, final DestinationType type) {
    FutureTask<Serializable> futureTask = new FutureTask<Serializable>(new Callable<Serializable>() {
        @Override/*from   w ww.j a v  a  2 s  .co  m*/
        public Serializable call() {
            return getSerializable(destinationId, type);
        }
    });
    return futureTask;
}