List of usage examples for java.util.concurrent TimeoutException TimeoutException
public TimeoutException(String message)
From source file:com.twitter.common.zookeeper.ZooKeeperClient.java
/** * Returns the current active ZK connection or establishes a new one if none has yet been * established or a previous connection was disconnected or had its session time out. This * method will attempt to re-use sessions when possible. * * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK * cluster to be established; 0 to wait forever * @return a connected ZooKeeper client//from ww w . ja v a 2s. co m * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster * @throws InterruptedException if interrupted while waiting for a connection to be established * @throws TimeoutException if a connection could not be established within the configured * session timeout */ public synchronized ZooKeeper get(Amount<Long, Time> connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; } } eventQueue.offer(event); } }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.getValue() > 0) { if (!connected.await(connectionTimeout.as(Time.MILLISECONDS), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java
/** * Returns the current active ZK connection or establishes a new one if none has yet been * established or a previous connection was disconnected or had its session time out. This * method will attempt to re-use sessions when possible. * * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK * cluster to be established; 0 to wait forever * @return a connected ZooKeeper client/*from www.j a v a 2s.c om*/ * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster * @throws InterruptedException if interrupted while waiting for a connection to be established * @throws TimeoutException if a connection could not be established within the configured * session timeout */ public synchronized ZooKeeper get(Duration connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; default: break; // nop } break; default: break; // nop } eventQueue.offer(event); } }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(connectString, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(connectString, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.inMillis() > 0) { if (!connected.await(connectionTimeout.inMillis(), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClient.java
/** * Executes a function with load balancer. * // www . ja v a2 s. c o m * @param path * @param function * @return * @throws NoServerAvailableException * @throws RetriesExceededException */ private <T> HttpResponse<T> executeWithLoadBalancer(String path, FunctionWrapper<T> function) throws NoServerAvailableException, RetriesExceededException { long retries = numRetries; do { // get a load balanced server ServerStats server = janus.getServer(); if (server == null) { throw new NoServerAvailableException(janus.getServiceName()); } // prefix URL with selected server String newUrl = server.getServerInstance().getUrl() + path; // call into REST Template wrapper HttpResponse<T> result = null; long latency = -1; try { server.incrementSentMessages(); server.incrementOpenRequests(); long startTime = System.currentTimeMillis(); result = function.execute(newUrl); latency = System.currentTimeMillis() - startTime; // exit if successful if (result == null) { throw new TimeoutException("Timed out while waiting for a response."); } else { if (result.getStatusCode() >= 500) { throw new HttpResponseException(result.getStatusCode(), "Unexpected response"); } return result; } } catch (Exception e) { // unexpected exception, treat as a server problem but also log it. logger.warn("RestClient threw unexpected exception, retrying another server", e); server.incrementErrors(); } finally { server.decrementOpenRequests(); if (latency > 0) { server.recordLatency(latency); } } retries -= 1; } while (retries >= 0); throw new RetriesExceededException(janus.getServiceName(), numRetries); }
From source file:com.maestrodev.maestrocontinuumplugin.ContinuumWorker.java
private void triggerBuild(ProjectSummary project, BuildDefinition buildDefinition) throws Exception { int projectId = project.getId(); int buildDefinitionId = buildDefinition.getId(); // We can't construct a SCHEDULED trigger, as Continuum currently overrides it internally. Instead, call a // method that uses a scheduled default trigger if needed try {//from w w w . ja v a2 s . c o m if (isForceBuild()) { BuildTrigger buildTrigger = new BuildTrigger(); buildTrigger.setTrigger(ContinuumProjectState.TRIGGER_FORCED); buildTrigger.setTriggeredBy(getRunUsername()); client.buildProject(projectId, buildDefinitionId, buildTrigger); } else { // Trigger a "scheduled" build client.addProjectToBuildQueue(projectId, buildDefinitionId); } } catch (Exception ex) { throw new Exception("Failed To Trigger Build " + ex.getMessage()); } long start = System.currentTimeMillis(); writeOutput("Waiting For Build To Start\n"); setWaiting(true); // we are waiting if: // - it is checking out or updating // - it is currently in a queue // This should cover all cases until it is building, or complete // We can't just check for building or complete because it might not build (or do so fast) if there are no SCM // changes, and it is initially in a complete state until it hits one of the queues boolean waiting = true; while (waiting) { project = client.getProjectSummary(projectId); if (project.getState() == ContinuumProjectState.CHECKING_OUT || project.getState() == ContinuumProjectState.UPDATING || client.isProjectInPrepareBuildQueue(projectId, buildDefinitionId) || client.isProjectInBuildingQueue(projectId, buildDefinitionId) || client.isProjectCurrentlyPreparingBuild(projectId, buildDefinitionId)) { if (System.currentTimeMillis() - start > buildStartTimeout) { throw new TimeoutException( "Failed To Detect Build Start After " + (buildStartTimeout / 1000) + " Seconds"); } Thread.sleep(250); } else { waiting = false; } } setWaiting(false); }
From source file:no.group09.connection.Protocol.java
/** * Requests the value of the specified pin on the remote device. This method is blocking * until a Timeout happens.//from ww w. j a va 2 s. c om * @param sensor which pin to get the value from * @return the value of the specified pin * @throws TimeoutException if the remote device used too long time to respond */ public final boolean read(int pin) throws TimeoutException { ProtocolInstruction newInstruction = new ProtocolInstruction(OpCode.PIN_R, (byte) pin, new byte[1]); lock(); waitingForAck = OpCode.PIN_R; try { sendBytes(newInstruction.getInstructionBytes()); } catch (IOException ex) { System.out.println("Send fail"); } release(); long time = System.currentTimeMillis(); while (waitingForAck != null) { if (System.currentTimeMillis() - time > TIMEOUT) { waitingForAck = null; throw new TimeoutException("Timeout"); } try { Thread.sleep(10); } catch (InterruptedException ex) { } } byte content[] = currentCommand.getContent(); ackProcessingComplete(); return content[0] > 0 ? true : false; }
From source file:com.twitter.distributedlog.readahead.ReadAheadWorker.java
@Override public Future<Void> asyncClose() { LOG.info("Stopping Readahead worker for {}", fullyQualifiedName); running = false;//from w w w . j a v a 2s .c om this.zkc.getWatcherManager().unregisterChildWatcher(this.logMetadata.getLogSegmentsPath(), this); // Aside from unfortunate naming of variables, this allows // the currently active long poll to be interrupted and completed AsyncNotification notification; synchronized (notificationLock) { notification = metadataNotification; metadataNotification = null; } if (null != notification) { notification.notifyOnOperationComplete(); } if (null == stopPromise) { return Future.Void(); } return FutureUtils .ignore(FutureUtils.within(stopPromise, 2 * conf.getReadAheadWaitTime(), TimeUnit.MILLISECONDS, new TimeoutException( "Timeout on waiting for ReadAhead worker to stop " + fullyQualifiedName), scheduler, fullyQualifiedName)); }
From source file:io.cloudslang.lang.tools.build.tester.SlangTestRunnerTest.java
@Test public void runTestCaseParallel() throws InterruptedException, ExecutionException, TimeoutException { Map<String, SlangTestCase> testCases = new HashMap<>(); SlangTestCase testCase1 = new SlangTestCase("test1", "testFlowPath1", null, null, null, null, null, null, null);/*from w w w . ja v a 2s .c o m*/ SlangTestCase testCase2 = new SlangTestCase("test2", "testFlowPath2", null, null, null, null, null, null, null); testCases.put("test1", testCase1); testCases.put("test2", testCase2); HashMap<String, CompilationArtifact> compiledFlows = new HashMap<>(); compiledFlows.put("testFlowPath1", new CompilationArtifact(new ExecutionPlan(), null, null, null)); compiledFlows.put("testFlowPath2", new CompilationArtifact(new ExecutionPlan(), null, null, null)); doNothing().when(testCaseEventDispatchService).unregisterAllListeners(); doNothing().when(testCaseEventDispatchService).registerListener(any(ISlangTestCaseEventListener.class)); final SubscribeArgumentsHolder subscribeArgumentsHolder = new SubscribeArgumentsHolder(); // Get the global event listener that was created doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); MultiTriggerTestCaseEventListener listener = (MultiTriggerTestCaseEventListener) arguments[0]; subscribeArgumentsHolder.setMultiTriggerTestCaseEventListener(listener); @SuppressWarnings("unchecked") Set<String> argument = (Set<String>) arguments[1]; subscribeArgumentsHolder.setEventTypes(argument); return null; } }).when(slang).subscribeOnEvents(any(ScoreEventListener.class), anySetOf(String.class)); final Future futureTestCase1 = mock(Future.class); final Future futureTestCase2 = mock(Future.class); final List<Runnable> runnableList = Lists.newArrayList(); // Collect the Runnable objects created inside, so that later we can verify them doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { int size = runnableList.size(); Object[] arguments = invocationOnMock.getArguments(); runnableList.add((Runnable) arguments[0]); return size == 0 ? futureTestCase1 : futureTestCase2; } }).when(parallelTestCaseExecutorService).submitTestCase(any(Runnable.class)); doThrow(new TimeoutException("timeout")).when(futureTestCase1).get(anyLong(), any(TimeUnit.class)); doThrow(new RuntimeException("unknown exception")).when(futureTestCase2).get(anyLong(), any(TimeUnit.class)); doNothing().when(slang).unSubscribeOnEvents(any(ScoreEventListener.class)); doNothing().when(testCaseEventDispatchService).notifyListeners(any(SlangTestCaseEvent.class)); final ThreadSafeRunTestResults runTestsResults = new ThreadSafeRunTestResults(); slangTestRunner.runTestsParallel("path", testCases, compiledFlows, runTestsResults); verify(testCaseEventDispatchService, times(2)).unregisterAllListeners(); verify(testCaseEventDispatchService).registerListener(isA(ThreadSafeRunTestResults.class)); verify(testCaseEventDispatchService).registerListener(isA(LoggingSlangTestCaseEventListener.class)); verify(slang).subscribeOnEvents(eq(subscribeArgumentsHolder.getMultiTriggerTestCaseEventListener()), eq(subscribeArgumentsHolder.getEventTypes())); InOrder inOrderTestCases = inOrder(parallelTestCaseExecutorService); inOrderTestCases.verify(parallelTestCaseExecutorService).submitTestCase(eq(runnableList.get(0))); inOrderTestCases.verify(parallelTestCaseExecutorService).submitTestCase(eq(runnableList.get(1))); inOrderTestCases.verifyNoMoreInteractions(); verify(futureTestCase1).get(eq(MAX_TIME_PER_TESTCASE_IN_MINUTES), eq(TimeUnit.MINUTES)); verify(futureTestCase2).get(eq(MAX_TIME_PER_TESTCASE_IN_MINUTES), eq(TimeUnit.MINUTES)); verify(testCaseEventDispatchService, times(2)).notifyListeners(isA(FailedSlangTestCaseEvent.class)); verify(slang).unSubscribeOnEvents(eq(subscribeArgumentsHolder.getMultiTriggerTestCaseEventListener())); }
From source file:com.mgmtp.perfload.core.console.LtConsole.java
private void awaitLatch(final CountDownLatch latch, final String message) throws InterruptedException, TimeoutException { if (!latch.await(2L, TimeUnit.MINUTES)) { throw new TimeoutException(message); }/*from w w w .ja v a 2s . c o m*/ }
From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java
/** * Generic wait function./*from ww w. j a v a 2s .c o m*/ */ public static <T> T waitForState(Supplier<T> supplier, Predicate<T> predicate, long waitIterationSleep, long waitIterationCount, Runnable cleanup) throws Throwable { for (int i = 0; i < waitIterationCount; i++) { T t = supplier.get(); if (predicate.test(t)) { return t; } Thread.sleep(waitIterationSleep); } if (cleanup != null) { cleanup.run(); } throw new TimeoutException("timeout waiting for state transition."); }
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Returns a value representing the remaining time before the operation expires. * /*from www . j a v a 2 s .co m*/ * @param operationExpiryTimeInMs * the time the request expires * @param timeoutIntervalInMs * the server side timeout interval * @return the remaining time before the operation expires * @throws StorageException * wraps a TimeoutException if there is no more time remaining */ public static int getRemainingTimeout(Long operationExpiryTimeInMs, Integer timeoutIntervalInMs) throws StorageException { if (operationExpiryTimeInMs != null) { long remainingTime = operationExpiryTimeInMs - new Date().getTime(); if (remainingTime > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (remainingTime > 0) { return (int) remainingTime; } else { TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION); StorageException translatedException = new StorageException( StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException); throw translatedException; } } else if (timeoutIntervalInMs != null) { return timeoutIntervalInMs + Constants.DEFAULT_READ_TIMEOUT; } else { return Constants.DEFAULT_READ_TIMEOUT; } }