List of usage examples for java.util.concurrent Future get
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
From source file:com.apress.prospringintegration.gateways.client.MainAsyncGateway.java
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("gateway-async.xml"); TicketIssuerAsync ticketIssuerAsync = context.getBean("ticketIssueGatewayAsync", TicketIssuerAsync.class); Future<Ticket> result = ticketIssuerAsync.issueTicket(100L); Ticket ticket = result.get(1000, TimeUnit.SECONDS); System.out.println("Ticket: " + ticket + " was issued on: " + ticket.getIssueDateTime() + " with ticket id: " + ticket.getTicketId()); }
From source file:com.curso.ejemplotareaplanificada.Principal.java
/** * @param args the command line arguments *//*from w w w .j a v a 2 s.co m*/ public static void main(String[] args) { //solo estamos usando anotaciones //en esta clase no hay nada de los metodos planificados porque esos ya los llama spring solito //esta clase es para pegarnos con los servicios asincronos ApplicationContext ctx = new AnnotationConfigApplicationContext(Configuracion.class); System.out.println("Contexto cargado"); ServicioAsincrono sa = ctx.getBean(ServicioAsincrono.class); System.out.println("Hilo principal " + Thread.currentThread()); //Este metodo devuelve void asi que el hilo arranca un nuevo hilo pero continua sin esperar ni ahora ni a un futuro sa.metodoUno(); //Este metodo devuelve un futuro, y cuando llamemos a get espera 5 segundos a ver si termina el nuevo hilo //Si sobre pasa esos 5 segundos lanza una excepcion Future<Double> numero = sa.factorial(100); try { System.out.println("El factorial es desde un Future:" + numero.get(5L, TimeUnit.SECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); } //Este metodo devuelve un escuchable ListenableFuture<Double> valor = sa.factorialLf(100); //Al metodo escuchable le aadimos una clase anonima de tipo llamable con dos metodos, uno que se ejecutara cuando acabe con exito //y otro si no acaba correctamente valor.addCallback(new ListenableFutureCallback<Double>() { @Override public void onSuccess(Double result) { System.out.println("El resultado es desde un ListenableFuture: " + result); } @Override public void onFailure(Throwable ex) { LOG.log(Level.SEVERE, "Ha ocurrido un error:", ex); } }); }
From source file:Main.java
private static <T> T readCallableResult(Future<T> future) throws Exception { try {//from www . jav a2 s. com return future.get(60, TimeUnit.SECONDS); } catch (TimeoutException e) { return null; } finally { future.cancel(true); } }
From source file:Main.java
public static <T> T executeWithTimeout(Callable<T> task, int milliseconds) { ExecutorService executor = Executors.newCachedThreadPool(); Future<T> future = executor.submit(task); T result;/*from ww w . ja v a 2s.c om*/ try { result = future.get(milliseconds, TimeUnit.MILLISECONDS); } catch (Exception e) { //handle timeout and other exceptions e.printStackTrace(); result = null; } finally { future.cancel(true); } return result; }
From source file:Main.java
/** * Simple helper method to have timed run method (that timeouts if runs too * long). Good for long calculations wich has time limit. * //from ww w. j a v a 2 s . c om * @param <V> * @param c Callable with calculation logic. * @param timeout Time after calculation times out. * @param timeUnit Time metric (seconds, minutes etc). * * @return Calculation result if calculation finished. * * @throws Throwable Exception that might be thrown in calculation. */ public static <V> V timedRun(Callable<V> c, long timeout, TimeUnit timeUnit) throws Throwable { Future<V> task = taskExec.submit(c); try { return task.get(timeout, timeUnit); } catch (ExecutionException e) { throw e.getCause(); } catch (TimeoutException e) { // throw exception if need to know that timeout occured // or leave empty if null can be returned on timeout } finally { task.cancel(true); } return null; }
From source file:Main.java
/** * Runs and blocking waits for the given callable to finish for the given * time. Returns <code>null</code> if timeouts waiting for callable value. * /*from w w w . j a v a 2s.com*/ * @param millisTimeout * @param callable * @return */ public static <R> R runWithTimeout(long millisTimeout, Callable<R> callable) { ExecutorService singleThreadExecutor = Executors.newFixedThreadPool(1); Future<R> future = singleThreadExecutor.submit(callable); try { return future.get(millisTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { } finally { singleThreadExecutor.shutdown(); } return null; }
From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpClient.java
private static SimpleHttpResponse execute(CloseableHttpClient httpClient, SimpleHttpRequest request, long timeout, TimeUnit timeunit) throws Exception { RequestTask task = new RequestTask(httpClient, request); Future<SimpleHttpResponse> futureResponse = null; try {// w ww. j a v a 2 s. c o m futureResponse = requestExecutor.submit(task); return futureResponse.get(timeout, timeunit); } catch (TimeoutException e) { httpClient.close(); RequestLine line = request.getRequestLine(); String method = request.getMethod(); if (line != null && method != null) { throw new TimeoutException(msg.format("error.complete", method.toUpperCase(), line.getUri(), timeout, timeunit.toString().toLowerCase())); } else { throw new TimeoutException(msg.format("error", timeout, timeunit.toString().toLowerCase())); } } catch (Exception e) { httpClient.close(); throw e; } finally { if (futureResponse != null) { futureResponse.cancel(true); } } }
From source file:com.sm.transport.grizzly.TCPClient.java
public static TCPClient start(String host, int port, BaseFilter coder, BaseFilter clientFilter) { TCPClient client = new TCPClient(host, port); client.clientFilter = clientFilter;// w ww.ja v a 2 s.c o m FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); // Add TransportFilter, which is responsible // for reading and writing data to the connection filterChainBuilder.add(new TransportFilter()); // StringFilter is responsible for Buffer <-> String conversion filterChainBuilder.add(coder); // EchoFilter is responsible for echoing received messages filterChainBuilder.add(clientFilter); // Create TCP transport client.transport = TCPNIOTransportBuilder.newInstance().build(); client.transport.setProcessor(filterChainBuilder.build()); try { // binding transport to start listen on certain host and port try { client.transport.start(); // perform async. connect to the server Future<Connection> future = client.transport.connect(client.host, client.port); // wait for connect operation to complete client.connection = future.get(5, TimeUnit.SECONDS); if (client.connection.isOpen()) return client; else throw new ConnectionException("can not connect to " + client.toString()); //System.in.read(); } catch (Exception e) { //shutdown transport thread if (client.transport != null) client.transport.shutdown(); throw new RuntimeException(e.getMessage(), e); } } finally { } }
From source file:com.silica.Silica.java
/** * Job??/*from w w w. ja va 2 s.c o m*/ * * @param job * @param jobTimeoutMsec * @return * @throws ServiceException */ public static <T extends Serializable> T execute(Job<T> job, long jobTimeoutMsec) throws ServiceException { JobExecutor<T> executor = new JobExecutor<T>(job); Future<T> future = EXECUTOR_POOL.submit(executor); Exception err = null; try { return future.get(jobTimeoutMsec, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.info(job.toString(), e); err = e; } catch (ExecutionException e) { LOG.error(job.toString(), e); err = e; } catch (TimeoutException e) { LOG.warn(job.toString(), e); err = e; } throw new ServiceException(job.toString(), err); }
From source file:mase.conillon.ConillonMasterProblem.java
public static void runWithTimeout(Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future future = executor.submit(runnable); executor.shutdown(); // This does not cancel the already-scheduled task. try {//from w ww .j ava2 s. c om future.get(timeout, timeUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { future.cancel(true); throw e; } }