Search in sources :

Example 11 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project netty by netty.

the class SslHandler method safeClose.

private void safeClose(final ChannelHandlerContext ctx, final ChannelFuture flushFuture, final ChannelPromise promise) {
    if (!ctx.channel().isActive()) {
        ctx.close(promise);
        return;
    }
    final ScheduledFuture<?> timeoutFuture;
    if (!flushFuture.isDone()) {
        long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
        if (closeNotifyTimeout > 0) {
            // Force-close the connection if close_notify is not fully sent in time.
            timeoutFuture = ctx.executor().schedule(new Runnable() {

                @Override
                public void run() {
                    // May be done in the meantime as cancel(...) is only best effort.
                    if (!flushFuture.isDone()) {
                        logger.warn("{} Last write attempt timed out; force-closing the connection.", ctx.channel());
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                }
            }, closeNotifyTimeout, TimeUnit.MILLISECONDS);
        } else {
            timeoutFuture = null;
        }
    } else {
        timeoutFuture = null;
    }
    // Close the connection if close_notify is sent in time.
    flushFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
            final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
            if (closeNotifyReadTimeout <= 0) {
                // Trigger the close in all cases to make sure the promise is notified
                // See https://github.com/netty/netty/issues/2358
                addCloseListener(ctx.close(ctx.newPromise()), promise);
            } else {
                final ScheduledFuture<?> closeNotifyReadTimeoutFuture;
                if (!sslClosePromise.isDone()) {
                    closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {

                        @Override
                        public void run() {
                            if (!sslClosePromise.isDone()) {
                                logger.debug("{} did not receive close_notify in {}ms; force-closing the connection.", ctx.channel(), closeNotifyReadTimeout);
                                // Do the close now...
                                addCloseListener(ctx.close(ctx.newPromise()), promise);
                            }
                        }
                    }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
                } else {
                    closeNotifyReadTimeoutFuture = null;
                }
                // Do the close once the we received the close_notify.
                sslClosePromise.addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) throws Exception {
                        if (closeNotifyReadTimeoutFuture != null) {
                            closeNotifyReadTimeoutFuture.cancel(false);
                        }
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                });
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelException(io.netty.channel.ChannelException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 12 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project openhab1-addons by openhab.

the class RRD4jService method store.

/**
     * @{inheritDoc}
     */
@Override
public synchronized void store(final Item item, final String alias) {
    final String name = alias == null ? item.getName() : alias;
    RrdDb db = getDB(name);
    if (db != null) {
        ConsolFun function = getConsolidationFunction(db);
        long now = System.currentTimeMillis() / 1000;
        if (function != ConsolFun.AVERAGE) {
            try {
                // happens right at this spot
                if (now - 1 > db.getLastUpdateTime()) {
                    // only do it if there is not already a value
                    double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
                    if (!Double.isNaN(lastValue)) {
                        Sample sample = db.createSample();
                        sample.setTime(now - 1);
                        sample.setValue(DATASOURCE_STATE, lastValue);
                        sample.update();
                        logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name, mapToState(lastValue, item.getName()));
                    }
                }
            } catch (IOException e) {
                logger.debug("Error storing last value (again): {}", e.getMessage());
            }
        }
        try {
            Sample sample = db.createSample();
            sample.setTime(now);
            DecimalType state = (DecimalType) item.getStateAs(DecimalType.class);
            if (state != null) {
                double value = state.toBigDecimal().doubleValue();
                if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) {
                    // counter
                    // values
                    // must
                    // be
                    // adjusted
                    // by
                    // stepsize
                    value = value * db.getRrdDef().getStep();
                }
                sample.setValue(DATASOURCE_STATE, value);
                sample.update();
                logger.debug("Stored '{}' with state '{}' in rrd4j database", name, state);
            }
        } catch (IllegalArgumentException e) {
            if (e.getMessage().contains("at least one second step is required")) {
                // we try to store the value one second later
                Runnable task = new Runnable() {

                    @Override
                    public void run() {
                        store(item, name);
                    }
                };
                ScheduledFuture<?> job = scheduledJobs.get(name);
                if (job != null) {
                    job.cancel(true);
                    scheduledJobs.remove(name);
                }
                job = scheduler.schedule(task, 1, TimeUnit.SECONDS);
                scheduledJobs.put(name, job);
            } else {
                logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
            }
        } catch (Exception e) {
            logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
        }
        try {
            db.close();
        } catch (IOException e) {
            logger.debug("Error closing rrd4j database: {}", e.getMessage());
        }
    }
}
Also used : Sample(org.rrd4j.core.Sample) IOException(java.io.IOException) ScheduledFuture(java.util.concurrent.ScheduledFuture) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) IOException(java.io.IOException) ConsolFun(org.rrd4j.ConsolFun) DecimalType(org.openhab.core.library.types.DecimalType) RrdDb(org.rrd4j.core.RrdDb)

Example 13 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project spring-framework by spring-projects.

the class SimpleBrokerMessageHandlerTests method startAndStopWithHeartbeatValue.

@SuppressWarnings("unchecked")
@Test
public void startAndStopWithHeartbeatValue() throws Exception {
    ScheduledFuture future = mock(ScheduledFuture.class);
    when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).thenReturn(future);
    this.messageHandler.setTaskScheduler(this.taskScheduler);
    this.messageHandler.setHeartbeatValue(new long[] { 15000, 16000 });
    this.messageHandler.start();
    verify(this.taskScheduler).scheduleWithFixedDelay(any(Runnable.class), eq(15000L));
    verifyNoMoreInteractions(this.taskScheduler, future);
    this.messageHandler.stop();
    verify(future).cancel(true);
    verifyNoMoreInteractions(future);
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) Test(org.junit.Test)

Example 14 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project spring-framework by spring-projects.

the class DefaultStompSessionTests method receiptNotReceived.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void receiptNotReceived() throws Exception {
    TaskScheduler taskScheduler = mock(TaskScheduler.class);
    this.session.afterConnected(this.connection);
    this.session.setTaskScheduler(taskScheduler);
    AtomicReference<Boolean> notReceived = new AtomicReference<>();
    ScheduledFuture future = mock(ScheduledFuture.class);
    when(taskScheduler.schedule(any(Runnable.class), any(Date.class))).thenReturn(future);
    StompHeaders headers = new StompHeaders();
    headers.setDestination("/topic/foo");
    headers.setReceipt("my-receipt");
    Receiptable receiptable = this.session.send(headers, "payload");
    receiptable.addReceiptLostTask(() -> notReceived.set(true));
    ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
    verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull());
    Runnable scheduledTask = taskCaptor.getValue();
    assertNotNull(scheduledTask);
    assertNull(notReceived.get());
    scheduledTask.run();
    assertTrue(notReceived.get());
    verify(future).cancel(true);
    verifyNoMoreInteractions(future);
}
Also used : Receiptable(org.springframework.messaging.simp.stomp.StompSession.Receiptable) AtomicReference(java.util.concurrent.atomic.AtomicReference) TaskScheduler(org.springframework.scheduling.TaskScheduler) ScheduledFuture(java.util.concurrent.ScheduledFuture) Date(java.util.Date) Test(org.junit.Test)

Example 15 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project spring-framework by spring-projects.

the class UserRegistryMessageHandlerTests method brokerUnavailableEvent.

@SuppressWarnings("unchecked")
@Test
public void brokerUnavailableEvent() throws Exception {
    ScheduledFuture future = Mockito.mock(ScheduledFuture.class);
    when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), any(Long.class))).thenReturn(future);
    BrokerAvailabilityEvent event = new BrokerAvailabilityEvent(true, this);
    this.handler.onApplicationEvent(event);
    verifyNoMoreInteractions(future);
    event = new BrokerAvailabilityEvent(false, this);
    this.handler.onApplicationEvent(event);
    verify(future).cancel(true);
}
Also used : BrokerAvailabilityEvent(org.springframework.messaging.simp.broker.BrokerAvailabilityEvent) ScheduledFuture(java.util.concurrent.ScheduledFuture) Test(org.junit.Test)

Aggregations

ScheduledFuture (java.util.concurrent.ScheduledFuture)83 Test (org.junit.Test)27 DelegatingScheduledFutureStripper (com.hazelcast.scheduledexecutor.impl.DelegatingScheduledFutureStripper)9 ParallelTest (com.hazelcast.test.annotation.ParallelTest)9 QuickTest (com.hazelcast.test.annotation.QuickTest)9 Date (java.util.Date)9 IOException (java.io.IOException)7 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)7 Map (java.util.Map)6 TimeValue (org.elasticsearch.common.unit.TimeValue)6 None (com.linkedin.common.util.None)5 D2Client (com.linkedin.d2.balancer.D2Client)5 D2ClientBuilder (com.linkedin.d2.balancer.D2ClientBuilder)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 JSONObject (org.json.simple.JSONObject)5 IdleReaderException (com.twitter.distributedlog.exceptions.IdleReaderException)4 ExecutionException (java.util.concurrent.ExecutionException)4 Future (java.util.concurrent.Future)4