@Override protected void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result, final RemoteServiceRequest request, final String responseName) { if (!optionsCopy.isResultExpected()) { return; } Long startTime = 0L; if (request != null && request.getArgs() != null && request.getArgs().length > 3) { startTime = (Long)request.getArgs()[3]; } long delay = startTime - System.currentTimeMillis(); if (delay > 0) { commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { ScheduledTasksService.super.awaitResultAsync(optionsCopy, result, request, responseName); } }, delay, TimeUnit.MILLISECONDS); } else { super.awaitResultAsync(optionsCopy, result, request, responseName); } }
private synchronized void scheduleReconnect() { if (_stop) return; if (_timeout != null) return; Constants.ahessianLogger.warn("channel closed wait to reconnect ..."); _retryCounter++; long retryIntervall = Math.min(RECONNECT_DELAY * _retryCounter, MAX_RECONNECT_DELAY); _timeout = _timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { _timeout = null; connect(_bootstrap.getBootstrap()); } }, retryIntervall, TimeUnit.MILLISECONDS); }
public HeartbeatHandlerInbound(final String name, final Timer timer, final long timeout) { _name = name; final TimerTask task = new TimerTask() { public void run(Timeout nTimeout) throws Exception { if (((getLastCalled() + timeout) <= System.currentTimeMillis()) && isConnected()) try { _action.timedOut(_ctx); } catch (Exception e) { Constants.ahessianLogger.warn("", e); } } }; _intervalTimer = new IntervalTimer(timer, task, timeout); }
public void start(PulsarClientImpl client, ConsumerBase consumerBase, long ackTimeoutMillis) { this.stop(); timeout = client.timer().newTimeout(new TimerTask() { @Override public void run(Timeout t) throws Exception { if (isAckTimeout()) { log.warn("[{}] {} messages have timed-out", consumerBase, oldOpenSet.size()); Set<MessageIdImpl> messageIds = new HashSet<>(); oldOpenSet.forEach(messageIds::add); oldOpenSet.clear(); consumerBase.redeliverUnacknowledgedMessages(messageIds); } toggle(); timeout = client.timer().newTimeout(this, ackTimeoutMillis, TimeUnit.MILLISECONDS); } }, ackTimeoutMillis, TimeUnit.MILLISECONDS); }
/** * {@inheritDoc} * @see io.netty.util.Timer#newTimeout(io.netty.util.TimerTask, long, java.util.concurrent.TimeUnit) */ @Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { final WrappedTimeout[] t = new WrappedTimeout[1]; t[0] = new WrappedTimeout(timer.newTimeout(new TimerTask(){ @Override public void run(final Timeout timeout) throws Exception { try { task.run(t[0]); } finally { pendingTimeouts.decrementAndGet(); timeouts.increment(); } } }, delay, unit)); return t[0]; }
/** * Intentional private local constructor * @param key the request key * @param request the request object * @param window the window * @param timeoutMillis the time after which this future will be cancelled * @param timer the timer used to implement the timeout functionality */ private TimedDeferredRequest(final K key, final R request, final Window<K, R, D> window, final Timer timer, final long timeoutMillis) { super(key, request, window); this.timeout = checkNotNull(timer).newTimeout(new TimerTask() { @Override public void run(Timeout timerTask) throws Exception { window.fail(checkNotNull(key), new TimeoutException("The operation timed out (Window full)")); } }, timeoutMillis, TimeUnit.MILLISECONDS); }
@Test public void afterTimeoutFutureIsCancelled() throws Exception { when(timer.newTimeout(any(TimerTask.class), anyInt(), eq(TimeUnit.MILLISECONDS))) .thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { invocationOnMock.getArgumentAt(0, TimerTask.class).run(null); return null; } }); DeferredRequest<Integer, String, Boolean> deferredRequest = TimedDeferredRequest.create(5, "request", window, timer, 10000); verify(window).fail(eq(5), any(TimeoutException.class)); }
private void newRefreshTask() { if (refreshTaskMap.containsKey(getName())) { return; } Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { expire(internalLockLeaseTime, TimeUnit.MILLISECONDS); refreshTaskMap.remove(getName()); newRefreshTask(); // reschedule itself } }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS); if (refreshTaskMap.putIfAbsent(getName(), task) != null) { task.cancel(); } }
public void fireNext(final ChannelHandlerContext ctx, final long delay) { final Event readyForNext = new Event(currentConversationId); if(delay > timerTickSize) { timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) { if(logger.isDebugEnabled()) { logger.debug("running after delay: {}", delay); } if(readyForNext.conversationId != currentConversationId) { logger.debug("pending 'next' event found obsolete, aborting"); return; } ctx.pipeline().fireChannelRead(readyForNext); } }, delay, TimeUnit.MILLISECONDS); } else { ctx.pipeline().fireChannelRead(readyForNext); } }
@Override public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { try { return timer.newTimeout(task, delay, unit); } catch (IllegalStateException e) { // timer is shutdown return dummyTimeout; } }
@Before public void setUp() throws Exception { /* * This needs to be called explicitly to ensure the featuresReply is not null. * Otherwise, there is no guarantee @Before will for setUpFeaturesReply() will * call that function before our @Before setUp() here. */ setUpFeaturesReply(); switchManager = createMock(IOFSwitchManager.class); roleManager = createMock(RoleManager.class); sw = createMock(IOFSwitchBackend.class); timer = createMock(Timer.class); expect(timer.newTimeout(anyObject(TimerTask.class), anyLong(), anyObject(TimeUnit.class))).andReturn(EasyMock.createNiceMock(Timeout.class)); replay(timer); seenXids = null; // TODO: should mock IDebugCounterService and make sure // the expected counters are updated. debugCounterService = new DebugCounterServiceImpl(); SwitchManagerCounters counters = new SwitchManagerCounters(debugCounterService); expect(switchManager.getCounters()).andReturn(counters).anyTimes(); replay(switchManager); connection = new MockOFConnection(featuresReply.getDatapathId(), OFAuxId.MAIN); switchHandler = new OFSwitchHandshakeHandler(connection, featuresReply, switchManager, roleManager, timer); // replay sw. Reset it if you need more specific behavior replay(sw); }
/** * Get SASL handler * @param bootstrap to reconnect to * @return new SASL handler * @throws java.io.IOException if handler failed to create */ private SaslClientHandler getSaslHandler(final UserGroupInformation realTicket, final Bootstrap bootstrap) throws IOException { return new SaslClientHandler(realTicket, authMethod, token, serverPrincipal, client.fallbackAllowed, client.conf.get("hbase.rpc.protection", SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()), new SaslClientHandler.SaslExceptionHandler() { @Override public void handle(int retryCount, Random random, Throwable cause) { try { // Handle Sasl failure. Try to potentially get new credentials handleSaslConnectionFailure(retryCount, cause, realTicket); // Try to reconnect client.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, random.nextInt(reloginMaxBackoff) + 1, TimeUnit.MILLISECONDS); } catch (IOException | InterruptedException e) { close(e); } } }, new SaslClientHandler.SaslSuccessfulConnectHandler() { @Override public void onSuccess(Channel channel) { startHBaseConnection(channel); } }); }
/** * Retry to connect or close * * @param bootstrap to connect with * @param connectCounter amount of tries * @param e exception of fail */ private void retryOrClose(final Bootstrap bootstrap, int connectCounter, Throwable e) { if (connectCounter < client.maxRetries) { client.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, client.failureSleep, TimeUnit.MILLISECONDS); } else { client.failedServers.addToFailedServers(address); close(e); } }
private Object waitForCallbackResult(final Long id, final HessianProxyFuture future) { long timeout = 10000; if (timeout > 0) { TimerTask task = new TimerTask() { public void run(Timeout arg0) throws Exception { _openCallbackCalls.remove(id); future.timedOut(); } }; future.setTimeout(_timer.newTimeout(task, timeout, TimeUnit.MILLISECONDS)); } try { return future.getCallbackResult(); } catch (Exception e) { e.printStackTrace(); } return null; }
@Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { _hasSession = false; ctx.channel().attr(SESSION).get().close(); final String sessionId = ctx.channel().attr(SESSION).get().getId(); Constants.ahessianLogger.info("Session disconnected: " + sessionId); _sessionId = ""; _channel = null; // remove the session if the client does not reconnect within timeout if (_sessionTimeout > 0) { Timeout timeOut = _timer.newTimeout(new TimerTask() { public void run(Timeout arg0) throws Exception { ctx.channel().attr(SESSION).get().invalidate(); _factory.removeSession(sessionId); _sessionPipelines.remove(sessionId); _valid = false; Constants.ahessianLogger.warn(ctx.channel() + " session timed out: " + sessionId); } }, _sessionTimeout, TimeUnit.MILLISECONDS); ctx.channel().attr(SESSION).get().setTimeOut(timeOut); } ctx.fireChannelInactive(); }
private void newPingTimeout(TimerTask pintTask) { try { healthCheckTimer.newTimeout(pintTask, 1000 * 60 * 5, TimeUnit.MILLISECONDS); } catch (IllegalStateException e) { // stop in case of timer stopped logger.debug("timer stopped. Caused:{}", e.getMessage()); } }
public Timeout setPeriodicTransmissionTimeout(TimerTask task, long delay, TimeUnit unit) { Timeout timeout = null; synchronized (ipv6PeriodicRATimerWheel) { timeout = ipv6PeriodicRATimerWheel.newTimeout(task, delay, unit); } return timeout; }
public void timerThroughputTest(Control ctrl) throws InterruptedException { counterDown.set(times); for (int i = 0; i < times; i++) { timer.newTimeout((TimerTask) (v) -> counterDown.decrementAndGet(), delay, TimeUnit.MILLISECONDS); } while (!ctrl.stopMeasurement && counterDown.get() > 0) { // spin } }
@Test(expected = InterruptedException.class) public void tryInterruptInterruptsWaitingThreads() throws Exception { final InterruptingSemaphore interruptingSemaphore = new InterruptingSemaphore(0); final Timer timer = new HashedWheelTimer(); timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { interruptingSemaphore.tryInterrupt(); } }, 10, TimeUnit.MILLISECONDS); interruptingSemaphore.acquire(); }
/** * Schedules a new timeout. * @param task The task to execute when the timer times out. * @param timeout_ms The timeout, in milliseconds (strictly positive). */ void newTimeout(final TimerTask task, final long timeout_ms) { try { timer.newTimeout(task, timeout_ms, MILLISECONDS); } catch (IllegalStateException e) { // This can happen if the timer fires just before shutdown() // is called from another thread, and due to how threads get // scheduled we tried to call newTimeout() after timer.stop(). LOG.warn("Failed to schedule timer." + " Ignore this if we're shutting down.", e); } }
private void trySetup(final int attempt) { log.info("Attempt {}", action); final ChannelFuture connect = action.setup(); connect.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { log.info("Successful {}", action); setChannel(future.channel()); return; } final long delay = policy.delay(attempt); log.warn("Failed {} (attempt: {}), retrying in {}s: {}", action, attempt + 1, TimeUnit.SECONDS.convert(delay, TimeUnit.MILLISECONDS), future.cause().getMessage()); timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (stopped.get()) { return; } trySetup(attempt + 1); } }, delay, TimeUnit.MILLISECONDS); } }); }
private TimerTask onTimeoutTask() { return new TimerTask() { @Override public void run(Timeout timeout) throws Exception { callback.onTimeout(connection, System.nanoTime() - startTime); cancelHandler(); } }; }
/** * Get SASL handler * * @param bootstrap to reconnect to * @return new SASL handler * @throws java.io.IOException if handler failed to create */ private SaslClientHandler getSaslHandler(final Bootstrap bootstrap) throws IOException { return new SaslClientHandler(authMethod, token, serverPrincipal, client.fallbackAllowed, client.conf.get("hbase.rpc.protection", SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()), new SaslClientHandler.SaslExceptionHandler() { @Override public void handle(int retryCount, Random random, Throwable cause) { try { // Handle Sasl failure. Try to potentially get new credentials handleSaslConnectionFailure(retryCount, cause, ticket.getUGI()); // Try to reconnect AsyncRpcClient.WHEEL_TIMER.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, random.nextInt(reloginMaxBackoff) + 1, TimeUnit.MILLISECONDS); } catch (IOException | InterruptedException e) { close(e); } } }, new SaslClientHandler.SaslSuccessfulConnectHandler() { @Override public void onSuccess(Channel channel) { startHBaseConnection(channel); } }); }
/** * Retry to connect or close * * @param bootstrap to connect with * @param connectCounter amount of tries * @param e exception of fail */ private void retryOrClose(final Bootstrap bootstrap, int connectCounter, Throwable e) { if (connectCounter < client.maxRetries) { AsyncRpcClient.WHEEL_TIMER.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { connect(bootstrap); } }, client.failureSleep, TimeUnit.MILLISECONDS); } else { client.failedServers.addToFailedServers(address); close(e); } }
private void scheduleHeartbeat() { hTimeout = hashedWheelTimer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (!disabled) { session.sendHeartbeat(); scheduleHeartbeat(); } } }, heartbeatInterval, TimeUnit.SECONDS); }
public void scheduleDisconnect() { dTimeout = hashedWheelTimer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (!disabled) { if (log.isDebugEnabled()) log.debug("{} Session will be disconnected by timeout", session.getSessionId()); session.disconnect(); } } }, heartbeatTimeout, TimeUnit.SECONDS); }
private void acquireAsync(final int permits, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<String> result, final long ttl, final TimeUnit timeUnit) { if (result.isDone()) { unsubscribe(subscribeFuture); return; } long timeoutDate = calcTimeout(ttl, timeUnit); RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate); tryAcquireFuture.addListener(new FutureListener<String>() { @Override public void operationComplete(Future<String> future) throws Exception { if (!future.isSuccess()) { unsubscribe(subscribeFuture); result.tryFailure(future.cause()); return; } final Long nearestTimeout; String permitId = future.getNow(); if (permitId != null) { if (!permitId.startsWith(":")) { unsubscribe(subscribeFuture); if (!result.trySuccess(permitId)) { releaseAsync(permitId); } return; } else { nearestTimeout = Long.valueOf(permitId.substring(1)) - System.currentTimeMillis(); } } else { nearestTimeout = null; } final RedissonLockEntry entry = getEntry(); synchronized (entry) { if (entry.getLatch().tryAcquire(permits)) { acquireAsync(permits, subscribeFuture, result, ttl, timeUnit); } else { final Timeout scheduledFuture; if (nearestTimeout != null) { scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { acquireAsync(permits, subscribeFuture, result, ttl, timeUnit); } }, nearestTimeout, TimeUnit.MILLISECONDS); } else { scheduledFuture = null; } Runnable listener = new Runnable() { @Override public void run() { if (scheduledFuture != null && !scheduledFuture.cancel()) { entry.getLatch().release(); return; } acquireAsync(permits, subscribeFuture, result, ttl, timeUnit); } }; entry.addListener(listener); } } } }); }
@Override public TimerTask task() { return null; }
private void lockAsync(final long leaseTime, final TimeUnit unit, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<Void> result, final long currentThreadId) { RFuture<Long> ttlFuture = tryAcquireAsync(leaseTime, unit, currentThreadId); ttlFuture.addListener(new FutureListener<Long>() { @Override public void operationComplete(Future<Long> future) throws Exception { if (!future.isSuccess()) { unsubscribe(subscribeFuture, currentThreadId); result.tryFailure(future.cause()); return; } Long ttl = future.getNow(); // lock acquired if (ttl == null) { unsubscribe(subscribeFuture, currentThreadId); if (!result.trySuccess(null)) { unlockAsync(currentThreadId); } return; } // waiting for message final RedissonLockEntry entry = getEntry(currentThreadId); synchronized (entry) { if (entry.getLatch().tryAcquire()) { lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId); } else { final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>(); final Runnable listener = new Runnable() { @Override public void run() { if (futureRef.get() != null) { futureRef.get().cancel(); } lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId); } }; entry.addListener(listener); if (ttl >= 0) { Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { synchronized (entry) { if (entry.removeListener(listener)) { lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId); } } } }, ttl, TimeUnit.MILLISECONDS); futureRef.set(scheduledFuture); } } } } }); }
@Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { return this.timer.newTimeout(task, delay, unit); }
Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { return WHEEL_TIMER.newTimeout(task, delay, unit); }
/** * Send request. * * @param methodName * the method name * @param args * the args * @param options * the options * * @return the future< object> * * @throws InterruptedException * the interrupted exception */ synchronized Future<Object> sendRequest(String methodName, Object[] args, Map options) throws InterruptedException { long t = System.currentTimeMillis(); if (_blocked) throw new RuntimeException("send blocked"); if (_stop) return null; Map<Object, Object> headers = options; final Long id = new Long(_id); _id++; headers.put(CALL_ID_HEADER_KEY, id); final HessianProxyFuture future = new HessianProxyFuture(); future.handleCallbacks(args); final HessianRPCCallMessage message = new HessianRPCCallMessage( methodName, args, headers, null); int i = 0; while (_openCalls.size() > MAX_OPEN_CALLS && getChannel() != null) { // System.out.println("too many open calls -> wait "+i++); Thread.sleep(10); } _openCalls.put(id, future); Integer g = (Integer) options.get("group"); final Integer group = g == null ? 0 : g; long timeout = _pendingCalls.getTimeout(group); if (timeout > 0) { TimerTask task = new TimerTask() { public void run(Timeout arg0) throws Exception { _openCalls.remove(id); future.timedOut(); } }; future.setTimeout(_timer.newTimeout(task, timeout, TimeUnit.MILLISECONDS)); } Channel channel = null; /* * while ((channel = getChannel()) == null) { _lock.lock(); try { * _connected.await(100, TimeUnit.MILLISECONDS); } finally { * _lock.unlock(); } } */ channel = getChannel(); if (channel == null) throw new RuntimeException("channel closed"); while (!channel.isWritable() && channel.isActive()) { // System.out.println("channel wait call "+Thread.currentThread().getName()); Thread.sleep(100); } channel.write(message); // System.out.println("sendRequest "+(System.currentTimeMillis()-t)); return future; }
public IntervalTimer(final Timer timer, final TimerTask task, final long interval) { _timer = timer; _task = new TimerTask() { public void run(Timeout timeout) throws Exception { _lock.lock(); try { if (!timeout.equals(getTimeout())) { // System.out.println("other timeout -> ignore"); return; } // System.out.println(new Date()+" timer called " + // _name+"/"+_interval); try { task.run(timeout); } catch (Throwable ex) { ex.printStackTrace(); } if (getTimeout() != null) setTimeout(_timer.newTimeout(this, interval, TimeUnit.MILLISECONDS)); } finally { _lock.unlock(); } } }; _interval = interval; }
private void scheduleNewIdleChannelDetector(TimerTask task) { nettyTimer.newTimeout(task, cleanerPeriod, TimeUnit.MILLISECONDS); }
private Timeout newTimeout(TimerTask task, long delay) { return nettyTimer.newTimeout(task, delay, TimeUnit.MILLISECONDS); }