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, ThreadFactory threadFactory) 

Source Link

Document

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed.

Usage

From source file:com.haulmont.cuba.core.UniqueNumbersTest.java

@Test
public void testConcurrentModification() throws Exception {
    int threadCnt = 8;
    ExecutorService executorService = Executors.newFixedThreadPool(threadCnt,
            new ThreadFactoryBuilder().setNameFormat("T%d").build());

    final Action[] actions = { new SleepAction(), new GetNumberAction(), new SetNumberAction(),
            new DeleteSequenceAction() };

    for (int i = 0; i < threadCnt; i++) {
        final int finalI = i;
        executorService.submit(new Runnable() {

            int runnableNo = finalI;

            @Override//w w w . jav  a  2  s  .  c o  m
            public void run() {
                ThreadLocalRandom random = ThreadLocalRandom.current();
                for (int i = 0; i < 10; i++) {
                    int action = random.nextInt(0, 4);
                    System.out.println(
                            "Runnable " + runnableNo + " iteration " + i + " action " + actions[action]);
                    try {
                        int seqN = actions[action].perform(runnableNo);
                        actions[action].success(runnableNo, seqN);
                    } catch (Exception e) {
                        if (e instanceof IllegalStateException
                                && StringUtils.contains(e.getMessage(), "Attempt to delete")) {
                            System.err.println(e.getMessage());
                            continue;
                        }
                        System.err.println(e.getMessage());
                        exceptionCnt.incrementAndGet();
                    }
                }
                finishedThreads.incrementAndGet();
            }
        });
    }

    while (finishedThreads.get() < threadCnt) {
        System.out.println("Waiting...");
        TimeUnit.MILLISECONDS.sleep(200);
    }

    assertEquals(exceptionCnt.get(), 0);
}

From source file:com.mgmtp.perfload.core.test.comp.ComponentTest.java

@BeforeTest
public void startDaemon() throws IOException {
    log.debug("Starting daemon...");

    ExecutorService executorService = Executors.newFixedThreadPool(2, new DaemonThreadFactory());
    executorService.submit(new DaemonTask(DAEMON_PORT));
}

From source file:com.baifendian.swordfish.execserver.runner.flow.FlowRunnerManager.java

public FlowRunnerManager(Configuration conf) {
    this.flowDao = DaoFactory.getDaoInstance(FlowDao.class);

    int flowThreads = conf.getInt(Constants.EXECUTOR_FLOWRUNNER_THREADS, Constants.defaultFlowRunnerThreadNum);
    ThreadFactory flowThreadFactory = new ThreadFactoryBuilder().setNameFormat("Exec-Worker-FlowRunner")
            .build();//  ww  w  .  j  a v a  2 s  .c o  m
    flowExecutorService = Executors.newFixedThreadPool(flowThreads, flowThreadFactory);

    int nodeThreads = conf.getInt(Constants.EXECUTOR_NODERUNNER_THREADS, Constants.defaultNodeRunnerThreadNum);
    ThreadFactory nodeThreadFactory = new ThreadFactoryBuilder().setNameFormat("Exec-Worker-NodeRunner")
            .build();
    nodeExecutorService = Executors.newFixedThreadPool(nodeThreads, nodeThreadFactory);

    // ?? runningFlows ??
    Thread cleanThread = new Thread(() -> {
        while (true) {
            try {
                cleanFinishedFlows();
            } catch (Exception e) {
                logger.error("clean thread error ", e);
            } finally {
                try {
                    Thread.sleep(Constants.defaultCleanFinishFlowInterval);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    cleanThread.setDaemon(true);
    cleanThread.setName("finishedFlowClean");
    cleanThread.start();
}

From source file:com.cloudera.oryx.kmeans.computation.local.WeightedPointsByFold.java

@Override
public List<List<WeightedRealVector>> call() throws InterruptedException, ExecutionException {
    Config config = ConfigUtils.getDefaultConfig();
    ClusterSettings cluster = ClusterSettings.create(config);
    KSketchIndex index = buildIndex(foldVecs, cluster);
    int pointsPerIteration = cluster.getSketchPoints();
    RandomGenerator random = RandomManager.getRandom();

    ListeningExecutorService exec = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(config.getInt("model.parallelism"),
                    new ThreadFactoryBuilder().setNameFormat("KSKETCH-%d").setDaemon(true).build()));
    for (int iter = 0; iter < cluster.getSketchIterations(); iter++) {
        log.info("Starting sketch iteration {}", iter + 1);
        List<ListenableFuture<Collection<RealVector>>> futures = Lists.newArrayList();
        for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
            futures.add(exec/*from www  .  ja  v  a  2 s .c  o  m*/
                    .submit(new SamplingRun(index, random, foldId, foldVecs.get(foldId), pointsPerIteration)));
        }
        // At the end of each iteration, gather up the sampled points to add to the index
        Future<List<Collection<RealVector>>> all = Futures.allAsList(futures);
        try {
            List<Collection<RealVector>> newSamples = all.get();
            for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
                for (RealVector v : newSamples.get(foldId)) {
                    index.add(v, foldId);
                }
            }
        } catch (ExecutionException e) {
            ExecutorUtils.shutdownNowAndAwait(exec);
            all.cancel(true);
            throw e;
        }
        index.rebuildIndices();
    }

    List<ListenableFuture<List<WeightedRealVector>>> ret = Lists.newArrayList();
    for (int foldId = 0; foldId < foldVecs.size(); foldId++) {
        ret.add(exec.submit(new AssignmentRun(index, foldId, foldVecs.get(foldId))));
    }
    try {
        return Futures.allAsList(ret).get();
    } finally {
        ExecutorUtils.shutdownNowAndAwait(exec);
    }
}

From source file:com.netflix.spinnaker.kork.astyanax.AstyanaxComponents.java

@Bean
public ExecutorService cassandraAsyncExecutor(
        @Value("${cassandra.asyncExecutorPoolSize:5}") int asyncPoolSize) {
    return Executors.newFixedThreadPool(asyncPoolSize,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("AstyanaxAsync-%d").build());
}

From source file:io.mandrel.frontier.FrontierContainer.java

public FrontierContainer(Spider spider, Accumulators accumulators, Clients clients) {
    super(accumulators, spider, clients);
    context.setDefinition(spider);//from ww  w .j  a  va  2  s  .c  om

    // Init stores
    MetadataStore metadatastore = spider.getStores().getMetadataStore().build(context);
    metadatastore.init();
    MetadataStores.add(spider.getId(), metadatastore);

    // Init frontier
    frontier = spider.getFrontier().build(context);

    // Revisitor
    BasicThreadFactory threadFactory = new BasicThreadFactory.Builder()
            .namingPattern("frontier-" + spider.getId() + "-%d").daemon(true).priority(Thread.MAX_PRIORITY)
            .build();
    executor = Executors.newFixedThreadPool(1, threadFactory);
    revisitor = new Revisitor(frontier, metadatastore);
    executor.submit(revisitor);

    current.set(ContainerStatus.INITIATED);
}

From source file:eu.interedition.collatex.tools.CollationServer.java

public CollationServer(int maxParallelCollations, int maxCollationSize, String dotPath) {
    this.collationThreads = Executors.newFixedThreadPool(maxParallelCollations, new ThreadFactory() {
        private final AtomicLong counter = new AtomicLong();

        @Override// w  w  w .  jav a  2 s.c  om
        public Thread newThread(Runnable r) {
            final Thread t = new Thread(r, "collator-" + counter.incrementAndGet());
            t.setDaemon(true);
            t.setPriority(Thread.MIN_PRIORITY);
            return t;
        }
    });

    this.maxCollationSize = maxCollationSize;
    this.dotPath = dotPath;
}

From source file:com.baifendian.swordfish.execserver.runner.streaming.StreamingRunnerManager.java

public StreamingRunnerManager(Configuration conf) {
    streamingDao = DaoFactory.getDaoInstance(StreamingDao.class);

    int threads = conf.getInt(Constants.EXECUTOR_STREAMING_THREADS, Constants.defaultStreamingThreadNum);

    ThreadFactory flowThreadFactory = new ThreadFactoryBuilder().setNameFormat("Exec-Server-StreamingRunner")
            .build();/*from w w  w.  j a  va 2s. com*/
    streamingExecutorService = Executors.newFixedThreadPool(threads, flowThreadFactory);
}

From source file:me.adaptive.services.notification.NotificationSender.java

@PostConstruct
void init() {//from  w  w w . ja  va2 s .  com
    LOGGER.info("Initializing");
    if (!CollectionUtils.isEmpty(services)) {
        executorService = Executors.newFixedThreadPool(services.size(),
                new CustomizableThreadFactory("NOTIFICATION-"));
        for (NotificationService service : services) {
            if (!notificationServices.containsKey(service.getChannel())) {
                notificationServices.put(service.getChannel(), new HashSet<>());
            }
            notificationServices.get(service.getChannel()).add(service);
        }
    }
    LOGGER.info("NotificationSender initialized with {} NotificationServices with the Channels {}",
            services.size(),
            Arrays.toString(notificationServices.keySet().stream().map(Enum::toString).toArray()));
}

From source file:com.flipkart.phantom.runtime.impl.server.netty.TCPNettyServer.java

/**
 * Interface method implementation. Creates server and worker thread pools if required and then calls {@link #afterPropertiesSet()} on the super class
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 *//*from www.  j  a  v a 2  s. co m*/
public void afterPropertiesSet() throws Exception {
    if (this.getServerExecutors() == null) { // no executors have been set for server listener
        if (this.getServerPoolSize() != TCPNettyServer.INVALID_POOL_SIZE) { // thread pool size has been set. create and use a fixed thread pool
            this.setServerExecutors(Executors.newFixedThreadPool(this.getServerPoolSize(),
                    new NamedThreadFactory("TCPServer-Listener")));
        } else { // default behavior of creating and using a cached thread pool
            this.setServerExecutors(
                    Executors.newCachedThreadPool(new NamedThreadFactory("TCPServer-Listener")));
        }
    }
    if (this.getWorkerExecutors() == null) { // no executors have been set for workers
        if (this.getWorkerPoolSize() != TCPNettyServer.INVALID_POOL_SIZE) { // thread pool size has been set. create and use a fixed thread pool
            this.setWorkerExecutors(Executors.newFixedThreadPool(this.getWorkerPoolSize(),
                    new NamedThreadFactory("TCPServer-Worker")));
        } else { // default behavior of creating and using a cached thread pool
            this.setWorkerExecutors(Executors.newCachedThreadPool(new NamedThreadFactory("TCPServer-Worker")));
        }
    }
    super.afterPropertiesSet();
}