Example usage for java.util.concurrent Executors newFixedThreadPool

List of usage examples for java.util.concurrent Executors newFixedThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newFixedThreadPool.

Prototype

public static ExecutorService newFixedThreadPool(int nThreads) 

Source Link

Document

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

Usage

From source file:com.adobe.api.platform.msc.client.config.ClientConfig.java

/**
 * Used for creating http connections to 3rd party API. It's a heavy-weight object and it's useful to reuse it.
 *
 * @return A JaxRS Client instance/*  w  w  w  .j  a  va 2s . c o  m*/
 */
@Bean
public Client getJaxrsClient() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Ignore differences between given hostname and certificate hostname
        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(null, trustAllCerts, null);

        ResteasyClientBuilder builder = new ResteasyClientBuilder().sslContext(ctx)
                .register(JacksonConfig.class)
                .hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY);

        //if not set, builder sets a pool with 10 threads
        if (workerThreadPooSize != null) {
            // if necessary expose the thread pool as bean (reuse the same thread pool for other scenarios).
            builder.asyncExecutor(Executors.newFixedThreadPool(workerThreadPooSize));
        }

        if (connectionPoolSize != null) {
            builder.connectionPoolSize(connectionPoolSize);
        }

        if (connectionTTL != null) {
            builder.connectionTTL(connectionTTL, TimeUnit.SECONDS);
        }

        if (socketTimeout != null) {
            builder.socketTimeout(socketTimeout, TimeUnit.SECONDS);
        }

        return builder.build();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wisc.cs407project.ImageLoader.ImageLoader.java

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
}

From source file:ai.grakn.engine.tasks.manager.StandaloneTaskManager.java

public StandaloneTaskManager(EngineID engineId) {
    this.engineID = engineId;
    instantiatedTasks = new ConcurrentHashMap<>();
    stateStorage = new TaskStateInMemoryStore();
    stateUpdateLock = new ReentrantLock();

    ConfigProperties properties = ConfigProperties.getInstance();
    schedulingService = Executors.newScheduledThreadPool(1);
    executorService = Executors.newFixedThreadPool(properties.getAvailableThreads());
}

From source file:com.seajas.search.codex.service.task.ExpirationNotifierTask.java

/**
 * Send out the actual notification e-mails.
 *//*from   w w w .j a  v  a2s .  co  m*/
public void send() {
    if (Boolean.getBoolean("com.seajas.search.codex.notifications.disabled")) {
        logger.info(
                "Notifications have been explicitly disabled using 'com.seajas.search.codex.notifications.disabled=true'. Skipping notification expiration checks.");

        return;
    }

    logger.info("Started expiration notifier task");

    // Also use a regular date for reference, to pass to the search engine

    final Date currentDate = new Date();

    // Retrieve the list of profile profiles to attend to

    List<Identity> identities = codexService.getNotifiableIdentities(currentDate);

    if (identities.size() == 0) {
        logger.info("No notifiable identities found - finishing expiration notifier task");

        return;
    }

    // Now process the profiles using a thread-pool of at most threadMaximum threads

    ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(identities.size(), threadMaximum));

    for (final Identity identity : identities)
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                List<IdentityAccount> accounts = codexService.getNotifiableAccounts(currentDate,
                        identity.getAccounts());

                for (IdentityAccount account : accounts) {
                    // Retrieve the most recently expired unreported token

                    IdentityAccountToken relevantToken = null;

                    for (IdentityAccountToken token : account.getTokens())
                        if (token.getExpireTime() > currentDate.getTime() && !token.getIsReported()) {
                            relevantToken = token;

                            break;
                        }

                    if (relevantToken == null) {
                        logger.error(
                                "No relevant token could be found - despite this account having been found to be notifiable");

                        break;
                    }

                    // Take the subject in the given language, or resort to the default language if it doesn't exist (yet)

                    String subject = null;

                    try {
                        subject = messageSource.getMessage("mail.result.subject.token.expired", null,
                                new Locale(identity.getNotifierLanguage()));
                    } catch (NoSuchMessageException e) {
                        logger.warn("Could not retrieve results message subject header in language "
                                + identity.getNotifierLanguage() + ", resorting to the default language "
                                + codexService.getDefaultApplicationLanguage());

                        subject = messageSource.getMessage("mail.confirmation.subject", null,
                                new Locale(codexService.getDefaultApplicationLanguage()));
                    }

                    // And send out the actual e-mail

                    if (!mailService.sendMessage(identity.getNotifierEmail(), subject, "TODO"))
                        logger.error(
                                "Could not e-mail the notification expiration message - attender failed to send message.");

                    // Update the processed subscribers' lastNotification indicator

                    codexService.markAccountNotified(account);
                }
            }
        });

    logger.info("Finishing expiration notifier task");
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {/*from   w  w  w  . j a  v a2s  .  c  o m*/
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();

                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server = new TestingServer(server.getPort(), server.getTempDirectory());
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.svds.genericconsumer.main.GenericConsumerGroup.java

/**
 * Create Kafka message streams to and spawn threads of Consumer objects to
 * listen to Kafka streams/*from  w  w  w  .  j  av  a 2  s .c om*/
 * 
 * @param topic         Kafka topic to listen to
 * @param numThreads    Number of Kafka listener threads to spawn
 * @param consumerClass Implementing class of consumer object
 * @param parameters    Optional parameters for consumer object
 * @throws IOException 
 */
public void run(String topic, int numThreads, String consumerClass, String[] parameters) throws IOException {
    try {
        LOG.info("HELLO from run");

        Map<String, Integer> topicCountMap = new HashMap<>();
        topicCountMap.put(topic, numThreads);
        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer
                .createMessageStreams(topicCountMap);
        List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);

        // now launch all the threads
        //
        executor = Executors.newFixedThreadPool(numThreads);

        // now create an object to consume the messages
        //
        int threadNumber = 0;
        for (final KafkaStream stream : streams) {
            Consumer consumerObject = (Consumer) Class.forName(consumerClass).newInstance();
            consumerObject.init(stream, threadNumber, parameters);
            executor.submit(consumerObject);
            threadNumber++;
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        LOG.error("Error running threads in GenericConsumerGroup");
        throw new IOException(ex);
    }
}

From source file:com.googlecode.jcasockets.perf.Client.java

public void execute() throws InterruptedException, ExecutionException {
    int numberOfThreads = clientOptions.getNumberOfThreads();
    String ipAddress = clientOptions.getIpAddress();
    List<Integer> ports = clientOptions.getPorts();
    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
    try {/*from  w  w  w.  j  ava  2 s .  c  om*/
        Collection<Callable<ExecutionStatistics>> senderTestRunners = new ArrayList<Callable<ExecutionStatistics>>(
                numberOfThreads);
        for (Integer port : ports) {
            for (int i = 0; i < numberOfThreads; i++) {
                SocketSender socketSender = socketSenderFactory.createSocketSender(ipAddress, port);
                senderTestRunners.add(new SenderTestRunner(clientOptions, socketSender));
            }
        }
        List<Future<ExecutionStatistics>> executionStatisticsFutures = executorService
                .invokeAll(senderTestRunners);
        executionStatistics = new ExecutionStatistics(null);
        for (Future<ExecutionStatistics> future : executionStatisticsFutures) {
            ExecutionStatistics that = future.get();
            executionStatistics.combine(that);
        }
    } finally {
        executorService.shutdown();
    }
}

From source file:edu.vt.middleware.cas.ldap.LoadDriver.java

public LoadDriver(final int sampleCount, final int workerCount, final File credentialsFile,
        final ApplicationContext context) {

    this.credentialsFile = credentialsFile;
    this.resultExecutor = Executors.newSingleThreadExecutor();
    this.workExecutor = Executors.newFixedThreadPool(workerCount);
    this.context = context;
    final AuthenticationHandler handler = this.context.getBean(AuthenticationHandler.class);
    if (handler == null) {
        throw new IllegalStateException("AuthenticationHandler bean not found.");
    }//from ww w .  j  a va2  s .c  o m
    if (!handler.supports(new UsernamePasswordCredentials())) {
        throw new IllegalStateException("AuthenticationHandler bean does not support password authentication");
    }
    this.state.setWorkQueue(new ArrayBlockingQueue<UsernamePasswordCredentials>(sampleCount));
    this.state.setResultQueue(new ArrayBlockingQueue<Sample>(sampleCount));
    this.state.setAuthenticationHandler(handler);
}

From source file:com.fonoster.astive.server.AstiveServer.java

public AstiveServer(int port, int backlog, InetAddress bindAddr) throws SystemException, IOException {
    super(port, backlog, bindAddr);
    // A separate thread for services: Admin , Astive  and Telnet.
    executorService = Executors.newFixedThreadPool(3);
}

From source file:com.apress.prospringintegration.customadapters.inbound.eventdriven.fsmon.LinuxInotifyDirectoryMonitor.java

@Override
public void afterPropertiesSet() throws Exception {
    if (this.executor == null) {
        this.executor = Executors.newFixedThreadPool(10);
    }//www .  j  a va  2  s  .  co m
}