Tag: callable

Java:带有Callables的ExecutorService:invokeAll()和future.get() – 结果是否正确?

我使用Java中的ExecutorService来调用带有invokeAll()线程。 之后,我使用future.get()获取结果集。 以我创建线程的相同顺序收到结果非常重要。 这是一个片段: try { final List threads = new ArrayList(); // create threads for (String name : collection) { final CallObject object = new CallObject(name); threads.add(object); } // start all Threads results = pool.invokeAll(threads, 3, TimeUnit.SECONDS); for (Future future : results) { try { // this method blocks until it receives the result, […]

如何在multithreading环境中更好地使用ExecutorService?

我需要创建一个库,在其中我将有同步和异步方法。 executeSynchronous() – 等到我有结果,返回结果。 executeAsynchronous() – 立即返回一个Future,如果需要,可以在其他事情完成后处理。 我的图书馆的核心逻辑 客户将使用我们的库,他们将通过传递DataKey构建器对象来调用它。 然后,我们将使用该DataKey对象构造一个URL,并通过执行它来对该URL进行HTTP客户端调用,然后在我们将响应作为JSON字符串返回之后,我们将通过创建将该JSON字符串发送回我们的客户DataResponse对象。 有些客户会调用executeSynchronous() ,有些可能会调用executeAsynchronous() ,这就是为什么我需要在我的库中单独提供两个方法。 接口: public interface Client { // for synchronous public DataResponse executeSynchronous(DataKey key); // for asynchronous public Future executeAsynchronous(DataKey key); } 然后我有我的DataClient实现上面的Client接口: public class DataClient implements Client { private RestTemplate restTemplate = new RestTemplate(); // do I need to have all threads as […]

如何终止multithreading中超时的任务?

我需要创建一个库,在其中我将有同步和异步方法。 executeSynchronous() – 等到我有结果,返回结果。 executeAsynchronous() – 立即返回一个Future,如果需要,可以在其他事情完成后处理。 我的图书馆的核心逻辑 客户将使用我们的库,他们将通过传递DataKey构建器对象来调用它。 然后,我们将使用该DataKey对象构造一个URL,并通过执行它来对该URL进行HTTP客户端调用,然后在我们将响应作为JSON字符串返回之后,我们将通过创建将该JSON字符串发送回我们的客户DataResponse对象。 有些客户会调用executeSynchronous() ,有些可能会调用executeAsynchronous() ,这就是为什么我需要在我的库中单独提供两个方法。 接口: public interface Client { // for synchronous public DataResponse executeSynchronous(DataKey key); // for asynchronous public Future executeAsynchronous(DataKey key); } 然后我有我的DataClient实现上面的Client接口: public class DataClient implements Client { private RestTemplate restTemplate = new RestTemplate(); private ExecutorService executor = Executors.newFixedThreadPool(10); // for synchronous call […]

RestTemplate应该是全局声明的静态吗?

我在我的代码中使用Java Callable Future。 下面是我使用未来和callables的主要代码 – public class TimeoutThread { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); Future future = executor.submit(new Task()); try { System.out.println(“Started..”); System.out.println(future.get(3, TimeUnit.SECONDS)); System.out.println(“Finished!”); } catch (TimeoutException e) { System.out.println(“Terminated!”); } executor.shutdownNow(); } } 下面是我的Task类,它实现了Callable接口,我需要根据我们拥有的主机名生成URL,然后使用RestTemplate调用SERVERS。 如果第一个主机名中有任何exception,那么我将为另一个主机名生成URL,我将尝试拨打电话。 class Task implements Callable { private static RestTemplate restTemplate = new […]