List of usage examples for java.util.concurrent FutureTask get
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
From source file:org.sakaiproject.tool.impl.SessionComponentRegressionTest.java
/** * Identical to {@link #testGetSessionReturnsSessionCreatedByStartSession()} * except that it tests the overload of <code>startSession()</code> * ({@link SessionComponent#startSession(String)}. * /*w w w . j a va2 s .c o m*/ * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ public void testGetSessionAlwaysReturnsSessionStartedWithClientSpecifiedId() throws InterruptedException, ExecutionException, TimeoutException { final Session startedSession = sessionComponent.startSession("9876543210"); assertSame(startedSession, sessionComponent.getSession(startedSession.getId())); assertSame(startedSession, sessionComponent.getSession(startedSession.getId())); // intentional duplicate // all threads should get the same Session obj for a given key FutureTask<Session> asynchGet = new FutureTask<Session>(new Callable<Session>() { public Session call() { return sessionComponent.getSession(startedSession.getId()); } }); new Thread(asynchGet).start(); assertSame(startedSession, asynchGet.get(1, TimeUnit.SECONDS)); }
From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java
int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { FutureTask<Integer> future = new FutureTask<Integer>(new Callable<Integer>() { @Override//ww w. j a v a2 s.co m public Integer call() throws InterruptedException { proc.destroy(); return proc.waitFor(); } }); executor.execute(future); return future.get(timeout, unit); }
From source file:org.sakaiproject.tool.impl.SessionComponentRegressionTest.java
/** * Verifies that a session created as a side-effect of * {@link SessionComponent#getCurrentSession()} is available in a * thread-scoped cache, i.e. that a call to {@link {@link SessionComponent#getCurrentSession()} * on a different, sessionless thread receives a different session. This is * distinct from {@link #testGetCurrentSessionLazilyCreatesTransientSession()} * which is concerned with whether or not lazily created "current" sessions * are findable by ID (they are <em>not</em>). * @throws TimeoutException //www. j a v a 2 s . c om * @throws ExecutionException * @throws InterruptedException */ public void testGetCurrentSessionCachesLazilyCreatedThreadScopedSession() throws InterruptedException, ExecutionException, TimeoutException { expectLazyCurrentSessionCreation("1234546789"); final Session session = sessionComponent.getCurrentSession(); assertNotNull("Should have allocated a new session", session); // Since we control the return value of the "gets" on threadLocalManager, // the important bit here is that the "get" expectation defined immediately // below is satisfied, much less so the "sameness" assertion following that. // The same basic point holds for the asynch further on down. checking(new Expectations() { { one(threadLocalManager).get(with(equal(SessionComponent.CURRENT_SESSION))); will(returnValue(session)); } }); assertSame("A thread should always receive the same \"current\" session", session, sessionComponent.getCurrentSession()); // other threads should get different "current" Session objects final SessionHolder sessionHolder = new SessionHolder(); expectLazyCurrentSessionCreation(sessionHolder, "987654321"); FutureTask<Session> asynchGet = new FutureTask<Session>(new Callable<Session>() { public Session call() { return sessionComponent.getCurrentSession(); } }); new Thread(asynchGet).start(); assertNotSame("Should have allocated a different \"current\" session for other thread", session, asynchGet.get(1, TimeUnit.SECONDS)); }
From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java
protected long runWithTimeout(MutationTestRunnable r) { long[] preIds = threadMxBean.getAllThreadIds(); FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r)); Thread thread = new Thread(future); thread.setDaemon(true);/*from www . j a v a 2 s. c om*/ logger.debug("Start test: "); StopWatch stopWatch = new StopWatch(); stopWatch.start(); thread.start(); String exceptionMessage = null; Throwable capturedThrowable = null; try { future.get(timeout, TimeUnit.SECONDS); logger.debug("Second timeout"); } catch (InterruptedException e) { capturedThrowable = e; } catch (ExecutionException e) { capturedThrowable = e; } catch (TimeoutException e) { exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout"; capturedThrowable = e; } catch (Throwable t) { capturedThrowable = t; } finally { if (capturedThrowable != null) { if (exceptionMessage == null) { exceptionMessage = "Exception caught during test execution."; } ByteArrayOutputStream out = new ByteArrayOutputStream(); capturedThrowable.printStackTrace(new PrintStream(out)); logger.debug( "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable); r.setFailed(exceptionMessage, capturedThrowable); } } if (!future.isDone()) { r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutated Thread is still running after timeout.", null); switchOfMutation(future); } stopWatch.stop(); if (!checkAllFinished(preIds)) { if (configuration.useThreadStop()) { stopThreads(preIds); } else { shutDown(r, stopWatch); } } logger.debug("End timed test, it took " + stopWatch.getTime() + " ms"); return stopWatch.getTime(); }
From source file:org.apache.ambari.server.KdcServerConnectionVerification.java
/** * Attempt to communicate with KDC server over UDP. * @param server KDC hostname or IP address * @param port KDC server port// w w w . j a va2s . c om * @return true if communication is successful; false otherwise */ public boolean isKdcReachableViaUDP(final String server, final int port) { int timeoutMillis = udpTimeout * 1000; final KdcConfig config = KdcConfig.getDefaultConfig(); config.setHostName(server); config.setKdcPort(port); config.setUseUdp(true); config.setTimeout(timeoutMillis); final KdcConnection connection = getKdcUdpConnection(config); FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() { try { // we are only testing whether we can communicate with server and not // validating credentials connection.getTgt("noUser@noRealm", "noPassword"); } catch (KerberosException e) { // unfortunately, need to look at msg as error 60 is a generic error code return !(e.getErrorCode() == ErrorType.KRB_ERR_GENERIC.getValue() && e.getMessage().contains("TimeOut")); //todo: evaluate other error codes to provide better information //todo: as there may be other error codes where we should return false } catch (Exception e) { // some bad unexpected thing occurred throw new RuntimeException(e); } return true; } }); new Thread(future, "ambari-kdc-verify").start(); Boolean result; try { // timeout after specified timeout result = future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.error("Interrupted while trying to communicate with KDC server over UDP"); result = false; future.cancel(true); } catch (ExecutionException e) { LOG.error( "An unexpected exception occurred while attempting to communicate with the KDC server over UDP", e); result = false; } catch (TimeoutException e) { LOG.error("Timeout occurred while attempting to to communicate with KDC server over UDP"); result = false; future.cancel(true); } return result; }
From source file:com.google.android.dialer.provider.DialerProvider.java
private <T> T execute(Callable<T> callable, String name, long time, TimeUnit timeUnit) { FutureCallable<T> futureCallable = new FutureCallable<T>(callable); FutureTask<T> future = new FutureTask<T>(futureCallable); futureCallable.setFuture(future);//from w w w. ja v a2s .c o m synchronized (mActiveTasks) { mActiveTasks.addLast(future); if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "Currently running tasks: " + mActiveTasks.size()); } while (mActiveTasks.size() > 8) { Log.w("DialerProvider", "Too many tasks, canceling one"); mActiveTasks.removeFirst().cancel(true); } } if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "Starting task " + name); } new Thread(future, name).start(); try { if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "Getting future " + name); } return future.get(time, timeUnit); } catch (InterruptedException e) { Log.w("DialerProvider", "Task was interrupted: " + name); Thread.currentThread().interrupt(); } catch (ExecutionException e) { Log.w("DialerProvider", "Task threw an exception: " + name, e); } catch (TimeoutException e) { Log.w("DialerProvider", "Task timed out: " + name); future.cancel(true); } catch (CancellationException e) { Log.w("DialerProvider", "Task was cancelled: " + name); } // TODO: Is this appropriate? return null; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException { final HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(reqConfBuilder.build()); if (this.host != null) context.setTargetHost(new HttpHost(this.host)); setHeaders(httpUriRequest);// ww w . j a v a 2 s .c om // statistics storeConnectionInfo(httpUriRequest); // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF if (httpUriRequest instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest; final HttpEntity entity = hrequest.getEntity(); assert entity != null; //assert !entity.isChunked(); //assert entity.getContentLength() >= 0; assert !hrequest.expectContinue(); } final String initialThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI()); final long time = System.currentTimeMillis(); try { if (concurrent) { FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>( new Callable<CloseableHttpResponse>() { @Override public CloseableHttpResponse call() throws ClientProtocolException, IOException { final CloseableHttpClient client = clientBuilder.build(); CloseableHttpResponse response = client.execute(httpUriRequest, context); return response; } }); executor.execute(t); try { this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw e.getCause(); } catch (Throwable e) { } try { t.cancel(true); } catch (Throwable e) { } if (this.httpResponse == null) throw new IOException("timout to client after " + this.timeout + "ms" + " for url " + httpUriRequest.getURI().toString()); } else { final CloseableHttpClient client = clientBuilder.build(); this.httpResponse = client.execute(httpUriRequest, context); } this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS, Long.toString(System.currentTimeMillis() - time)); } catch (final Throwable e) { ConnectionInfo.removeConnection(httpUriRequest.hashCode()); httpUriRequest.abort(); if (this.httpResponse != null) this.httpResponse.close(); //e.printStackTrace(); throw new IOException( "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage()) + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url " + httpUriRequest.getURI().toString()); } finally { /* Restore the thread initial name */ Thread.currentThread().setName(initialThreadName); } }
From source file:org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter.java
/** * Calls the {@link AbstractMappingMetadataExtracter#extractRaw(ContentReader)} method * using the given limits.//from w w w . j av a 2 s . c o m * <p> * Currently the only limit supported by {@link MetadataExtracterLimits} is a timeout * so this method uses {@link AbstractMappingMetadataExtracter#getExecutorService()} * to execute a {@link FutureTask} with any timeout defined. * <p> * If no timeout limit is defined or is unlimited (-1), * the <code>extractRaw</code> method is called directly. * * @param reader the document to extract the values from. This stream provided by * the reader must be closed if accessed directly. * @param limits the limits to impose on the extraction * @return Returns a map of document property values keyed by property name. * @throws Throwable All exception conditions can be handled. */ private Map<String, Serializable> extractRaw(ContentReader reader, MetadataExtracterLimits limits) throws Throwable { if (limits == null || limits.getTimeoutMs() == -1) { return extractRaw(reader); } FutureTask<Map<String, Serializable>> task = null; StreamAwareContentReaderProxy proxiedReader = null; try { proxiedReader = new StreamAwareContentReaderProxy(reader); task = new FutureTask<Map<String, Serializable>>(new ExtractRawCallable(proxiedReader)); getExecutorService().execute(task); return task.get(limits.getTimeoutMs(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { task.cancel(true); if (null != proxiedReader) { proxiedReader.release(); } throw e; } catch (InterruptedException e) { // We were asked to stop task.cancel(true); return null; } catch (ExecutionException e) { // Unwrap our cause and throw that Throwable cause = e.getCause(); if (cause != null && cause instanceof ExtractRawCallableException) { cause = ((ExtractRawCallableException) cause).getCause(); } throw cause; } }
From source file:android.webkit.cts.WebViewTest.java
public void testPrinting() throws Throwable { if (!NullWebViewUtils.isWebViewAvailable()) { return;//from w w w .j ava 2s. com } mOnUiThread.loadDataAndWaitForCompletion("<html><head></head>" + "<body>foo</body></html>", "text/html", null); final PrintDocumentAdapter adapter = mOnUiThread.createPrintDocumentAdapter(); printDocumentStart(adapter); PrintAttributes attributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4) .setResolution(new PrintAttributes.Resolution("foo", "bar", 300, 300)) .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build(); final WebViewCtsActivity activity = getActivity(); final File file = activity.getFileStreamPath(PRINTER_TEST_FILE); final ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("w")); final FutureTask<Boolean> result = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() { return true; } }); printDocumentLayout(adapter, null, attributes, new LayoutResultCallback() { // Called on UI thread @Override public void onLayoutFinished(PrintDocumentInfo info, boolean changed) { savePrintedPage(adapter, descriptor, result); } }); try { result.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS); assertTrue(file.length() > 0); FileInputStream in = new FileInputStream(file); byte[] b = new byte[PDF_PREAMBLE.length()]; in.read(b); String preamble = new String(b); assertEquals(PDF_PREAMBLE, preamble); } finally { // close the descriptor, if not closed already. descriptor.close(); file.delete(); } }
From source file:org.atomserver.core.dbstore.DBBasedAtomCollection.java
protected <T> T executeTransactionally(final TransactionalTask<T> task) { final String t_user = AtomServerUserInfo.getUser(); FutureTask<T> timeoutTask = null; try {/* w w w . j av a 2 s .co m*/ // create new timeout task timeoutTask = new FutureTask<T>(new Callable() { public T call() throws Exception { return (T) getTransactionTemplate().execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { AtomServerUserInfo.setUser(t_user); StopWatch stopWatch = new AtomServerStopWatch(); try { // NOTE: we will actually wait for all of these to possibly finish, // unless the methods below honor InterruptedExceptions // BUT the transaction will still be rolled back eventually by the catch below. getWriteEntriesDAO().acquireLock(); return task.execute(); } catch (Exception ee) { if (ee instanceof EntryNotFoundException && (((EntryNotFoundException) ee) .getType() == EntryNotFoundException.EntryNotFoundType.DELETE)) { log.warn("Exception in DB transaction", ee); } else { log.error("Exception in DB transaction", ee); } // the following is not really required, but ensures that this will rollback, without question transactionStatus.setRollbackOnly(); if (ee instanceof InterruptedException) { // InterruptedException - if the current thread was interrupted while waiting // Re-assert the thread's interrupted status Thread.currentThread().interrupt(); } // NOTE: per the Spring manual, a transaction is ONLY rolled back // when a RuntimeException is thrown!!! // And the timeout causes an InterruptedException (via task.cancel()), // which is NOT Runtime!! // (AtomServerException extends RuntimeException) throw (ee instanceof AtomServerException) ? (AtomServerException) ee : new AtomServerException("A " + ee.getCause().getClass().getSimpleName() + " caught in Transaction", ee.getCause()); } finally { stopWatch.stop("DB.txn", "DB.txn"); } } }); } }); // start timeout task in a new thread new Thread(timeoutTask).start(); // wait for the execution to finish, timeout after X secs int timeout = (getTransactionTemplate().getTimeout() > 0) ? getTransactionTemplate().getTimeout() : DEFAULT_TXN_TIMEOUT; return timeoutTask.get(timeout, TimeUnit.SECONDS); } catch (AtomServerException ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw ee; } catch (ExecutionException ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw (ee.getCause() == null) ? new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee) : (ee.getCause() instanceof AtomServerException) ? (AtomServerException) ee.getCause() : new AtomServerException( "A " + ee.getCause().getClass().getSimpleName() + " caught in Transaction", ee.getCause()); } catch (Exception ee) { log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage()); throw new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee); } finally { // NOTE: We MUST call timeoutTask.cancel() here. // This is the ONLY way that we see an InterruptedException in the transaction task, // and thus, the ONLY way that we can make the transaction rollback. // NOTE: Calling cancel() on a completed task is a noop. log.debug("@@@@@@@@@@@@@@ Calling task.cancel"); timeoutTask.cancel(true); timeoutTask = null; } }