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:self.philbrown.droidQuery.Ajax.java

/**
 * Constructor/*w  w  w. ja va2 s.co m*/
 * @param options used to configure this task
 */
public Ajax(AjaxOptions options) {
    this.options = options;
    if (options.url() == null) {
        throw new NullPointerException("Cannot call Ajax with null URL!");
    }
    this.mHandler = new Handler();
    this.executor = Executors.newFixedThreadPool(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.setPriority(Ajax.this.options.priority());
            return t;
        }
    });
}

From source file:com.couchbase.lite.Manager.java

/**
 * Constructor/*from  w  w  w.ja  va2  s .c  om*/
 *
 * @throws java.lang.SecurityException - Runtime exception that can be thrown by File.mkdirs()
 */
@InterfaceAudience.Public
public Manager(Context context, ManagerOptions options) throws IOException {

    Log.d(Database.TAG, "Starting Manager version: %s", Manager.VERSION);

    this.context = context;
    this.directoryFile = context.getFilesDir();
    this.options = (options != null) ? options : DEFAULT_OPTIONS;
    this.databases = new HashMap<String, Database>();
    this.encryptionKeys = new HashMap<String, Object>();
    this.replications = new ArrayList<Replication>();

    if (!directoryFile.exists()) {
        directoryFile.mkdirs();
    }
    if (!directoryFile.isDirectory()) {
        throw new IOException(
                String.format(Locale.ENGLISH, "Unable to create directory for: %s", directoryFile));
    }

    upgradeOldDatabaseFiles(directoryFile);

    // this must be a single threaded executor due to contract w/ Replication object
    // which must run on either:
    // - a shared single threaded executor
    // - its own single threaded executor
    workExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "CBLManagerWorkExecutor");
        }
    });
}

From source file:com.codefollower.lealone.omid.tso.TSOHandler.java

/**
 * Constructor/* w  w w . jav  a  2  s . c om*/
 * @param channelGroup
 */
public TSOHandler(ChannelGroup channelGroup, TSOState state, int batchSize) {
    this.channelGroup = channelGroup;
    this.timestampOracle = state.getTimestampOracle();
    this.sharedState = state;

    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.batchSize = batchSize;
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely, with a common prefix.
 * /*  w ww.j  a  v  a 2  s .  c o  m*/
 * @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);
        }
    };
}

From source file:org.everrest.websockets.client.WSClient.java

/**
 * Create new websocket client./*w  w  w  . j  av  a2s  .  co m*/
 *
 * @param target
 *         connection URI, e.g. <i>ws://localhost:8080/websocket</i>
 * @param maxMessagePayloadSize
 *         max size of data in message. If received message contains payload greater then this value IOException thrown
 *         when read such message
 * @param listeners
 *         message listeners
 * @throws IllegalArgumentException
 *         if any of the following conditions are met:
 *         <ul>
 *         <li><code>target</code> is <code>null</code></li>
 *         <li>protocol specified in <code>target</code> not supported</li>
 *         <li><code>maxMessagePayloadSize</code> is zero or negative</li>
 *         <li><code>listeners</code> is <code>null</code></li>
 *         </ul>
 * @see #DEFAULT_MAX_MESSAGE_PAYLOAD_SIZE
 * @see MessageConverter
 */
public WSClient(URI target, int maxMessagePayloadSize, ClientMessageListener... listeners) {
    if (target == null) {
        throw new IllegalArgumentException("Connection URI may not be null. ");
    }

    if (!"ws".equals(target.getScheme())) {
        // TODO: add 'wss' support
        throw new IllegalArgumentException(String.format("Unsupported scheme: %s", target.getScheme()));
    }

    if (maxMessagePayloadSize < 1) {
        throw new IllegalArgumentException(
                String.format("Invalid max message payload size: %d", maxMessagePayloadSize));
    }

    if (listeners == null) {
        throw new IllegalArgumentException("listeners may not be null. ");
    }

    this.target = target;
    this.maxMessagePayloadSize = maxMessagePayloadSize;
    executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            final Thread t = new Thread(r, "everrest.WSClient" + sequence.getAndIncrement());
            t.setDaemon(true);
            return t;
        }
    });
    this.listeners = new ArrayList<>(listeners.length);
    Collections.addAll(this.listeners, listeners);

    secWebSocketKey = generateSecKey();
}

From source file:com.clustercontrol.systemlog.service.SystemLogMonitor.java

@Override
public synchronized void start() {
    _executor = new MonitoredThreadPoolExecutor(_threadSize, _threadSize, 0L, TimeUnit.MICROSECONDS,
            new LinkedBlockingQueue<Runnable>(_queueSize), new ThreadFactory() {
                private volatile int _count = 0;

                @Override/*from w  w w  . j a v  a2s . c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "SystemLogFilter-" + _count++);
                }
            }, new SystemLogRejectionHandler());
}

From source file:com.datatorrent.lib.io.WebSocketOutputOperator.java

private void openConnection() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    final AsyncHttpClientConfigBean config = new AsyncHttpClientConfigBean();
    config.setIoThreadMultiplier(ioThreadMultiplier);
    config.setApplicationThreadPool(Executors.newCachedThreadPool(new ThreadFactory() {
        @Override/*from  w  w  w.j a  v a2s  .co  m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(ClassUtils.getShortClassName(this.getClass()) + "-AsyncHttpClient-" + count++);
            return t;
        }

    }));
    client = new AsyncHttpClient(config);
    uri = URI.create(uri.toString()); // force reparse after deserialization
    LOG.info("Opening URL: {}", uri);
    connection = client.prepareGet(uri.toString())
            .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new WebSocketTextListener() {
                @Override
                public void onMessage(String string) {
                }

                @Override
                public void onOpen(WebSocket ws) {
                    LOG.debug("Connection opened");
                }

                @Override
                public void onClose(WebSocket ws) {
                    LOG.debug("Connection closed.");
                }

                @Override
                public void onError(Throwable t) {
                    LOG.error("Caught exception", t);
                }

            }).build()).get(5, TimeUnit.SECONDS);
}

From source file:org.apache.nifi.registry.bootstrap.RunNiFiRegistry.java

public RunNiFiRegistry(final File bootstrapConfigFile, final boolean verbose) throws IOException {
    this.bootstrapConfigFile = bootstrapConfigFile;

    loggingExecutor = Executors.newFixedThreadPool(2, new ThreadFactory() {
        @Override//from w w  w .j  a  va2  s . co  m
        public Thread newThread(final Runnable runnable) {
            final Thread t = Executors.defaultThreadFactory().newThread(runnable);
            t.setDaemon(true);
            t.setName("NiFi logging handler");
            return t;
        }
    });
}

From source file:eagle.jobrunning.crawler.RunningJobCrawlerImpl.java

private void startJobConfigProcessThread() {
    int configThreadCount = DEFAULT_CONFIG_THREAD_COUNT;
    LOG.info("Job Config crawler main thread started, pool size: " + DEFAULT_CONFIG_THREAD_COUNT);

    ThreadFactory factory = new ThreadFactory() {
        private final AtomicInteger count = new AtomicInteger(0);

        public Thread newThread(Runnable runnable) {
            count.incrementAndGet();//from www . ja va  2  s .com
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
            thread.setName("config-crawler-workthread-" + count.get());
            return thread;
        }
    };

    ThreadPoolExecutor pool = new ThreadPoolExecutor(configThreadCount, configThreadCount, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), factory);

    while (true) {
        JobContext context;
        try {
            context = queueOfConfig.take();
            LOG.info("queueOfConfig size: " + queueOfConfig.size());
            Runnable configCrawlerThread = new ConfigWorkTask(new JobContext(context), fetcher, callback, this);
            pool.execute(configCrawlerThread);
        } catch (InterruptedException e) {
            LOG.warn("Got an InterruptedException: " + e.getMessage());
        } catch (RejectedExecutionException e2) {
            LOG.warn("Got RejectedExecutionException: " + e2.getMessage());
        } catch (Throwable t) {
            LOG.warn("Got an throwable t, " + t.getMessage());
        }
    }
}

From source file:org.apache.sentry.service.thrift.SentryService.java

public SentryService(Configuration conf) {
    this.conf = conf;
    int port = conf.getInt(ServerConfig.RPC_PORT, ServerConfig.RPC_PORT_DEFAULT);
    if (port == 0) {
        port = findFreePort();/*from  w w  w.  java 2 s . co  m*/
        conf.setInt(ServerConfig.RPC_PORT, port);
    }
    this.address = NetUtils
            .createSocketAddr(conf.get(ServerConfig.RPC_ADDRESS, ServerConfig.RPC_ADDRESS_DEFAULT), port);
    LOGGER.info("Configured on address " + address);
    kerberos = ServerConfig.SECURITY_MODE_KERBEROS
            .equalsIgnoreCase(conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
    maxThreads = conf.getInt(ServerConfig.RPC_MAX_THREADS, ServerConfig.RPC_MAX_THREADS_DEFAULT);
    minThreads = conf.getInt(ServerConfig.RPC_MIN_THREADS, ServerConfig.RPC_MIN_THREADS_DEFAULT);
    maxMessageSize = conf.getLong(ServerConfig.SENTRY_POLICY_SERVER_THRIFT_MAX_MESSAGE_SIZE,
            ServerConfig.SENTRY_POLICY_SERVER_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
    if (kerberos) {
        // Use Hadoop libraries to translate the _HOST placeholder with actual hostname
        try {
            String rawPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL),
                    ServerConfig.PRINCIPAL + " is required");
            principal = SecurityUtil.getServerPrincipal(rawPrincipal, address.getAddress());
        } catch (IOException io) {
            throw new RuntimeException("Can't translate kerberos principal'", io);
        }
        LOGGER.info("Using kerberos principal: " + principal);

        principalParts = SaslRpcServer.splitKerberosName(principal);
        Preconditions.checkArgument(principalParts.length == 3,
                "Kerberos principal should have 3 parts: " + principal);
        keytab = Preconditions.checkNotNull(conf.get(ServerConfig.KEY_TAB),
                ServerConfig.KEY_TAB + " is required");
        File keytabFile = new File(keytab);
        Preconditions.checkState(keytabFile.isFile() && keytabFile.canRead(),
                "Keytab " + keytab + " does not exist or is not readable.");
    } else {
        principal = null;
        principalParts = null;
        keytab = null;
    }
    serviceExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        private int count = 0;

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, SentryService.class.getSimpleName() + "-" + (count++));
        }
    });
    webServerPort = conf.getInt(ServerConfig.SENTRY_WEB_PORT, ServerConfig.SENTRY_WEB_PORT_DEFAULT);
    status = Status.NOT_STARTED;
}