Search in sources :

Example 36 with ThreadFactory

use of java.util.concurrent.ThreadFactory in project languagetool by languagetool-org.

the class LanguageToolSupport method init.

private void init() {
    try {
        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);
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) MouseEvent(java.awt.event.MouseEvent) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) IOException(java.io.IOException) MouseListener(java.awt.event.MouseListener) Language(org.languagetool.Language) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File)

Example 37 with ThreadFactory

use of java.util.concurrent.ThreadFactory in project jersey by jersey.

the class TransportFilter method initializeChannelGroup.

private void initializeChannelGroup() throws IOException {
    if (closeWaitTask != null) {
        closeWaitTask.cancel(true);
        closeWaitTask = null;
    }
    if (channelGroup == null) {
        ThreadFactory threadFactory = threadPoolConfig.getThreadFactory();
        if (threadFactory == null) {
            threadFactory = new TransportThreadFactory(threadPoolConfig);
        }
        ExecutorService executor;
        if (threadPoolConfig.getQueue() != null) {
            executor = new QueuingExecutor(threadPoolConfig.getCorePoolSize(), threadPoolConfig.getMaxPoolSize(), threadPoolConfig.getKeepAliveTime(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, threadPoolConfig.getQueue(), false, threadFactory);
        } else {
            int taskQueueLimit = threadPoolConfig.getQueueLimit();
            if (taskQueueLimit == -1) {
                taskQueueLimit = Integer.MAX_VALUE;
            }
            executor = new QueuingExecutor(threadPoolConfig.getCorePoolSize(), threadPoolConfig.getMaxPoolSize(), threadPoolConfig.getKeepAliveTime(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(taskQueueLimit), true, threadFactory);
        }
        // Thread pool is owned by the channel group and will be shut down when channel group is shut down
        channelGroup = AsynchronousChannelGroup.withCachedThreadPool(executor, threadPoolConfig.getCorePoolSize());
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService)

Example 38 with ThreadFactory

use of java.util.concurrent.ThreadFactory in project Openfire by igniterealtime.

the class MINAConnectionAcceptor method start.

/**
     * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be
     * logged and the method invocation is otherwise ignored.
     */
@Override
public synchronized void start() {
    if (socketAcceptor != null) {
        Log.warn("Unable to start acceptor (it is already started!)");
        return;
    }
    try {
        // Configure the thread pool that is to be used.
        final int initialSize = (configuration.getMaxThreadPoolSize() / 4) + 1;
        final ExecutorFilter executorFilter = new ExecutorFilter(initialSize, configuration.getMaxThreadPoolSize(), 60, TimeUnit.SECONDS);
        final ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor) executorFilter.getExecutor();
        final ThreadFactory threadFactory = new NamedThreadFactory(name + "-thread-", eventExecutor.getThreadFactory(), true, null);
        eventExecutor.setThreadFactory(threadFactory);
        // Construct a new socket acceptor, and configure it.
        socketAcceptor = buildSocketAcceptor();
        if (JMXManager.isEnabled()) {
            configureJMX(socketAcceptor, name);
        }
        final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
        filterChain.addFirst(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, executorFilter);
        // Add the XMPP codec filter
        filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, new ProtocolCodecFilter(new XMPPCodecFactory()));
        // Kill sessions whose outgoing queues keep growing and fail to send traffic
        filterChain.addAfter(ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, ConnectionManagerImpl.CAPACITY_FILTER_NAME, new StalledSessionsFilter());
        // Ports can be configured to start connections in SSL (as opposed to upgrade a non-encrypted socket to an encrypted one, typically using StartTLS)
        if (configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode) {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
        }
        // Throttle sessions who send data too fast
        if (configuration.getMaxBufferSize() > 0) {
            socketAcceptor.getSessionConfig().setMaxReadBufferSize(configuration.getMaxBufferSize());
            Log.debug("Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize());
        }
        // Start accepting connections
        socketAcceptor.setHandler(connectionHandler);
        socketAcceptor.bind(new InetSocketAddress(configuration.getBindAddress(), configuration.getPort()));
    } catch (Exception e) {
        System.err.println("Error starting " + configuration.getPort() + ": " + e.getMessage());
        Log.error("Error starting: " + configuration.getPort(), e);
        // Reset for future use.
        if (socketAcceptor != null) {
            try {
                socketAcceptor.unbind();
            } finally {
                socketAcceptor = null;
            }
        }
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) SslFilter(org.apache.mina.filter.ssl.SslFilter) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) InetSocketAddress(java.net.InetSocketAddress) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) StalledSessionsFilter(org.jivesoftware.openfire.net.StalledSessionsFilter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter) MalformedObjectNameException(javax.management.MalformedObjectNameException) JMException(javax.management.JMException)

Example 39 with ThreadFactory

use of java.util.concurrent.ThreadFactory in project hadoop by apache.

the class NonAggregatingLogHandler method createScheduledThreadPoolExecutor.

ScheduledThreadPoolExecutor createScheduledThreadPoolExecutor(Configuration conf) {
    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("LogDeleter #%d").build();
    sched = new HadoopScheduledThreadPoolExecutor(conf.getInt(YarnConfiguration.NM_LOG_DELETION_THREADS_COUNT, YarnConfiguration.DEFAULT_NM_LOG_DELETE_THREAD_COUNT), tf);
    return sched;
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) HadoopScheduledThreadPoolExecutor(org.apache.hadoop.util.concurrent.HadoopScheduledThreadPoolExecutor) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder)

Example 40 with ThreadFactory

use of java.util.concurrent.ThreadFactory in project hbase by apache.

the class Threads method getNamedThreadFactory.

/**
   * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely,
   * with a common prefix.
   * @param prefix The prefix of every created Thread's name
   * @return a {@link java.util.concurrent.ThreadFactory} that names threads
   */
public static ThreadFactory getNamedThreadFactory(final String prefix) {
    SecurityManager s = System.getSecurityManager();
    final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    return new ThreadFactory() {

        final AtomicInteger threadNumber = new AtomicInteger(1);

        private final int poolNumber = Threads.poolNumber.getAndIncrement();

        final ThreadGroup group = threadGroup;

        @Override
        public Thread newThread(Runnable r) {
            final String name = prefix + "-pool" + poolNumber + "-t" + threadNumber.getAndIncrement();
            return new Thread(group, r, name);
        }
    };
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Aggregations

ThreadFactory (java.util.concurrent.ThreadFactory)250 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)47 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)46 ExecutorService (java.util.concurrent.ExecutorService)45 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)35 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)21 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)19 Test (org.junit.Test)17 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)16 Future (java.util.concurrent.Future)15 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)13 ArrayList (java.util.ArrayList)13 LoggingThreadGroup (org.apache.geode.internal.logging.LoggingThreadGroup)12 IOException (java.io.IOException)10 AtomicLong (java.util.concurrent.atomic.AtomicLong)10 ExecutionException (java.util.concurrent.ExecutionException)9 Executor (java.util.concurrent.Executor)9 ChannelFuture (io.netty.channel.ChannelFuture)8 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)8 SynchronousQueue (java.util.concurrent.SynchronousQueue)7