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.apache.hadoop.fs.s3r.S3RFileSystem.java

/**
 * Returns a {@link ThreadFactory} that names each created thread uniquely,
 * with a common prefix.//  w w w.ja  v a 2 s  .  c  o  m
 * @param prefix The prefix of every created Thread's name
 * @return a {@link 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 poolNum = poolNumber.getAndIncrement();
        final ThreadGroup group = threadGroup;

        @Override
        public Thread newThread(Runnable r) {
            final String name = prefix + "-pool" + poolNum + "-t" + threadNumber.getAndIncrement();
            return new Thread(group, r, name);
        }
    };
}

From source file:com.baidu.asynchttpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w  w w .  j a  va2s  .  co  m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {

            Thread t = new Thread(r, "AsyncHttpClient #" + mCount.getAndIncrement());
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != (Thread.NORM_PRIORITY - 1))
                t.setPriority((Thread.NORM_PRIORITY - 1));
            return t;
        }
    });

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.openecomp.sdc.be.dao.titan.TitanGraphClient.java

public TitanGraphClient() {
    super();//w  w  w .  ja  v  a2  s.c o  m

    // Initialize a single threaded scheduler for health-check
    this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Titan-Health-Check-Task");
        }
    });

    healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
            .getTitanHealthCheckReadTimeout(2);
    reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration()
            .getTitanReconnectIntervalInSeconds(3);

    logger.info("** TitanGraphClient created");
}

From source file:org.helios.netty.jmx.MetricCollector.java

/**
 * Creates a new MetricCollector// www. j a  v a  2  s  .  co m
 * @param period The period of collection
 */
private MetricCollector(long period) {
    super();
    haveNioMXBean = ManagementFactory.getPlatformMBeanServer().isRegistered(directNio);
    this.period = period;
    try {
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, OBJECT_NAME);
        scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r,
                        OBJECT_NAME.getKeyProperty("service") + "Thread#" + serial.incrementAndGet());
                t.setDaemon(true);
                return t;
            }
        });
        initMetricNames();
        scheduler.schedule(this, period, TimeUnit.MILLISECONDS);
        log.info("Started MetricCollector with a period of " + period + " ms.");
    } catch (Exception e) {
        throw new RuntimeException("Failed to create MetricCollector", e);
    }
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

@Override
public void initialize(final UserGroupProviderInitializationContext initializationContext)
        throws AuthorizerCreationException {
    ldapSync = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        final ThreadFactory factory = Executors.defaultThreadFactory();

        @Override/*from w w  w.ja  va 2 s.  c  o m*/
        public Thread newThread(Runnable r) {
            final Thread thread = factory.newThread(r);
            thread.setName(String.format("%s (%s) - background sync thread", getClass().getSimpleName(),
                    initializationContext.getIdentifier()));
            return thread;
        }
    });
}

From source file:com.mgmtp.jfunk.core.JFunk.java

private ExecutorService createExecutorService() {
    return new FixedSizeThreadExecutor(min(threadCount, scripts.size()), new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override/*from ww  w . j  a v a2  s .  c  om*/
        public Thread newThread(final Runnable r) {
            int id = threadNumber.getAndIncrement();
            String threadName = StringUtils.leftPad(String.valueOf(id), 2, "0");
            Thread th = new Thread(r);
            th.setName(threadName);
            return th;
        }
    });
}

From source file:org.apache.nifi.registry.security.ldap.tenants.LdapUserGroupProvider.java

@Override
public void initialize(final UserGroupProviderInitializationContext initializationContext)
        throws SecurityProviderCreationException {
    ldapSync = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        final ThreadFactory factory = Executors.defaultThreadFactory();

        @Override/*from w  w  w. j a v a  2  s .  com*/
        public Thread newThread(Runnable r) {
            final Thread thread = factory.newThread(r);
            thread.setName(String.format("%s (%s) - background sync thread", getClass().getSimpleName(),
                    initializationContext.getIdentifier()));
            return thread;
        }
    });
}

From source file:org.apache.tuscany.sca.implementation.bpel.ode.EmbeddedODEServer.java

private void initBpelServer() {
    if (__log.isDebugEnabled()) {
        __log.debug("ODE initializing");
    }/* ww  w  .  ja va2s.c o m*/
    ThreadFactory threadFactory = new ThreadFactory() {
        int threadNumber = 0;

        public Thread newThread(Runnable r) {
            threadNumber += 1;
            Thread t = new Thread(r, "ODEServer-" + threadNumber);
            t.setDaemon(true);
            return t;
        }
    };

    _executorService = Executors.newCachedThreadPool(threadFactory);

    // executor service for long running bulk transactions
    ExecutorService _polledRunnableExecutorService = Executors.newCachedThreadPool(new ThreadFactory() {
        int threadNumber = 0;

        public Thread newThread(Runnable r) {
            threadNumber += 1;
            Thread t = new Thread(r, "PolledRunnable-" + threadNumber);
            t.setDaemon(true);
            return t;
        }
    });

    _bpelServer = new BpelServerImpl();
    _scheduler = createScheduler();
    _scheduler.setJobProcessor(_bpelServer);

    BpelServerImpl.PolledRunnableProcessor polledRunnableProcessor = new BpelServerImpl.PolledRunnableProcessor();
    polledRunnableProcessor.setPolledRunnableExecutorService(_polledRunnableExecutorService);
    polledRunnableProcessor.setContexts(_bpelServer.getContexts());
    //_scheduler.setPolledRunnableProcesser(polledRunnableProcessor);

    _bpelServer.setDaoConnectionFactory(_daoCF);
    _bpelServer.setInMemDaoConnectionFactory(new BpelDAOConnectionFactoryImpl(_scheduler));

    _bpelServer.setEndpointReferenceContext(new ODEEprContext());
    _bpelServer.setMessageExchangeContext(new ODEMessageExchangeContext(this));
    _bpelServer.setBindingContext(new ODEBindingContext());
    _bpelServer.setScheduler(_scheduler);
    if (_config.isDehydrationEnabled()) {
        CountLRUDehydrationPolicy dehy = new CountLRUDehydrationPolicy();
        dehy.setProcessMaxAge(_config.getDehydrationMaximumAge());
        dehy.setProcessMaxCount(_config.getDehydrationMaximumCount());
        _bpelServer.setDehydrationPolicy(dehy);
    }

    _bpelServer.setConfigProperties(_config.getProperties());
    _bpelServer.init();
    _bpelServer.setInstanceThrottledMaximumCount(_config.getInstanceThrottledMaximumCount());
    _bpelServer.setProcessThrottledMaximumCount(_config.getProcessThrottledMaximumCount());
    _bpelServer.setProcessThrottledMaximumSize(_config.getProcessThrottledMaximumSize());
    _bpelServer.setHydrationLazy(_config.isHydrationLazy());
    _bpelServer.setHydrationLazyMinimumSize(_config.getHydrationLazyMinimumSize());

    // Register event listener on the BPEL server
    _bpelServer.registerBpelEventListener(new ODEEventListener(this, _bpelServer));
}

From source file:org.apache.hadoop.fs.s3r.S3RFileSystem.java

/**
 * Get a named {@link ThreadFactory} that just builds daemon threads.
 * @param prefix name prefix for all threads created from the factory
 * @return a thread factory that creates named, daemon threads with
 *         the supplied exception handler and normal priority
 *//*from   w  w w. j a  v  a  2s. co m*/
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    };
}

From source file:ca.sqlpower.architect.enterprise.ArchitectClientSideSession.java

/**
 * This constructor is only used for testing. This constructor allows users
 * to specify an executor to use as the foreground thread instead of using
 * the normal EDT. This is handy for ensuring all of the events occur on the
 * correct thread and updates do not conflict with persists. If the executor
 * is null then the foreground thread will just execute the runnables on the
 * current thread.// ww w  .  java2 s.co  m
 */
public ArchitectClientSideSession(ArchitectSessionContext context, String name, ProjectLocation projectLocation,
        boolean useThreadPool) throws SQLObjectException {
    super(context, name, new ArchitectSwingProject());

    this.projectLocation = projectLocation;
    this.useThreadPool = useThreadPool;
    this.foregroundThreadExecutor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.MINUTES,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread newThread = new Thread(r);
                    foregroundExecutorThread.add(newThread);
                    return newThread;
                }
            });
    foregroundThreadExecutor.allowCoreThreadTimeOut(false);
    dataSourceCollectionUpdater = new ArchitectDataSourceCollectionUpdater(projectLocation);
    this.isEnterpriseSession = true;

    setupSnapshots();

    String ddlgClass = prefs.get(this.projectLocation.getUUID() + ".ddlg", null);
    if (ddlgClass != null) {
        try {
            DDLGenerator ddlg = (DDLGenerator) Class
                    .forName(ddlgClass, true, ArchitectClientSideSession.class.getClassLoader()).newInstance();
            setDDLGenerator(ddlg);
            ddlg.setTargetCatalog(prefs.get(this.projectLocation.getUUID() + ".targetCatalog", null));
            ddlg.setTargetSchema(prefs.get(this.projectLocation.getUUID() + ".targetSchema", null));
        } catch (Exception e) {
            createUserPrompter("Cannot load DDL settings due to missing class " + ddlgClass,
                    UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, null, "OK");
            logger.error("Cannot find DDL Generator for class " + ddlgClass
                    + ", ddl generator properties are not loaded.");
        }
    }

    outboundHttpClient = ClientSideSessionUtils.createHttpClient(projectLocation.getServiceInfo(), cookieStore);
    dataSourceCollection = getDataSources();

    sessionPersister = new ArchitectSessionPersister("inbound-" + projectLocation.getUUID(), getWorkspace(),
            new ArchitectPersisterSuperConverter(dataSourceCollection, getWorkspace()));
    sessionPersister.setWorkspaceContainer(this);

    jsonMessageDecoder = new SPJSONMessageDecoder(sessionPersister);

    updater = new ArchitectNetworkConflictResolver(projectLocation, jsonMessageDecoder,
            ClientSideSessionUtils.createHttpClient(projectLocation.getServiceInfo(), cookieStore),
            outboundHttpClient, this);

    jsonPersister = new SPJSONPersister(updater);

    verifyServerLicense(projectLocation);
}