Example usage for java.util.concurrent Executors defaultThreadFactory

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

Introduction

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

Prototype

public static ThreadFactory defaultThreadFactory() 

Source Link

Document

Returns a default thread factory used to create new threads.

Usage

From source file:tv.arte.resteventapi.core.scheduling.RestEventScheduledThreadPoolExecutorScheduler.java

/**
 * @see ScheduledThreadPoolExecutor#ScheduledThreadPoolExecutor(int, RejectedExecutionHandler)
 *//*from w ww .j a  va2s  . c o  m*/
public RestEventScheduledThreadPoolExecutorScheduler(int corePoolSize, RejectedExecutionHandler handler) {
    this(corePoolSize, Executors.defaultThreadFactory(), handler, null, null);
}

From source file:org.hawkular.apm.performance.server.ClientSimulator.java

public void run() {
    Metrics metrics = new Metrics(name);
    ServiceRegistry reg = new DefaultServiceRegistry(systemConfig, metrics);

    List<PathConfiguration> paths = new ArrayList<PathConfiguration>();
    for (PathConfiguration pc : systemConfig.getPaths()) {
        for (int i = 0; i < pc.getWeight(); i++) {
            paths.add(pc);//  w ww .  j a va2 s . c o m
        }
    }

    // Initialise publisher metrics handler
    TracePublisher publisher = ServiceResolver.getSingletonService(TracePublisher.class);
    if (publisher == null) {
        log.severe("Trace publisher has not been configured correctly");
        return;
    }

    publisher.setMetricHandler(new PublisherMetricHandler<Trace>() {
        @Override
        public void published(String tenantId, List<Trace> items, long metric) {
            metrics.publishTraces(metric);
        }
    });

    Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    }).scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            metrics.report();
        }
    }, 1, 1, TimeUnit.SECONDS);

    for (int i = 0; i < requesters; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("THREAD: " + Thread.currentThread() + ": STARTED");

                for (int j = 0; j < invocations; j++) {
                    // Randomly select path
                    int index = (int) (Math.random() * (paths.size() - 1));

                    Service s = reg.getServiceInstance(paths.get(index).getService());

                    Message m = new Message(paths.get(index).getName());

                    s.call(m, null, null);
                }

                System.out.println("THREAD: " + Thread.currentThread() + ": FINISHED: " + new java.util.Date());

                synchronized (this) {
                    try {
                        wait(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

From source file:com.taobao.metamorphosis.gregor.slave.OrderedThreadPoolExecutor.java

/**
 * Creates a default ThreadPool, with default values : - minimum pool size
 * is 0 - maximum pool size is 16 - keepAlive set to 30 seconds - A default
 * ThreadFactory - All events are accepted
 *//*from  w ww. j  a  va  2 s  .co  m*/
public OrderedThreadPoolExecutor() {
    this(DEFAULT_INITIAL_THREAD_POOL_SIZE, DEFAULT_MAX_THREAD_POOL, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS,
            Executors.defaultThreadFactory());
}

From source file:org.deeplearning4j.arbiter.optimize.runner.BaseOptimizationRunner.java

protected void init() {
    futureListenerExecutor = Executors.newFixedThreadPool(maxConcurrentTasks(), new ThreadFactory() {
        private AtomicLong counter = new AtomicLong(0);

        @Override/*  ww  w . j a  v a  2  s  .  co m*/
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            t.setName("ArbiterOptimizationRunner-" + counter.getAndIncrement());
            return t;
        }
    });
}

From source file:net.transmutator4j.RunTransmutator4j.java

@Override
public void run() {

    long startTime = System.currentTimeMillis();
    InetAddress localhost;//  w w  w .  j  av  a2s.  c  o m
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new IllegalStateException("can not resolve local host", e);
    }
    //socket get dynamically generated port
    SocketAddress socket = new InetSocketAddress(localhost, 0);
    AsynchronousChannelGroup group;
    try {
        group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory());
    } catch (IOException e1) {
        throw new IllegalStateException("can not create channel group", e1);
    }

    try (

            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(socket,
                    1);

    ) {

        int numTotalTests = runUnmutatedTests();
        long unmutatedTimeEnd = System.currentTimeMillis();
        long unmutatedElapsedTime = unmutatedTimeEnd - startTime;
        listener.testInfo(numTotalTests, unmutatedElapsedTime);
        System.out.println("unmutated tests took " + unmutatedElapsedTime + " ms");
        long timeOut = computeTimeoutTime(unmutatedElapsedTime);
        InetSocketAddress inetSocketAddress = (InetSocketAddress) server.getLocalAddress();
        int port = inetSocketAddress.getPort();
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel resultChannel, Object attachment) {
                try {
                    ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(resultChannel));
                    MutationTestResult testResult = (MutationTestResult) in.readObject();

                    in.close();

                    listener.mutationResult(testResult);
                    boolean stillPassed = testResult.testsStillPassed();
                    System.out.print(stillPassed ? "P" : ".");
                    System.out.flush();
                    numberOfMutationsMade++;

                    if (stillPassed) {
                        numberOfMutationsThatStillPassedTests++;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RuntimeException("error getting test result ", e);
                }
                //accept a new connection
                server.accept(null, this);

            }

            @Override
            public void failed(Throwable e, Object attachment) {
                //   System.err.println(attachment + " failed with:" + e.getClass().getName());
                //    e.printStackTrace();
            }
        });

        OUTER: for (String classToMutate : new ClassPathClassRepository()) {
            boolean shouldMutate = shouldMutate(classToMutate);
            if (shouldMutate) {
                System.out.printf("mutating %s%n", classToMutate);
                boolean done = false;
                int mutationCount = 0;
                while (!done) {
                    JavaProcessBuilder builder = new JavaProcessBuilder(

                            "net.transmutator4j.Transmutator4j", classToMutate, nameOfTestSuite,
                            Integer.toString(mutationCount), Integer.toString(port));

                    try {
                        TimedProcess timedProcess = new TimedProcess(builder.getBuilder(), timeOut);
                        int exitValue = timedProcess.call();

                        TransmutatorUtil.EXIT_STATES exitState = TransmutatorUtil.EXIT_STATES
                                .getValueFor(exitValue);
                        if (exitState == TransmutatorUtil.EXIT_STATES.NO_MUTATIONS_MADE) {
                            done = true;
                            System.out.println();
                        } else if (exitState == TransmutatorUtil.EXIT_STATES.TIMED_OUT) {
                            numberOfMutationsThatTimedOut++;

                        }

                    } catch (InterruptedException e) {
                        System.err.println("detected cancellation...halting");
                        //stop iterating through all the classes
                        //by breaking out of outer for loop
                        break OUTER;
                    }

                    mutationCount++;

                }

            }
        }
        //kill any waiting connections this will cause the completionHandler's fail to get called
        group.shutdownNow();
        //group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        long endTime = System.currentTimeMillis();
        System.out.printf("took %d ms to run %d mutations of which %d caused timeouts and %d still passed%n",
                (endTime - startTime), numberOfMutationsMade, numberOfMutationsThatTimedOut,
                numberOfMutationsThatStillPassedTests);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException ignored) {
                //ignore
            }
        }
        group.shutdown();
    }
}

From source file:org.madsonic.service.PodcastService.java

public PodcastService() {
    ThreadFactory threadFactory = new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);//from  w ww .  ja  v a 2 s  .  c  o m
            return t;
        }
    };
    refreshExecutor = Executors.newFixedThreadPool(5, threadFactory);
    downloadExecutor = Executors.newFixedThreadPool(4, threadFactory);

    //settingsService.getPodcastEpisodeDownloadLimit()

    scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
}

From source file:edu.umass.cs.nio.JSONMessenger.java

/**
 * @param niot//ww w .  j a  v  a2s .  com
 * @param numWorkers
 */
@SuppressWarnings("unchecked")
public JSONMessenger(final InterfaceNIOTransport<NodeIDType, JSONObject> niot, int numWorkers) {
    // to not create thread pools unnecessarily
    if (niot instanceof JSONMessenger)
        this.execpool = ((JSONMessenger<NodeIDType>) niot).execpool;
    else
        this.execpool = Executors.newScheduledThreadPool(5, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = Executors.defaultThreadFactory().newThread(r);
                thread.setName(JSONMessenger.class.getSimpleName() + niot.getMyID() + thread.getName());
                return thread;
            }
        });
    nioTransport = (InterfaceNIOTransport<NodeIDType, JSONObject>) niot;

    this.workers = new MessageNIOTransport[numWorkers];
    for (int i = 0; i < workers.length; i++) {
        try {
            log.info((this + " starting worker with ssl mode " + this.nioTransport.getSSLMode()));
            this.workers[i] = new MessageNIOTransport<NodeIDType, JSONObject>(null, this.getNodeConfig(),
                    this.nioTransport.getSSLMode());
            this.workers[i].setName(JSONMessenger.class.getSimpleName() + niot.getMyID() + "_send_worker" + i);
        } catch (IOException e) {
            this.workers[i] = null;
            e.printStackTrace();
        }
    }
}

From source file:org.pentaho.reporting.platform.plugin.async.PentahoAsyncExecutor.java

/**
 * @param capacity               thread pool capacity
 * @param autoSchedulerThreshold quantity of rows after which reports are automatically scheduled
 *///ww w .  j a v a 2 s .  co m
public PentahoAsyncExecutor(final int capacity, final int autoSchedulerThreshold) {
    this.autoSchedulerThreshold = autoSchedulerThreshold;
    log.info("Initialized reporting async execution fixed thread pool with capacity: " + capacity);
    executorService = new DelegatedListenableExecutor(new ThreadPoolExecutor(capacity, capacity, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = Executors.defaultThreadFactory().newThread(r);
                    thread.setDaemon(true);
                    thread.setName("PentahoAsyncExecutor Thread Pool");
                    return thread;
                }
            }));
    PentahoSystem.addLogoutListener(this);
    this.writeToJcrListeners = new ConcurrentHashMap<>();
    this.schedulingLocationListener = new MemorizeSchedulingLocationListener();
}

From source file:org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean.java

/**
 * Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
 * Default is the ThreadPoolExecutor's default thread factory.
 * @see java.util.concurrent.Executors#defaultThreadFactory()
 *///  w  ww.  j  ava 2 s  .  c  om
public void setThreadFactory(ThreadFactory threadFactory) {
    this.threadFactory = (threadFactory != null ? threadFactory : Executors.defaultThreadFactory());
}

From source file:com.yahoo.omid.tso.TSOServer.java

@Override
public void run() {
    // *** Start the Netty configuration ***
    // Start server with Nb of active threads = 2*NB CPU + 1 as maximum.
    ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), (Runtime.getRuntime().availableProcessors() * 2 + 1) * 2);

    ServerBootstrap bootstrap = new ServerBootstrap(factory);
    // Create the global ChannelGroup
    ChannelGroup channelGroup = new DefaultChannelGroup(TSOServer.class.getName());
    // threads max
    // int maxThreads = Runtime.getRuntime().availableProcessors() *2 + 1;
    int maxThreads = 5;
    // Memory limitation: 1MB by channel, 1GB global, 100 ms of timeout
    ThreadPoolExecutor pipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor(maxThreads, 1048576,
            1073741824, 100, TimeUnit.MILLISECONDS, new ObjectSizeEstimator() {
                @Override//from w w w  . ja v  a2  s .c  o m
                public int estimateSize(Object o) {
                    return 1000;
                }
            }, Executors.defaultThreadFactory());

    // This is the only object of timestamp oracle
    // TODO: make it singleton
    //TimestampOracle timestampOracle = new TimestampOracle();
    // The wrapper for the shared state of TSO
    state = BookKeeperStateBuilder.getState(this.config);

    if (state == null) {
        LOG.error("Couldn't build state");
        return;
    }

    state.addRecord(new byte[] { LoggerProtocol.LOGSTART }, new AddRecordCallback() {
        @Override
        public void addRecordComplete(int rc, Object ctx) {
        }
    }, null);

    TSOState.BATCH_SIZE = config.getBatchSize();
    System.out.println("PARAM MAX_ITEMS: " + TSOState.MAX_ITEMS);
    System.out.println("PARAM BATCH_SIZE: " + TSOState.BATCH_SIZE);
    System.out.println("PARAM LOAD_FACTOR: " + TSOState.LOAD_FACTOR);
    System.out.println("PARAM MAX_THREADS: " + maxThreads);

    final TSOHandler handler = new TSOHandler(channelGroup, state);
    handler.start();

    bootstrap.setPipelineFactory(new TSOPipelineFactory(pipelineExecutor, handler));
    bootstrap.setOption("tcpNoDelay", false);
    //setting buffer size can improve I/O
    bootstrap.setOption("child.sendBufferSize", 1048576);
    bootstrap.setOption("child.receiveBufferSize", 1048576);
    // better to have an receive buffer predictor
    bootstrap.setOption("receiveBufferSizePredictorFactory", new AdaptiveReceiveBufferSizePredictorFactory());
    //if the server is sending 1000 messages per sec, optimum write buffer water marks will
    //prevent unnecessary throttling, Check NioSocketChannelConfig doc
    bootstrap.setOption("writeBufferLowWaterMark", 32 * 1024);
    bootstrap.setOption("writeBufferHighWaterMark", 64 * 1024);

    bootstrap.setOption("child.tcpNoDelay", false);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.reuseAddress", true);
    bootstrap.setOption("child.connectTimeoutMillis", 60000);

    // *** Start the Netty running ***

    // Create the monitor
    ThroughputMonitor monitor = new ThroughputMonitor(state);
    // Add the parent channel to the group
    Channel channel = bootstrap.bind(new InetSocketAddress(config.getPort()));
    channelGroup.add(channel);

    // Compacter handler
    ChannelFactory comFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), (Runtime.getRuntime().availableProcessors() * 2 + 1) * 2);
    ServerBootstrap comBootstrap = new ServerBootstrap(comFactory);
    ChannelGroup comGroup = new DefaultChannelGroup("compacter");
    final CompacterHandler comHandler = new CompacterHandler(comGroup, state);
    comBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", new ObjectDecoder());
            pipeline.addLast("encoder", new ObjectEncoder());
            pipeline.addLast("handler", comHandler);
            return pipeline;
        }
    });
    comBootstrap.setOption("tcpNoDelay", false);
    comBootstrap.setOption("child.tcpNoDelay", false);
    comBootstrap.setOption("child.keepAlive", true);
    comBootstrap.setOption("child.reuseAddress", true);
    comBootstrap.setOption("child.connectTimeoutMillis", 100);
    comBootstrap.setOption("readWriteFair", true);
    channel = comBootstrap.bind(new InetSocketAddress(config.getPort() + 1));

    // Starts the monitor
    monitor.start();
    synchronized (lock) {
        while (!finish) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    //timestampOracle.stop();
    handler.stop();
    comHandler.stop();
    state.stop();

    // *** Start the Netty shutdown ***

    // End the monitor
    System.out.println("End of monitor");
    monitor.interrupt();
    // Now close all channels
    System.out.println("End of channel group");
    channelGroup.close().awaitUninterruptibly();
    comGroup.close().awaitUninterruptibly();
    // Close the executor for Pipeline
    System.out.println("End of pipeline executor");
    pipelineExecutor.shutdownNow();
    // Now release resources
    System.out.println("End of resources");
    factory.releaseExternalResources();
    comFactory.releaseExternalResources();
}