Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:com.carmatech.maven.model.ParallelMerger.java

private List<Future<PropertiesConfiguration>> parallelToProperties(final List<File> sourceFiles) {
    final List<Future<PropertiesConfiguration>> futures = Lists
            .newArrayListWithExpectedSize(sourceFiles.size());
    for (final File sourceFile : sourceFiles) {
        futures.add(threadPool.submit(new Callable<PropertiesConfiguration>() {
            @Override//  ww  w  .  j  ava  2s  .c o m
            public PropertiesConfiguration call() throws Exception {
                return toProperties(sourceFile);
            }
        }));
    }
    return futures;
}

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   ww  w  .  j a  v  a2 s. 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.netflix.dyno.connectionpool.impl.lb.CircularListTest.java

@Test
public void testSingleThreadWithElementAdd() throws Exception {

    final AtomicBoolean stop = new AtomicBoolean(false);

    Future<Map<Integer, Integer>> future = threadPool.submit(new Callable<Map<Integer, Integer>>() {

        @Override//www  . j  av a 2 s  . c o  m
        public Map<Integer, Integer> call() throws Exception {

            TestWorker worker = new TestWorker();

            while (!stop.get()) {
                worker.process();
            }

            return worker.map;
        }
    });

    Thread.sleep(500);

    List<Integer> newList = new ArrayList<Integer>();
    newList.addAll(iList);
    for (int i = 10; i < 15; i++) {
        newList.add(i);
    }

    cList.swapWithList(newList);

    Thread.sleep(100);

    stop.set(true);

    Map<Integer, Integer> result = future.get();

    Map<Integer, Integer> subMap = CollectionUtils.filterKeys(result, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return input != null && input < 10;
        }
    });

    List<Integer> list = new ArrayList<Integer>(subMap.values());
    checkValues(list);

    subMap = CollectionUtils.difference(result, subMap).entriesOnlyOnLeft();
    list = new ArrayList<Integer>(subMap.values());
    checkValues(list);
}

From source file:com.parse.FileObjectStore.java

@Override
public Task<Void> setAsync(final T object) {
    return Task.call(new Callable<Void>() {
        @Override/*from w  w w  .  ja  va2s .  c  om*/
        public Void call() throws Exception {
            saveToDisk(coder, object, file);
            //TODO (grantland): check to see if this failed? We currently don't for legacy reasons.
            return null;
        }
    }, ParseExecutors.io());
}

From source file:at.ac.univie.isc.asio.metadata.AtosMetadataRepository.java

/**
 * Find metadata on the datasets with given {@code localID}.
 *
 * @param localIdentifier identifier of dataset
 * @return metadata on target dataset if present
 *//*from   ww  w .  ja  v a 2 s  .c  o  m*/
public Observable<AtosDataset> findByLocalId(final String localIdentifier) {
    return checkedRequest(new Callable<List<AtosResourceMetadata>>() {
        @Override
        public List<AtosResourceMetadata> call() throws Exception {
            final AtosResourceMetadataList resources = endpoint.path("/metadata/facets/Dataset/localID")
                    .queryParam("value", localIdentifier).request(MediaType.APPLICATION_XML_TYPE)
                    .get(AtosResourceMetadataList.class);
            return resources.getResourceMetadata();
        }
    }).flatMap(new Func1<List<AtosResourceMetadata>, Observable<AtosResourceMetadata>>() {
        @Override
        public Observable<AtosResourceMetadata> call(final List<AtosResourceMetadata> resourceList) {
            return Observable.from(resourceList);
        }
    }).map(new Func1<AtosResourceMetadata, AtosDataset>() {
        @Override
        public AtosDataset call(final AtosResourceMetadata resource) {
            return resource.getDataset();
        }
    }).filter(new Func1<AtosDataset, Boolean>() {
        @Override
        public Boolean call(final AtosDataset atosDataset) {
            return atosDataset != null;
        }
    });
}

From source file:net.bhira.sample.api.controller.CompanyController.java

/**
 * Fetch all the companies in the system. It will return a light weight version of
 * {@link net.bhira.sample.model.Company} model without the address and contactInfo objects.
 * /*from w  w  w  .  j av a2s.  c  om*/
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Company} instances as JSON.
 */
@RequestMapping(value = "/company", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getAll(HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET company/");
                List<Company> list = companyService.loadAll();
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET company/ count = {}", count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading companies. {}", body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.PresentationDaoImplTest.java

@Test
public void testDelete() {
    this.execute(new Callable<Object>() {
        @Override/*from w  w  w.j  a  v  a  2s .c  o  m*/
        public Object call() {
            final BlackboardPresentationResponse response = new BlackboardPresentationResponse();
            response.setCreatorId("test@example.com");
            response.setDescription("super sweet media");
            response.setPresentationId(183838);
            response.setSize(1024);

            final Presentation pres = dao.createPresentation(response, "aliens_exist.pdf");
            assertNotNull(pres);

            dao.deletePresentation(pres);

            Presentation shouldBeNull = dao.getPresentationByBlackboardId(pres.getBbPresentationId());
            assertNull(shouldBeNull);
            return null;
        }
    });
}

From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketConnector.java

public Future<DragoonSession> connect(final SocketAddress address, final MessageHandler messageHandler) {
    if (address == null) {
        throw new IllegalArgumentException("address is null");
    }//from ww w  . j  a v  a 2s  . c  o  m

    if (!(address instanceof InetSocketAddress)) {
        throw new IllegalArgumentException("address must be VmPipeAddress.");
    }

    final InetSocketAddress inetSocketAddress = (InetSocketAddress) address;

    FutureTask<DragoonSession> task = new FutureTask<DragoonSession>(new Callable<DragoonSession>() {

        public DragoonSession call() throws Exception {
            connectCount.incrementAndGet();
            if (LOG.isInfoEnabled()) {
                LOG.info("CONNECT TO " + inetSocketAddress);
            }

            remoteAddress = inetSocketAddress.toString();
            Socket socket = new Socket(inetSocketAddress.getAddress(), inetSocketAddress.getPort());

            connectEstablishedCount.incrementAndGet();

            if (LOG.isInfoEnabled()) {
                LOG.info("CONNECTED TO " + inetSocketAddress);
            }

            SocketSessionImpl impl = new SocketSessionImpl(socket, receivedBytes, receivedMessages, sentBytes,
                    sentMessages);

            final long sessionId = generateSessionId();

            DragoonSession session = new DragoonSession(sessionId, new DragoonSessionConfig(messageHandler),
                    impl);
            impl.init(session);

            return session;
        }

    });
    connectorExecutor.submit(task);

    return task;
}

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;/*  w w w  . j  ava 2s.  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:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    PMF.runInServlet(new Callable<Void>() {
        @Override//from  w  w  w . ja va  2 s.c om
        public Void call() throws Exception {
            DocumentServlet.super.service(req, resp);
            return null;
        }
    });
}