Example usage for java.util.concurrent ThreadFactory ThreadFactory

List of usage examples for java.util.concurrent ThreadFactory ThreadFactory

Introduction

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

Prototype

ThreadFactory

Source Link

Usage

From source file:org.languagetool.gui.LanguageToolSupport.java

private void init() {
    try {//from   w w w  . j  av  a  2s .  com
        config = new Configuration(new File(System.getProperty("user.home")), CONFIG_FILE, null);
    } catch (IOException ex) {
        throw new RuntimeException("Could not load configuration", ex);
    }

    Language defaultLanguage = config.getLanguage();
    if (defaultLanguage == null) {
        defaultLanguage = Languages.getLanguageForLocale(Locale.getDefault());
    }

    /**
     * Warm-up: we have a lot of lazy init in LT, which causes the first check to
     * be very slow (several seconds) for languages with a lot of data and a lot of
     * rules. We just assume that the default language is the language that the user
     * often uses and init the LT object for that now, not just when it's first used.
     * This makes the first check feel much faster:
     */
    reloadLanguageTool(defaultLanguage);

    checkExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setName(t.getName() + "-lt-background");
            return t;
        }
    });

    check = new AtomicInteger(0);

    this.textComponent.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), false);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            recalculateSpans(e.getOffset(), e.getLength(), true);
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            mustDetectLanguage = config.getAutoDetect();
            if (backgroundCheckEnabled) {
                checkDelayed(null);
            }
        }
    });

    mouseListener = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
                showPopup(me);
            }
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }
    };
    this.textComponent.addMouseListener(mouseListener);

    actionListener = e -> _actionPerformed(e);

    mustDetectLanguage = config.getAutoDetect();
    if (!this.textComponent.getText().isEmpty() && backgroundCheckEnabled) {
        checkImmediately(null);
    }
}

From source file:org.apache.jackrabbit.oak.jcr.repository.RepositoryImpl.java

private static ScheduledExecutorService createListeningScheduledExecutorService() {
    ThreadFactory tf = new ThreadFactory() {
        private final AtomicLong counter = new AtomicLong();

        @Override//w w  w.java 2s  .c o m
        public Thread newThread(@Nonnull Runnable r) {
            Thread t = new Thread(r, newName());
            t.setDaemon(true);
            return t;
        }

        private String newName() {
            return "oak-repository-executor-" + counter.incrementAndGet();
        }
    };
    return new ScheduledThreadPoolExecutor(1, tf) {
        // purge the list of schedule tasks before scheduling a new task in order
        // to reduce memory consumption in the face of many cancelled tasks. See OAK-1890.

        @Override
        public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
            purge();
            return super.schedule(callable, delay, unit);
        }

        @Override
        public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
            purge();
            return super.schedule(command, delay, unit);
        }

        @Override
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period,
                TimeUnit unit) {
            purge();
            return super.scheduleAtFixedRate(command, initialDelay, period, unit);
        }

        @Override
        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
                TimeUnit unit) {
            purge();
            return super.scheduleWithFixedDelay(command, initialDelay, delay, unit);
        }
    };
}

From source file:org.apache.helix.messaging.handling.HelixTaskExecutor.java

/** Dedicated Thread pool can be provided in configuration or by client.
 *  This method is to check it and update the thread pool if necessary.
 */// ww w .jav a  2  s  . c  om
private void updateStateTransitionMessageThreadPool(Message message, HelixManager manager) {
    if (!message.getMsgType().equals(MessageType.STATE_TRANSITION.name())) {
        return;
    }

    String resourceName = message.getResourceName();
    String factoryName = message.getStateModelFactoryName();
    String stateModelName = message.getStateModelDef();

    if (factoryName == null) {
        factoryName = HelixConstants.DEFAULT_STATE_MODEL_FACTORY;
    }
    StateModelFactory<? extends StateModel> stateModelFactory = manager.getStateMachineEngine()
            .getStateModelFactory(stateModelName, factoryName);

    String perStateTransitionTypeKey = getStateTransitionType(
            getPerResourceStateTransitionPoolName(resourceName), message.getFromState(), message.getToState());
    if (perStateTransitionTypeKey != null && stateModelFactory != null
            && !_transitionTypeThreadpoolChecked.contains(perStateTransitionTypeKey)) {
        ExecutorService perStateTransitionTypeExecutor = stateModelFactory.getExecutorService(resourceName,
                message.getFromState(), message.getToState());
        _transitionTypeThreadpoolChecked.add(perStateTransitionTypeKey);

        if (perStateTransitionTypeExecutor != null) {
            _executorMap.put(perStateTransitionTypeKey, perStateTransitionTypeExecutor);
            LOG.info(String.format("Added client specified dedicate threadpool for resource %s from %s to %s",
                    getPerResourceStateTransitionPoolName(resourceName), message.getFromState(),
                    message.getToState()));
            return;
        }
    }

    if (!_resourcesThreadpoolChecked.contains(resourceName)) {
        int threadpoolSize = -1;
        ConfigAccessor configAccessor = manager.getConfigAccessor();
        // Changes to this configuration on thread pool size will only take effect after the participant get restarted.
        if (configAccessor != null) {
            HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE)
                    .forCluster(manager.getClusterName()).forResource(resourceName).build();

            String threadpoolSizeStr = configAccessor.get(scope, MAX_THREADS);
            try {
                if (threadpoolSizeStr != null) {
                    threadpoolSize = Integer.parseInt(threadpoolSizeStr);
                }
            } catch (Exception e) {
                LOG.error("Failed to parse ThreadPoolSize from resourceConfig for resource" + resourceName, e);
            }
        }
        final String key = getPerResourceStateTransitionPoolName(resourceName);
        if (threadpoolSize > 0) {
            _executorMap.put(key, Executors.newFixedThreadPool(threadpoolSize, new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "GerenricHelixController-message_handle_" + key);
                }
            }));
            LOG.info("Added dedicate threadpool for resource: " + resourceName + " with size: "
                    + threadpoolSize);
        } else {
            // if threadpool is not configured
            // check whether client specifies customized threadpool.
            if (stateModelFactory != null) {
                ExecutorService executor = stateModelFactory.getExecutorService(resourceName);
                if (executor != null) {
                    _executorMap.put(key, executor);
                    LOG.info("Added client specified dedicate threadpool for resource: " + key);
                }
            } else {
                LOG.error(String.format(
                        "Fail to get dedicate threadpool defined in stateModelFactory %s: using factoryName: %s for resource %s. No stateModelFactory was found!",
                        stateModelName, factoryName, resourceName));
            }
        }
        _resourcesThreadpoolChecked.add(resourceName);
    }
}

From source file:co.paralleluniverse.galaxy.netty.UDPComm.java

private void configureThreadPool(String name, ThreadPoolExecutor executor) {
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
    executor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat(name + "-%d").setDaemon(true)
            .setThreadFactory(new ThreadFactory() {
                @Override//ww w.  j ava 2 s  .  c o m
                public Thread newThread(Runnable r) {
                    return new CommThread(r);
                }
            }).build());
    ThreadPoolExecutorMonitor.register(name, executor);
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

SQLPaxosLogger(int id, String strID, String dbPath, PaxosMessenger<?> messenger) {
    super(id, dbPath, messenger);
    this.strID = strID;
    GC = Executors.newScheduledThreadPool(2, new ThreadFactory() {
        @Override//w w  w . ja  v a 2s  .co m
        public Thread newThread(Runnable r) {
            Thread thread = Executors.defaultThreadFactory().newThread(r);
            thread.setName(SQLPaxosLogger.class.getSimpleName() + ":" + strID);
            return thread;
        }
    }); // new Timer(strID);
    addDerbyLogger(this);
    this.journaler = new Journaler(this.logDirectory, this.strID/* this.myID */);
    this.deleteTmpJournalFiles();

    this.mapDB = USE_MAP_DB
            ? new MapDBContainer(DBMaker.fileDB(new File(this.getLogIndexDBPrefix())).make(),
                    DBMaker.memoryDB().transactionDisable().make())
            : null;

    Diskable<String, LogIndex> disk = new Diskable<String, LogIndex>() {

        @Override
        public Set<String> commit(Map<String, LogIndex> toCommit) throws IOException {
            return SQLPaxosLogger.this.pauseLogIndex(toCommit);
        }

        @Override
        public LogIndex restore(String key) throws IOException {
            return SQLPaxosLogger.this.unpauseLogIndex(key);
        }

        public String toString() {
            return MessageLogDiskMap.class.getSimpleName() + SQLPaxosLogger.this.strID;
        }

    };
    this.messageLog = USE_MAP_DB ? new MessageLogMapDB(this.mapDB.inMemory, this.mapDB.onDisk, disk)
            : USE_DISK_MAP ? new MessageLogDiskMap(disk) : new MessageLogPausable(disk);

    // will set up db, connection, tables, etc. as needed
    if (!initialize(true))
        throw new RuntimeException("Unable to initiate " + PaxosManager.class.getSimpleName() + " for " + id);
    ;
}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Constructs MarketplaceWebServiceClient with AWS Access Key ID, AWS Secret Key
 * and MarketplaceWebServiceConfig. Use MarketplaceWebServiceConfig to pass additional
 * configuration that affects how service is being called.
 *
 * @param awsAccessKeyId//  w w w.  j a v a  2s.co m
 *          AWS Access Key ID
 * @param awsSecretAccessKey
 *          AWS Secret Access Key
 * @param config
 *          Additional configuration options
 */
@SuppressWarnings("serial")
public MarketplaceWebServiceClient(String awsAccessKeyId, String awsSecretAccessKey, String applicationName,
        String applicationVersion, MarketplaceWebServiceConfig config) {
    this.awsAccessKeyId = awsAccessKeyId;
    this.awsSecretAccessKey = awsSecretAccessKey;
    this.config = config;
    this.httpClient = configureHttpClient(applicationName, applicationVersion);
    this.asyncExecutor = new ThreadPoolExecutor(config.getMaxAsyncThreads(), config.getMaxAsyncThreads(), 60L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(config.getMaxAsyncQueueSize()) {

                @Override
                public boolean offer(Runnable task) {
                    log.debug("Maximum number of concurrent threads reached, queuing task...");
                    return super.offer(task);
                }
            }, new ThreadFactory() {

                private final AtomicInteger threadNumber = new AtomicInteger(1);

                public Thread newThread(Runnable task) {
                    Thread thread = new Thread(task,
                            "MarketplaceWebServiceClient-Thread-" + threadNumber.getAndIncrement());
                    thread.setDaemon(true);
                    if (thread.getPriority() != Thread.NORM_PRIORITY) {
                        thread.setPriority(Thread.NORM_PRIORITY);
                    }
                    log.debug("ThreadFactory created new thread: " + thread.getName());
                    return thread;
                }
            }, new RejectedExecutionHandler() {

                public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                    log.debug("Maximum number of concurrent threads reached, and queue is full. "
                            + "Running task in the calling thread..." + Thread.currentThread().getName());
                    if (!executor.isShutdown()) {
                        task.run();
                    }
                }
            });
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProviderService.java

private ExecutorService createExecutor() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 5, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger counter = new AtomicInteger();
                private final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
                    @Override// w w  w  .jav a 2 s .c  o m
                    public void uncaughtException(Thread t, Throwable e) {
                        log.warn("Error occurred in asynchronous processing ", e);
                    }
                };

                @Override
                public Thread newThread(@Nonnull Runnable r) {
                    Thread thread = new Thread(r, createName());
                    thread.setDaemon(true);
                    thread.setPriority(Thread.MIN_PRIORITY);
                    thread.setUncaughtExceptionHandler(handler);
                    return thread;
                }

                private String createName() {
                    return "oak-lucene-" + counter.getAndIncrement();
                }
            });
    executor.setKeepAliveTime(1, TimeUnit.MINUTES);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}

From source file:org.apache.lens.driver.jdbc.JDBCDriver.java

/**
 * Inits the.//from   w  ww .  j  a v a2 s.c  o m
 *
 * @throws LensException the lens exception
 */
public void init() throws LensException {
    final int maxPoolSize = parseInt(getConf().get(JDBC_POOL_MAX_SIZE.getConfigKey()));
    final int maxConcurrentQueries = parseInt(
            getConf().get(MaxConcurrentDriverQueriesConstraintFactory.MAX_CONCURRENT_QUERIES_KEY));
    checkState(maxPoolSize >= maxConcurrentQueries,
            "maxPoolSize:" + maxPoolSize + " maxConcurrentQueries:" + maxConcurrentQueries);

    queryContextMap = new ConcurrentHashMap<>();
    asyncQueryPool = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread th = new Thread(runnable);
            th.setName("lens-driver-jdbc-" + THID.incrementAndGet());
            return th;
        }
    });

    Class<? extends ConnectionProvider> cpClass = getConf().getClass(JDBC_CONNECTION_PROVIDER,
            DataSourceConnectionProvider.class, ConnectionProvider.class);
    try {
        connectionProvider = cpClass.newInstance();
        estimateConnectionProvider = cpClass.newInstance();
    } catch (Exception e) {
        log.error("Error initializing connection provider: ", e);
        throw new LensException(e);
    }
    this.logSegregationContext = new MappedDiagnosticLogSegregationContext();
    this.isStatementCancelSupported = getConf().getBoolean(STATEMENT_CANCEL_SUPPORTED,
            DEFAULT_STATEMENT_CANCEL_SUPPORTED);
}

From source file:org.apache.geode.cache.client.internal.PoolImpl.java

private void start() {
    if (this.startDisabled)
        return;/*  w w  w .  ja va 2s  .  co  m*/

    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
        List locators = getLocators();
        if (!locators.isEmpty()) {
            logger.debug("PoolImpl - starting pool with locators: {}", locators);
        } else {
            logger.debug("PoolImpl -starting pool with servers: {}", getServers());
        }
    }

    final String timerName = "poolTimer-" + getName() + "-";
    backgroundProcessor = new ScheduledThreadPoolExecutorWithKeepAlive(BACKGROUND_TASK_POOL_SIZE,
            BACKGROUND_TASK_POOL_KEEP_ALIVE, TimeUnit.MILLISECONDS, new ThreadFactory() {
                AtomicInteger threadNum = new AtomicInteger();

                public Thread newThread(final Runnable r) {
                    Thread result = new Thread(r, timerName + threadNum.incrementAndGet());
                    result.setDaemon(true);
                    return result;
                }
            });
    ((ScheduledThreadPoolExecutorWithKeepAlive) backgroundProcessor)
            .setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    ((ScheduledThreadPoolExecutorWithKeepAlive) backgroundProcessor)
            .setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

    source.start(this);
    connectionFactory.start(backgroundProcessor);
    endpointManager.addListener(new InstantiatorRecoveryListener(backgroundProcessor, this));
    endpointManager.addListener(new DataSerializerRecoveryListener(backgroundProcessor, this));
    if (Boolean.getBoolean(ON_DISCONNECT_CLEAR_PDXTYPEIDS)) {
        endpointManager.addListener(new PdxRegistryRecoveryListener(this));
    }
    endpointManager.addListener(new LiveServerPinger(this));

    manager.start(backgroundProcessor);
    if (queueManager != null) {
        if (isDebugEnabled) {
            logger.debug("starting queueManager");
        }
        queueManager.start(backgroundProcessor);
    }
    if (isDebugEnabled) {
        logger.debug("scheduling pings every {} milliseconds", pingInterval);
    }

    if (this.statisticInterval > 0 && this.dsys.getConfig().getStatisticSamplingEnabled()) {
        backgroundProcessor.scheduleWithFixedDelay(new PublishClientStatsTask(), statisticInterval,
                statisticInterval, TimeUnit.MILLISECONDS);
    }
    // LOG: changed from config to info
    logger.info(LocalizedMessage.create(
            LocalizedStrings.PoolImpl_POOL_0_STARTED_WITH_MULTIUSER_SECURE_MODE_ENABLED_1,
            new Object[] { this.name, this.multiuserSecureModeEnabled }));
}

From source file:org.springframework.osgi.extender.internal.support.ExtenderConfiguration.java

private TaskExecutor createDefaultShutdownTaskExecutor() {
    ThreadPoolTaskScheduler taskExecutor = new ThreadPoolTaskScheduler() {
        private static final long serialVersionUID = 1L;

        protected ScheduledExecutorService createExecutor(int poolSize, final ThreadFactory threadFactory,
                RejectedExecutionHandler rejectedExecutionHandler) {

            ThreadFactory tf = new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = threadFactory.newThread(r);
                    t.setName("Spring DM context shutdown thread");
                    return t;
                }/*from   w w w. ja v a  2 s.c  om*/

            };

            return new ScheduledThreadPoolExecutor(poolSize, tf, rejectedExecutionHandler);
        }
    };
    taskExecutor.afterPropertiesSet();
    isShutdownTaskExecutorManagedInternally = true;
    return taskExecutor;
}