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:api.startup.PDFIndexer.java

/**
 * Indexes all the documents in the CSV file
 * @param writer - index writer/*  ww w .  j a  v a  2s  . co  m*/
 * @param indexConfiguration - the configuration for all the indexable documents
 * @throws IOException
 */
static void indexDocs(final IndexWriter writer, String indexConfiguration) throws IOException {
    Reader in = new FileReader(indexConfiguration);
    CSVParser parser = CSVFormat.RFC4180.withHeader().parse(in);
    List<Callable<Object>> tasks = new ArrayList<>();
    int threadPoolSize = Runtime.getRuntime().availableProcessors();
    log.info("Indexing with " + threadPoolSize + " processors");
    ExecutorService pool = Executors.newFixedThreadPool(threadPoolSize);
    for (CSVRecord record : parser) {
        DocumentMetadata meta = new DocumentMetadata(record);
        tasks.add(() -> {
            indexDoc(writer, meta);
            return null;
        });
    }

    try {
        pool.invokeAll(tasks);
    } catch (InterruptedException e) {
        log.error("Indexing was interrupted " + e.getMessage());
    }

}

From source file:com.cloverstudio.spika.utils.BitmapManager.java

BitmapManager() {
    cache = new HashMap<String, SoftReference<Bitmap>>();
    pool = Executors.newFixedThreadPool(5);
}

From source file:com.otz.transport.consumer.dispatcher.LogEventDispatcher.java

@PostConstruct
public void init() {
    if (loadedPlugins.getNames().contains(LOG)) {
        String numberOfThreads = environment.getProperty(environment.getActiveProfiles()[0] + SERVICES + LOG);

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            LogEventRunnable logEventRunnable = new LogEventRunnable(this, kafkaProperties, 200);
            listeners.add(logEventRunnable);
            executorService.submit(logEventRunnable);
        }/*from w ww. j ava2 s.  co m*/

    }
}

From source file:com.developmentsprint.spring.breaker.hystrix.HystrixAnnotationDrivenConcreteClassTest.java

@Test
public void testMaxConcurrency() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(20);
    List<Future<String>> futures = new ArrayList<Future<String>>();
    for (int i = 0; i < 20; i++) {
        futures.add(executor.submit(new Callable<String>() {
            @Override//  w  ww.  j  ava 2 s  .  c  om
            public String call() throws Exception {
                return methods.getText();
            }
        }));
    }

    Thread.sleep(500L);

    int successes = 0;
    int rejections = 0;
    for (Future<String> future : futures) {
        try {
            future.get();
            successes++;
        } catch (Exception e) {
            rejections++;
        }
    }

    assertThat(successes).isEqualTo(10);
    assertThat(rejections).isEqualTo(10);
}

From source file:com.mobilyzer.AccountSelector.java

public AccountSelector(Context context) {
    this.context = context;
    this.checkinExecutor = Executors.newFixedThreadPool(1);
    this.phoneUtils = PhoneUtils.getPhoneUtils();
}

From source file:com.precioustech.fxtrading.tradingbot.strategies.CopyTwitterStrategy.java

@PostConstruct
public void init() {
    this.executorService = Executors.newFixedThreadPool(1);
}

From source file:org.apache.camel.component.http4.HttpConcurrentTest.java

private void doSendMessages(int files, int poolSize) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    // we access the responses Map below only inside the main thread,
    // so no need for a thread-safe Map implementation
    Map<Integer, Future<String>> responses = new HashMap<Integer, Future<String>>();
    for (int i = 0; i < files; i++) {
        final int index = i;
        Future<String> out = executor.submit(new Callable<String>() {
            public String call() throws Exception {
                return template.requestBody("http4://" + getHostName() + ":" + getPort(), null, String.class);
            }//from  w w w. j  a v  a 2 s  . c  o  m
        });
        responses.put(index, out);
    }

    assertEquals(files, responses.size());

    // get all responses
    Set<String> unique = new HashSet<String>();
    for (Future<String> future : responses.values()) {
        unique.add(future.get());
    }

    // should be 'files' unique responses
    assertEquals("Should be " + files + " unique responses", files, unique.size());
    executor.shutdownNow();
}

From source file:com.otz.transport.consumer.dispatcher.ApplicationEventDispatcher.java

@PostConstruct
public void init() {
    if (loadedPlugins.getNames().contains(APPLICATION)) {
        String numberOfThreads = environment
                .getProperty(environment.getActiveProfiles()[0] + SERVICES + APPLICATION);

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            ApplicationEventRunnable applicationEventRunnable = new ApplicationEventRunnable(this,
                    kafkaProperties, 200);
            listeners.add(applicationEventRunnable);
            executorService.submit(applicationEventRunnable);
        }/*from   www. j  a  v a2s . c  o  m*/

    }
}

From source file:org.openspaces.rest.space.SpaceTaskAPIController.java

private ModelAndView execute(String spaceName, String locators, final SpaceTaskRequest request) {
    GigaSpace space = ControllerUtils.xapCache.get(spaceName, locators);
    final int instanceCount = ControllerUtils.xapCache.getInstances(spaceName);
    ExecutorService svc = Executors.newFixedThreadPool(instanceCount);
    int instances = 0;

    log.fine("request.target=" + request.target);
    if (request.target != null && !request.target.equals("all")) {
        instances = 1;//from  w  w w .  j a  v a2 s .  co  m
    } else {
        instances = instanceCount;
    }

    System.out.println("instances=" + instances);

    List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(instances);
    for (int i = 0; i < instances; i++) {
        Object routing = 0;
        if (request.target != null && request.target.equals("all")) {
            routing = i;
        } else {
            routing = request.target;
        }
        tasks.add(new ScriptCallable(space, request, routing));
    }

    ModelAndView mv = new ModelAndView("jsonView");
    List<Object> model = new ArrayList<Object>(instances);
    try {
        List<Future<Object>> results = svc.invokeAll(tasks);

        for (Future<Object> fut : results) {
            if (fut.get() != null)
                model.add(fut.get());
        }
        mv.addObject("results", model);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        svc.shutdownNow();
    }
    return mv;
}

From source file:ch.ralscha.extdirectspring.controller.ConfigurationService.java

@Override
public void afterPropertiesSet() {

    if (configuration == null) {
        configuration = new Configuration();
    }/*from   w  w w  .ja v  a  2 s.com*/

    if (configuration.getJsonHandler() != null) {
        jsonHandler = configuration.getJsonHandler();
    }

    if (jsonHandler == null) {
        jsonHandler = new JsonHandler();
    }

    if (routerExceptionHandler == null) {
        routerExceptionHandler = new DefaultRouterExceptionHandler(this);
    }

    if (configuration.getBatchedMethodsExecutionPolicy() == BatchedMethodsExecutionPolicy.CONCURRENT
            && configuration.getBatchedMethodsExecutorService() == null) {
        configuration.setBatchedMethodsExecutorService(Executors.newFixedThreadPool(5));
    }

    if (configuration.getConversionService() == null) {
        Map<String, ConversionService> conversionServices = context.getBeansOfType(ConversionService.class);
        if (conversionServices.isEmpty()) {
            configuration.setConversionService(new DefaultFormattingConversionService());
        } else if (conversionServices.size() == 1) {
            configuration.setConversionService(conversionServices.values().iterator().next());
        } else {
            if (conversionServices.containsKey("mvcConversionService")) {
                configuration.setConversionService(conversionServices.get("mvcConversionService"));
            } else {
                for (ConversionService conversionService : conversionServices.values()) {
                    if (conversionService instanceof FormattingConversionService) {
                        configuration.setConversionService(conversionService);
                        break;
                    }
                }
                if (configuration.getConversionService() == null) {
                    configuration.setConversionService(conversionServices.values().iterator().next());
                }
            }
        }
    }

    Collection<WebArgumentResolver> webResolvers = context.getBeansOfType(WebArgumentResolver.class).values();
    parametersResolver = new ParametersResolver(configuration.getConversionService(), jsonHandler,
            webResolvers);
}