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:net.oddsoftware.android.feedscribe.data.Downloader.java

private Downloader(Context ctx) {
    mContext = ctx;/*from w w  w  . j  av a 2  s  .co m*/

    mThreadPool = Executors.newFixedThreadPool(4);

    mFeedManager = FeedManager.getInstance(mContext);

    mDownloadCount = 0;

    mWakeLock = ((PowerManager) ctx.getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FeedScribe.Downloader");
    mWakeLock.setReferenceCounted(false);

    mAwakeChecker = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(mAwakeInterval);
                    checkAwake();
                }
            } catch (InterruptedException exc) {
                return;
            }
        }
    };

    mAwakeChecker.start();
}

From source file:com.uber.hoodie.func.TestBoundedInMemoryQueue.java

@Before
public void beforeTest() {
    this.executorService = Executors.newFixedThreadPool(2);
}

From source file:com.ctrip.infosec.rule.executor.ModelRulesExecutorService.java

@PostConstruct
public void dequeue() {
    int threads = 1;
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < threads; i++) {
        executor.submit(new Runnable() {
            @Override//from   w ww .j av  a  2s . c o  m
            public void run() {
                while (true) {
                    RiskFact fact = null;
                    beforeInvoke("ModelRules.execute");
                    try {
                        fact = queue.take();
                        TraceLogger.beginTrans(fact.eventId);
                        TraceLogger.setParentTransId(
                                valueAsString(fact.ext, Constants.key_traceLoggerParentTransId));
                        fact.ext.remove(Constants.key_traceLoggerParentTransId);
                        execute(fact);
                    } catch (Exception ex) {
                        fault("ModelRules.execute");
                        logger.error("dequeue exception.", ex);
                    } finally {
                        afterInvoke("ModelRules.execute");
                        if (fact != null) {
                            TraceLogger.commitTrans();
                        }
                        Threads.sleep(10, TimeUnit.MILLISECONDS);
                    }
                }
            }
        });
    }
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            int size = queue.size();
            if (size > 0) {
                SarsMqStatRepository.put("MODEL_EXECUTE_QUEUE", size);
                logger.warn("queue size: " + size);
            }
            int max = 10000;
            if (size > max) {
                do {
                    RiskFact fact = queue.poll();
                    logger.warn("model queue is full. drop message: " + fact.eventId);
                } while (queue.size() > max);
            }
        }
    }, 30, 30, TimeUnit.SECONDS);
}

From source file:com.alibaba.otter.manager.biz.common.alarm.AbstractAlarmService.java

public void afterPropertiesSet() throws Exception {
    executor = Executors.newFixedThreadPool(1);
    executor.submit(new Runnable() {

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                sendAlarmInternal();/*from w w w .  ja  va 2 s .c om*/
                LockSupport.parkNanos(period * 1000L * 1000L);
            }
        }
    });
}

From source file:de.cuseb.bilderbuch.images.ImageSearchService.java

public ImageResponse searchImages(final String query) {

    final ImageResponse response = new ImageResponse();
    final ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(searches.size()));

    for (final ImageSearch search : searches.values()) {

        if (!search.isEnabled()) {
            continue;
        }/*w  w w.j  a  v a  2 s.com*/

        ListenableFuture<List<Image>> searchResult = executor.submit(new Callable<List<Image>>() {
            @Override
            public List<Image> call() throws Exception {
                log.debug("starting enabled search " + search.getClass().getSimpleName());
                return search.searchImages(query);
            }
        });

        Futures.addCallback(searchResult, new FutureCallback<List<Image>>() {
            @Override
            public void onSuccess(List<Image> result) {
                log.debug(search.getClass().getSimpleName() + " result size: " + result.size());
                response.addImages(result);
            }

            @Override
            public void onFailure(Throwable t) {
                log.error(search.getClass().getSimpleName(), t);
            }
        });
    }

    try {
        executor.shutdown();
        executor.awaitTermination(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error("awaitTermination interrupted", e);
    }

    if (shuffle) {
        log.debug("shuffling result");
        response.shuffle();
    }

    return response;
}

From source file:com.flipkart.bifrost.CommunicationTest.java

@Test
public void testSendReceive() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    Connection connection = new Connection(Lists.newArrayList("localhost"), "guest", "guest");
    connection.start();//from w ww  .j a va2  s .  c om

    BifrostExecutor<Void> executor = BifrostExecutor.<Void>builder(TestAction.class).connection(connection)
            .objectMapper(mapper).requestQueue("bifrost-send").responseQueue("bifrost-recv").concurrency(10)
            .executorService(Executors.newFixedThreadPool(10)).build();

    BifrostRemoteCallExecutionServer<Void> executionServer = BifrostRemoteCallExecutionServer
            .<Void>builder(TestAction.class).objectMapper(mapper).connection(connection).concurrency(10)
            .requestQueue("bifrost-send").build();
    executionServer.start();

    long startTime = System.currentTimeMillis();
    AtomicInteger counter = new AtomicInteger(0);
    int requestCount = 100;
    CompletionService<Void> ecs = new ExecutorCompletionService<>(Executors.newFixedThreadPool(50));
    List<Future<Void>> futures = Lists.newArrayListWithCapacity(requestCount);
    for (int i = 0; i < requestCount; i++) {
        futures.add(ecs.submit(new ServiceCaller(executor, counter)));
    }
    for (int i = 0; i < requestCount; i++) {
        try {
            ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    System.out.println(
            String.format("Completed: %d in %d ms", counter.get(), (System.currentTimeMillis() - startTime)));
    executor.shutdown();
    executionServer.stop();
    connection.stop();

    Assert.assertEquals(requestCount, counter.get());
}

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

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

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            ErrorEventRunnable errorEventRunnable = new ErrorEventRunnable(this, kafkaProperties, 200);
            listeners.add(errorEventRunnable);
            executorService.submit(errorEventRunnable);
        }/*  w  ww .ja  va  2  s. c o m*/

    }
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

public ApacheSdkHttpClient() {
    initDefaultClient();
    threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
}

From source file:com.esri.geoevent.test.performance.kafka.KafkaConsumerGroup.java

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

    // now launch all the threads
    ////w w w .j  a  v a 2s.c om
    executor = Executors.newFixedThreadPool(numThreads);

    // now create an object to consume the messages
    //
    int threadNumber = 0;
    for (final KafkaStream stream : streams) {
        executor.submit(new ConsumerThread(stream, receiveGeoEvent, threadNumber));
        threadNumber++;
    }
}

From source file:org.kordamp.javatrove.chat03.client.AppModule.java

protected void bindExecutorService() {
    bind(ExecutorService.class).toInstance(Executors.newFixedThreadPool(2));
}