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:de.ufinke.cubaja.sort.SortManager.java

private ThreadFactory createThreadFactory() {

    return new ThreadFactory() {

        public Thread newThread(Runnable r) {

            Thread thread = new Thread(r);
            thread.setDaemon(true);// ww w . j a  va2 s .  co m
            return thread;
        }
    };
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSConnectionPoolImplTest.java

@Test
public void testPoolWithMultipleThreads() {
    String testAppId = "multithreadTestApp";
    /**//from   w w  w  .j  av a2  s.  c  o  m
     * create 5 threads each sending to 100 devices
     */
    int deviceCount = 100;
    int threadCount = 5;
    Map<String, String> payload = new LinkedHashMap<String, String>(100);
    for (int i = 0; i < deviceCount; i++) {
        payload.put("device:" + (i + 1), "JSON Payload{}:" + (i + 1));
    }
    objectFactory.clearCounter();
    APNSConnectionPoolImpl pool = APNSConnectionPoolImpl.getInstance();
    //initialize the pool with connections for all apps

    //    for (int i = 0; i < appIds.length; i++) {
    //      APNSConnection conn = pool.getConnection(appIds[i], true);
    //      pool.returnConnection(conn);
    //    }

    CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    Executor executor = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
        private AtomicInteger counter = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("TestThread:" + counter.getAndIncrement());
            return t;
        }
    });
    for (int i = 0; i < threadCount; i++) {
        executor.execute(new SimpleAPNSSenderThread(testAppId, true, payload, countDownLatch));
    }
    //wait for the threads to finish
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    int count = objectFactory.getCreatedCount(new APNSConnectionPoolImpl.APNSConnectionKey(testAppId, true));
    assertEquals("Object got created too many times", MAX_OBJECTS_PER_KEY, count);
}

From source file:org.jumpmind.symmetric.service.impl.PushService.java

public void start() {
    nodeChannelExtractForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-extract-for-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);/*from  ww  w.  ja v a2  s . co  m*/
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });

    nodeChannelTransportForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });
}

From source file:org.xdi.oxauth.util.ServerUtil.java

public static ScheduledExecutorService createExecutor() {
    return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        public Thread newThread(Runnable p_r) {
            Thread thread = new Thread(p_r);
            thread.setDaemon(true);/*from w ww  . j  av a2s . c om*/
            return thread;
        }
    });
}

From source file:org.energy_home.jemma.javagal.layers.business.implementations.GatewayEventManager.java

/**
 * Creates a new instance with a Gal Controller reference.
 * /*from  w w w. jav  a 2 s  . c o m*/
 * @param _gal
 *            a Gal controller reference.
 */
public GatewayEventManager(GalController _gal) {
    gal = _gal;
    LOG.debug("Creating Executor for GatewayEventManager with: {} threads",
            getGal().getPropertiesManager().getNumberOfThreadForAnyPool());

    executor = Executors.newFixedThreadPool(getGal().getPropertiesManager().getNumberOfThreadForAnyPool(),
            new ThreadFactory() {

                public Thread newThread(Runnable r) {

                    return new Thread(r, "THPool-EventManager");
                }
            });

    if (executor instanceof ThreadPoolExecutor) {
        ((ThreadPoolExecutor) executor).setKeepAliveTime(getGal().getPropertiesManager().getKeepAliveThread(),
                TimeUnit.MINUTES);
        ((ThreadPoolExecutor) executor).allowCoreThreadTimeOut(true);

    }
}

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

public void start() {
    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override/*from w ww .  jav a  2  s .co  m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.flushFuture = scheduledExecutor.schedule(flushThread, TSOState.FLUSH_TIMEOUT, TimeUnit.MILLISECONDS);
    this.executor = Executors.newSingleThreadExecutor();
}

From source file:com.xabber.android.data.connection.ConnectionThread.java

public ConnectionThread(final ConnectionItem connectionItem) {
    LogManager.i(this, "NEW connection thread " + connectionItem.getRealJid());

    this.connectionItem = connectionItem;
    executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override/*from  w ww .j  ava 2  s. c o m*/
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable,
                    "Connection thread for " + (connectionItem instanceof AccountItem
                            ? ((AccountItem) connectionItem).getAccount()
                            : connectionItem));
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setDaemon(true);
            return thread;
        }
    });
    ConnectionManager.getInstance().onConnection(this);
    ConnectionSettings connectionSettings = connectionItem.getConnectionSettings();
    protocol = connectionSettings.getProtocol();
    serverName = connectionSettings.getServerName();
    token = connectionSettings.getPassword();
    resource = connectionSettings.getResource();
    saslEnabled = connectionSettings.isSaslEnabled();
    tlsMode = connectionSettings.getTlsMode();
    compression = connectionSettings.useCompression();
    if (saslEnabled && protocol == AccountProtocol.gtalk)
        login = connectionSettings.getUserName() + "@" + connectionSettings.getServerName();
    else
        login = connectionSettings.getUserName();
    proxyType = connectionSettings.getProxyType();
    proxyHost = connectionSettings.getProxyHost();
    proxyPort = connectionSettings.getProxyPort();
    proxyUser = connectionSettings.getProxyUser();
    proxyPassword = connectionSettings.getProxyPassword();
    started = false;
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

private void appendEntries(long term, ServerInfo leaderId, long leaderCommit, long prevLogIndex,
        long prevLogTerm, List<RaftLogEntry> entries, long maxIndex) {
    Preconditions.checkNotNull(entries);

    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;/* w  w  w. j a  va 2  s .c o  m*/
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection connection = connections.get(server);
        LOG.debug(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
        Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), connection,
                getRaftNode().getRaftLog(), getRaftNode().getServerInfo(), term, leaderCommit, prevLogIndex,
                prevLogTerm, entries, maxIndex));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:org.pentaho.osgi.i18n.impl.LocalizationManager.java

public void bundleChanged(Bundle bundle) throws IOException, ParseException {
    boolean rebuildCache;
    synchronized (configMap) {
        rebuildCache = configMap.remove(bundle.getBundleId()) != null;
    }/* w w  w .  j a v  a  2s  . c om*/

    if (bundle.getState() == Bundle.ACTIVE) {
        Map<String, OSGIResourceBundleFactory> configEntry = new HashMap<String, OSGIResourceBundleFactory>();
        OSGIResourceBundleFactory bundleFactory;
        Enumeration<URL> urlEnumeration = bundle.findEntries(OSGIResourceNamingConvention.RESOURCES_ROOT_FOLDER,
                "*" + OSGIResourceNamingConvention.RESOURCES_DEFAULT_EXTENSION + "*", true);
        if (urlEnumeration != null) {
            while (urlEnumeration.hasMoreElements()) {
                URL url = urlEnumeration.nextElement();
                if (url != null) {
                    String fileName = url.getFile();
                    String relativeName = fileName;
                    String name = getPropertyName(fileName);
                    int priority = OSGIResourceNamingConvention.getPropertyPriority(fileName);
                    bundleFactory = new OSGIResourceBundleFactory(name, relativeName, url, priority);
                    configEntry.put(relativeName, bundleFactory);
                    rebuildCache = true;
                }
            }
        }

        if (!configEntry.isEmpty()) {
            synchronized (configMap) {
                configMap.put(bundle.getBundleId(), configEntry);
            }
            rebuildCache = true;
        }
    }
    if (rebuildCache) {
        synchronized (configMap) {
            if (executorService == null) {
                executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = Executors.defaultThreadFactory().newThread(r);
                        thread.setDaemon(true);
                        thread.setName("Localization pool");
                        return thread;
                    }
                });
            }
            cache = executorService.submit(new OSGIResourceBundleCacheCallable(
                    new HashMap<Long, Map<String, OSGIResourceBundleFactory>>(configMap)));
        }
    }
}

From source file:org.rhq.core.system.SigarAccessHandler.java

SigarAccessHandler(SigarFactory sigarFactory) {
    this.sigarFactory = sigarFactory;
    sharedSigarLock = new ReentrantLock();
    localSigarLock = new ReentrantLock();
    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();

        private AtomicInteger threadCounter = new AtomicInteger(0);

        @Override/*  w ww  .  j a va  2s .  c  o m*/
        public Thread newThread(Runnable runnable) {
            Thread thread = defaultThreadFactory.newThread(runnable);
            thread.setName("SigarAccessHandler-" + threadCounter.incrementAndGet());
            // With daemon threads, there is no need to call #shutdown on the executor to let the JVM go down
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduledExecutorService.scheduleWithFixedDelay(new ThresholdChecker(), 1, 5, MINUTES);
    localSigarInstancesCount = 0;
    closed = false;
}