Example usage for java.util.concurrent FutureTask run

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

Introduction

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

Prototype

public void run() 

Source Link

Usage

From source file:org.t2framework.commons.util.LazyLoadingReference.java

 public T get() throws IllegalStateException {
   while (true) {
      WeakReference<Future<T>> ref = reference.get();
      boolean valid = true;
      if (ref == null) {
         FutureTask<T> f = new FutureTask<T>(new Callable<T>() {
            @Override// w w  w .jav  a  2 s  .com
            public T call() throws Exception {
               return factory.create();
            }
         });
         ref = new WeakReference<Future<T>>(f);
         if (valid = reference.compareAndSet(null, ref)) {
            f.run();
         }
      }
      if (valid) {
         try {
            Future<T> f = ref.get();
            if (f != null) {
               return f.get();
            } else {
               reference.compareAndSet(ref, null);
            }
         } catch (CancellationException e) {
            reference.compareAndSet(ref, null);
         } catch (ExecutionException e) {
            throw new IllegalStateException(e.getCause());
         } catch (Exception e) {
            throw new IllegalStateException(e);
         }
      }
   }
}

From source file:pl.nask.hsn2.service.CachingTemplateRegistry.java

final String getTemplateUsingCache(final String templateName) throws ResourceException {
    Future<String> f = templates.get(templateName);
    if (f == null) {
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {

            @Override// w ww.  j  a  v a  2  s.c om
            public String call() throws ResourceException {
                return readFileAsString(templateName);
            }
        });
        f = templates.putIfAbsent(templateName, future);
        if (f == null) {
            f = future;
            future.run();
        }
    }

    try {
        return f.get();
    } catch (InterruptedException e) {
        throw new ResourceException("Interrupted while waiting for the resource", e);
    } catch (ExecutionException e) {
        throw new ResourceException("Exception while producing the resource", e);
    }
}

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  ww .ja  va2 s  . c o 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:com.taobao.common.tfs.comm.TfsClientFactory.java

public TfsClient get(Long targetId, final int connectionTimeout, final PacketStreamer pstreamer)
        throws TfsException {
    final Long key = targetId;
    if (clients.containsKey(key)) {
        try {//from   w ww  .j a  va 2s  .  c  o m
            return clients.get(key).get();
        } catch (Exception e) {
            removeClient(key);
            throw new TfsException("get tfs connection error,targetAddress is " + targetId, e);
        }
    } else {
        FutureTask<TfsClient> task = new FutureTask<TfsClient>(new Callable<TfsClient>() {
            public TfsClient call() throws Exception {
                return createClient(key, connectionTimeout, pstreamer);
            }
        });
        FutureTask<TfsClient> existTask = clients.putIfAbsent(key, task);
        if (existTask == null) {
            existTask = task;
            task.run();
        }
        try {
            return existTask.get();
        } catch (Exception e) {
            removeClient(key);
            throw new TfsException("get tfs connection error,targetAddress is " + targetId, e);
        }
    }
}

From source file:com.taobao.tair.comm.TairClientFactory.java

public TairClient get(final String targetUrl, final int connectionTimeout, final PacketStreamer pstreamer)
        throws TairClientException {
    String key = targetUrl;/*from w w  w.j  ava2s  .c o  m*/
    FutureTask<TairClient> existTask = null;
    existTask = clients.get(key);

    if (existTask == null) {
        FutureTask<TairClient> task = new FutureTask<TairClient>(new Callable<TairClient>() {
            public TairClient call() throws Exception {
                return createClient(targetUrl, connectionTimeout, pstreamer);
            }
        });
        existTask = clients.putIfAbsent(key, task);
        if (existTask == null) {
            existTask = task;
            task.run();
        }
    }

    try {
        return existTask.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (CancellationException e) {
        // cancel exception may be lost connection fd, but we never called task.cancel();
        clients.remove(key);
        throw e;
    } catch (ExecutionException e) {
        // create socket failed, so need not close
        clients.remove(key);
        throw new TairClientException("create socket exception, target address is " + targetUrl, e);
    }
}

From source file:org.apache.qpid.disttest.client.MessageProvider.java

protected String getMessagePayload(final CreateProducerCommand command) {
    FutureTask<String> createTextFuture = new FutureTask<String>(new Callable<String>() {
        @Override/* w w  w  .j  av  a  2 s.c o m*/
        public String call() throws Exception {
            return StringUtils.repeat("a", command.getMessageSize());
        }
    });

    Future<String> future = _payloads.putIfAbsent(command.getMessageSize(), createTextFuture);
    if (future == null) {
        createTextFuture.run();
        future = createTextFuture;
    }
    String payload = null;
    try {
        payload = future.get();
    } catch (Exception e) {
        throw new DistributedTestException("Unable to create message payload :" + e.getMessage(), e);
    }
    return payload;
}

From source file:com.alibaba.dragoon.common.protocol.DragoonSession.java

public Future<ResponseMessage> sendMessage(RequestMessage message) {
    int frameId = nextSequence();
    message.setFrameId(frameId);/* w ww .  j a v  a  2 s  .c  om*/

    ResponseMessageTask task = new ResponseMessageTask();
    taskMap.put(frameId, task);

    FutureTask<ResponseMessage> future = new FutureTask<ResponseMessage>(task);
    futureMap.put(frameId, future);

    try {
        sentMessageCount.incrementAndGet();
        impl.sendMessageDirect(message);
    } catch (IOException e) {
        task.setError(e);
        future.run();
    }

    return future;
}

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   ww w.  ja v  a  2  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:com.linuxbox.enkive.message.search.AbstractMessageSearchService.java

@Override
@Async/* www . ja  v a 2  s.c o  m*/
public Future<SearchResult> searchAsync(final Map<String, String> fields) throws MessageSearchException {
    FutureTask<SearchResult> searchFuture = new FutureTask<SearchResult>(new Callable<SearchResult>() {
        public SearchResult call() {
            SearchResult result = null;
            try {
                result = search(fields);
            } catch (MessageSearchException e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn("Error Searching for message", e);
            }
            return result;
        }
    });
    searchFuture.run();
    return searchFuture;
}

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;/*from www  . j  av  a 2  s .  c  o 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();
        }

    }
}