Search in sources :

Example 31 with ScheduledExecutorService

use of java.util.concurrent.ScheduledExecutorService in project OpenAM by OpenRock.

the class ThreadMonitorTest method mockNoOpScheduledExecutor.

private ScheduledExecutorService mockNoOpScheduledExecutor() {
    ScheduledExecutorService r = mock(ScheduledExecutorService.class);
    given(r.scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))).willReturn(mock(ScheduledFuture.class));
    return r;
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TimeUnit(java.util.concurrent.TimeUnit) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 32 with ScheduledExecutorService

use of java.util.concurrent.ScheduledExecutorService in project voltdb by VoltDB.

the class LatencyLogger method main.

public static void main(String[] args) throws Exception {
    final String hostname;
    if (args.length == 1) {
        readHistogramFromFile(args[0]);
        return;
    }
    if (args.length != 3) {
        if (args.length == 4) {
            hostname = args[3];
        } else {
            System.out.println(usage());
            return;
        }
    } else {
        hostname = args[0];
    }
    final String server = args[0];
    int dur = 0;
    try {
        dur = Integer.valueOf(args[2]);
        if (dur < 1) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        System.out.println("reportIntervalSeconds should be greater than or equal to 1");
        System.out.println(usage());
        System.exit(0);
    }
    final int duration = dur;
    // start with an empty password
    String username = "";
    String password = "";
    // if credentials set in env, use them
    if (System.getenv().containsKey("VOLTDBUSER")) {
        username = System.getenv("VOLTDBUSER");
    }
    if (System.getenv().containsKey("VOLTDBPASSWORD")) {
        password = System.getenv("VOLTDBPASSWORD");
    }
    // create the client with our credentials
    ClientConfig clientConfig = new ClientConfig(username, password);
    final Client c = ClientFactory.createClient(clientConfig);
    int port = 0;
    try {
        port = Integer.valueOf(args[1]);
    } catch (NumberFormatException e) {
        System.out.println("Failed to parse port number.");
        System.out.println("Usage server port reportIntervalSeconds");
        System.exit(0);
    }
    System.out.println("Connecting to " + server + " port " + port);
    c.createConnection(args[0], port);
    System.out.printf("%12s, %10s, %10s, %10s, %10s, %10s, %10s, %10s\n", "TIMESTAMP", "COUNT", "TPS", "95", "99", "99.9", "99.99", "99.999");
    final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    ses.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            VoltTable table = null;
            try {
                table = c.callProcedure("@Statistics", "LATENCY_HISTOGRAM", 0).getResults()[0];
            } catch (IOException | ProcCallException e) {
                System.out.println("Failed to get statistics:");
                e.printStackTrace();
                System.exit(0);
            }
            List<String> hostnames = new ArrayList<String>();
            String tableHostname = "";
            while (!hostname.equalsIgnoreCase(tableHostname)) {
                if (!table.advanceRow()) {
                    System.out.println("Server host name " + server + " not found. Valid host names are " + hostnames.toString());
                    System.exit(0);
                }
                tableHostname = table.getString(2);
                hostnames.add(tableHostname);
            }
            Date now = new Date(table.getLong(0));
            Histogram newHistogram = AbstractHistogram.fromCompressedBytes(table.getVarbinary(4), CompressionStrategySnappy.INSTANCE);
            Histogram diffHistogram;
            if (m_histogramData == null) {
                diffHistogram = newHistogram;
            } else {
                diffHistogram = Histogram.diff(newHistogram, m_histogramData);
            }
            long totalCount = diffHistogram.getTotalCount();
            if (totalCount > 0) {
                System.out.printf("%12s, %10d, %10.0f, %8.2fms, %8.2fms, %8.2fms, %8.2fms, %8.2fms\n", sdf.format(now), totalCount, ((double) totalCount / duration), (diffHistogram.getValueAtPercentile(95.0D) / 1000.0D), (diffHistogram.getValueAtPercentile(99) / 1000.0D), (diffHistogram.getValueAtPercentile(99.9) / 1000.0D), (diffHistogram.getValueAtPercentile(99.99) / 1000.0D), (diffHistogram.getValueAtPercentile(99.999) / 1000.0D));
            } else {
                System.out.printf("%12s, %10d, %10d, %8.2fms, %8.2fms, %8.2fms, %8.2fms, %8.2fms\n", sdf.format(now), totalCount, 0, 0D, 0D, 0D, 0D, 0D);
            }
            m_histogramData = AbstractHistogram.fromCompressedBytes(table.getVarbinary(4), CompressionStrategySnappy.INSTANCE);
            ;
        }
    }, 0, duration, TimeUnit.SECONDS);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AbstractHistogram(org.HdrHistogram_voltpatches.AbstractHistogram) Histogram(org.HdrHistogram_voltpatches.Histogram) VoltTable(org.voltdb.VoltTable) Date(java.util.Date) ArrayList(java.util.ArrayList) List(java.util.List) ClientConfig(org.voltdb.client.ClientConfig) Client(org.voltdb.client.Client) SimpleDateFormat(java.text.SimpleDateFormat)

Example 33 with ScheduledExecutorService

use of java.util.concurrent.ScheduledExecutorService in project jersey by jersey.

the class ParallelTest method testParallel.

@Test
public void testParallel() throws BrokenBarrierException, InterruptedException, TimeoutException {
    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(PARALLEL_CLIENTS);
    try {
        final WebTarget target = target();
        for (int i = 1; i <= PARALLEL_CLIENTS; i++) {
            final int id = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    try {
                        startBarrier.await();
                        Response response;
                        response = target.path(PATH).request().get();
                        assertEquals("GET", response.readEntity(String.class));
                        receivedCounter.incrementAndGet();
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                        LOGGER.log(Level.WARNING, "Client thread " + id + " interrupted.", ex);
                    } catch (BrokenBarrierException ex) {
                        LOGGER.log(Level.INFO, "Client thread " + id + " failed on broken barrier.", ex);
                    } catch (Throwable t) {
                        t.printStackTrace();
                        LOGGER.log(Level.WARNING, "Client thread " + id + " failed on unexpected exception.", t);
                    } finally {
                        doneLatch.countDown();
                    }
                }
            });
        }
        startBarrier.await(1, TimeUnit.SECONDS);
        assertTrue("Waiting for clients to finish has timed out.", doneLatch.await(5 * getAsyncTimeoutMultiplier(), TimeUnit.SECONDS));
        assertEquals("Resource counter", PARALLEL_CLIENTS, resourceCounter.get());
        assertEquals("Received counter", PARALLEL_CLIENTS, receivedCounter.get());
    } finally {
        executor.shutdownNow();
        Assert.assertTrue("Executor termination", executor.awaitTermination(5, TimeUnit.SECONDS));
    }
}
Also used : Response(javax.ws.rs.core.Response) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) WebTarget(javax.ws.rs.client.WebTarget) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 34 with ScheduledExecutorService

use of java.util.concurrent.ScheduledExecutorService in project wildfly by wildfly.

the class InfinispanBeanManagerFactory method createBeanManager.

@Override
public BeanManager<I, T, TransactionBatch> createBeanManager(IdentifierFactory<I> identifierFactory, PassivationListener<T> passivationListener, RemoveListener<T> removeListener) {
    MarshallingContext context = new SimpleMarshallingContextFactory().createMarshallingContext(this.configuration.getMarshallingConfigurationRepository(), this.configuration.getBeanContext().getClassLoader());
    MarshalledValueFactory<MarshallingContext> factory = new SimpleMarshalledValueFactory(context);
    Cache<BeanKey<I>, BeanEntry<I>> beanCache = this.configuration.getCache();
    Cache<BeanGroupKey<I>, BeanGroupEntry<I, T>> groupCache = this.configuration.getCache();
    final CacheProperties properties = new InfinispanCacheProperties(groupCache.getCacheConfiguration());
    final String beanName = this.configuration.getBeanContext().getBeanName();
    BeanGroupFactory<I, T> groupFactory = new InfinispanBeanGroupFactory<>(groupCache, beanCache, factory, context, properties);
    Configuration<BeanGroupKey<I>, BeanGroupEntry<I, T>, BeanGroupFactory<I, T>> groupConfiguration = new SimpleConfiguration<>(groupCache, groupFactory);
    BeanFactory<I, T> beanFactory = new InfinispanBeanFactory<>(beanName, groupFactory, beanCache, properties, this.configuration.getBeanContext().getTimeout(), properties.isPersistent() ? passivationListener : null);
    Configuration<BeanKey<I>, BeanEntry<I>, BeanFactory<I, T>> beanConfiguration = new SimpleConfiguration<>(beanCache, beanFactory);
    final NodeFactory<Address> nodeFactory = this.configuration.getNodeFactory();
    final Registry<String, ?> registry = this.configuration.getRegistry();
    final KeyAffinityServiceFactory affinityFactory = this.configuration.getKeyAffinityServiceFactory();
    final CommandDispatcherFactory dispatcherFactory = this.configuration.getCommandDispatcherFactory();
    final Time timeout = this.configuration.getBeanContext().getTimeout();
    final ScheduledExecutorService scheduler = this.configuration.getScheduler();
    final ExpirationConfiguration<T> expiration = new ExpirationConfiguration<T>() {

        @Override
        public Time getTimeout() {
            return timeout;
        }

        @Override
        public RemoveListener<T> getRemoveListener() {
            return removeListener;
        }

        @Override
        public ScheduledExecutorService getExecutor() {
            return scheduler;
        }
    };
    final Executor executor = this.configuration.getExecutor();
    final BeanPassivationConfiguration passivationConfig = this.configuration.getPassivationConfiguration();
    final PassivationConfiguration<T> passivation = new PassivationConfiguration<T>() {

        @Override
        public PassivationListener<T> getPassivationListener() {
            return passivationListener;
        }

        @Override
        public BeanPassivationConfiguration getConfiguration() {
            return passivationConfig;
        }

        @Override
        public Executor getExecutor() {
            return executor;
        }
    };
    InfinispanBeanManagerConfiguration<T> configuration = new InfinispanBeanManagerConfiguration<T>() {

        @Override
        public String getBeanName() {
            return beanName;
        }

        @Override
        public KeyAffinityServiceFactory getAffinityFactory() {
            return affinityFactory;
        }

        @Override
        public Registry<String, ?> getRegistry() {
            return registry;
        }

        @Override
        public NodeFactory<Address> getNodeFactory() {
            return nodeFactory;
        }

        @Override
        public CommandDispatcherFactory getCommandDispatcherFactory() {
            return dispatcherFactory;
        }

        @Override
        public ExpirationConfiguration<T> getExpirationConfiguration() {
            return expiration;
        }

        @Override
        public PassivationConfiguration<T> getPassivationConfiguration() {
            return passivation;
        }

        @Override
        public CacheProperties getProperties() {
            return properties;
        }
    };
    return new InfinispanBeanManager<>(configuration, identifierFactory, beanConfiguration, groupConfiguration);
}
Also used : InfinispanBeanGroupFactory(org.wildfly.clustering.ejb.infinispan.group.InfinispanBeanGroupFactory) Address(org.infinispan.remoting.transport.Address) Time(org.wildfly.clustering.ejb.Time) BeanPassivationConfiguration(org.wildfly.clustering.ejb.BeanPassivationConfiguration) InfinispanCacheProperties(org.wildfly.clustering.ee.infinispan.InfinispanCacheProperties) CacheProperties(org.wildfly.clustering.ee.infinispan.CacheProperties) Executor(java.util.concurrent.Executor) SimpleMarshallingContextFactory(org.wildfly.clustering.marshalling.jboss.SimpleMarshallingContextFactory) InfinispanBeanFactory(org.wildfly.clustering.ejb.infinispan.bean.InfinispanBeanFactory) CommandDispatcherFactory(org.wildfly.clustering.dispatcher.CommandDispatcherFactory) MarshallingContext(org.wildfly.clustering.marshalling.jboss.MarshallingContext) InfinispanBeanGroupFactory(org.wildfly.clustering.ejb.infinispan.group.InfinispanBeanGroupFactory) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InfinispanBeanFactory(org.wildfly.clustering.ejb.infinispan.bean.InfinispanBeanFactory) BeanPassivationConfiguration(org.wildfly.clustering.ejb.BeanPassivationConfiguration) KeyAffinityServiceFactory(org.wildfly.clustering.infinispan.spi.affinity.KeyAffinityServiceFactory) SimpleMarshalledValueFactory(org.wildfly.clustering.marshalling.jboss.SimpleMarshalledValueFactory) InfinispanCacheProperties(org.wildfly.clustering.ee.infinispan.InfinispanCacheProperties)

Example 35 with ScheduledExecutorService

use of java.util.concurrent.ScheduledExecutorService in project wildfly by wildfly.

the class RemoveOnCancelScheduledExecutorServiceBuilder method build.

@Override
public ServiceBuilder<ScheduledExecutorService> build(ServiceTarget target) {
    Function<ScheduledExecutorService, ScheduledExecutorService> mapper = executor -> JBossExecutors.protectedScheduledExecutorService(executor);
    Supplier<ScheduledExecutorService> supplier = () -> {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(this.size, this.factory);
        executor.setRemoveOnCancelPolicy(true);
        executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        return executor;
    };
    Service<ScheduledExecutorService> service = new SuppliedValueService<>(mapper, supplier, ScheduledExecutorService::shutdown);
    return new AsynchronousServiceBuilder<>(this.name, service).startSynchronously().build(target).setInitialMode(ServiceController.Mode.ON_DEMAND);
}
Also used : Service(org.jboss.msc.service.Service) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) AsynchronousServiceBuilder(org.wildfly.clustering.service.AsynchronousServiceBuilder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) SuppliedValueService(org.wildfly.clustering.service.SuppliedValueService) ServiceController(org.jboss.msc.service.ServiceController) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ServiceName(org.jboss.msc.service.ServiceName) ServiceTarget(org.jboss.msc.service.ServiceTarget) JBossExecutors(org.jboss.threads.JBossExecutors) ThreadFactory(java.util.concurrent.ThreadFactory) Builder(org.wildfly.clustering.service.Builder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) SuppliedValueService(org.wildfly.clustering.service.SuppliedValueService)

Aggregations

ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)821 Test (org.junit.Test)267 CountDownLatch (java.util.concurrent.CountDownLatch)79 ArrayList (java.util.ArrayList)72 Test (org.testng.annotations.Test)72 IOException (java.io.IOException)71 ExecutorService (java.util.concurrent.ExecutorService)70 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)65 HashMap (java.util.HashMap)57 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)53 List (java.util.List)51 Map (java.util.Map)51 TimeUnit (java.util.concurrent.TimeUnit)44 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)43 ThreadFactory (java.util.concurrent.ThreadFactory)40 CompletableFuture (java.util.concurrent.CompletableFuture)35 UUID (java.util.UUID)34 Cleanup (lombok.Cleanup)31 ExecutionException (java.util.concurrent.ExecutionException)30 HashSet (java.util.HashSet)25