Example usage for com.google.common.util.concurrent ThreadFactoryBuilder build

List of usage examples for com.google.common.util.concurrent ThreadFactoryBuilder build

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ThreadFactoryBuilder build.

Prototype

public ThreadFactory build() 

Source Link

Document

Returns a new thread factory using the options supplied during the building process.

Usage

From source file:org.apache.hadoop.hbase.replication.regionserver.HFileReplicator.java

public HFileReplicator(Configuration sourceClusterConf, String sourceBaseNamespaceDirPath,
        String sourceHFileArchiveDirPath, Map<String, List<Pair<byte[], List<String>>>> tableQueueMap,
        Configuration conf, Connection connection) throws IOException {
    this.sourceClusterConf = sourceClusterConf;
    this.sourceBaseNamespaceDirPath = sourceBaseNamespaceDirPath;
    this.sourceHFileArchiveDirPath = sourceHFileArchiveDirPath;
    this.bulkLoadHFileMap = tableQueueMap;
    this.conf = conf;
    this.connection = connection;

    userProvider = UserProvider.instantiate(conf);
    fsDelegationToken = new FsDelegationToken(userProvider, "renewer");
    this.hbaseStagingDir = conf.get("hbase.bulkload.staging.dir");
    this.maxCopyThreads = this.conf.getInt(REPLICATION_BULKLOAD_COPY_MAXTHREADS_KEY,
            REPLICATION_BULKLOAD_COPY_MAXTHREADS_DEFAULT);
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setNameFormat("HFileReplicationCallable-%1$d");
    this.exec = new ThreadPoolExecutor(maxCopyThreads, maxCopyThreads, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), builder.build());
    this.exec.allowCoreThreadTimeOut(true);
    this.copiesPerThread = conf.getInt(REPLICATION_BULKLOAD_COPY_HFILES_PERTHREAD_KEY,
            REPLICATION_BULKLOAD_COPY_HFILES_PERTHREAD_DEFAULT);

    sinkFs = FileSystem.get(conf);
}

From source file:org.apache.bookkeeper.meta.AbstractZkLedgerManager.java

/**
 * ZooKeeper-based Ledger Manager Constructor
 *
 * @param conf//w w  w .  ja  va 2s. com
 *          Configuration object
 * @param zk
 *          ZooKeeper Client Handle
 */
protected AbstractZkLedgerManager(AbstractConfiguration conf, ZooKeeper zk) {
    this.conf = conf;
    this.zk = zk;
    this.ledgerRootPath = conf.getZkLedgersRootPath();
    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder().setNameFormat("ZkLedgerManagerScheduler-%d");
    this.scheduler = Executors.newSingleThreadScheduledExecutor(tfb.build());
    LOG.debug("Using AbstractZkLedgerManager with root path : {}", ledgerRootPath);
}

From source file:com.google.worldcoin.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.wallet = checkNotNull(wallet);
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file);
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = new Callable<Void>() {
        @Override//from  w ww . j  a  va  2  s .com
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet, last seen block is {}/{}", wallet.getLastBlockSeenHeight(),
                    wallet.getLastBlockSeenHash());
            saveNowInternal();
            return null;
        }
    };
}

From source file:io.bitsquare.storage.FileManager.java

public FileManager(File dir, File storageFile, long delay, TimeUnit delayTimeUnit) {
    this.dir = dir;
    this.storageFile = storageFile;

    ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("FileManager thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.

    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);

    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = () -> {
        // Runs in an auto save thread.
        if (!savePending.getAndSet(false)) {
            // Some other scheduled request already beat us to it.
            return null;
        }//from w  w  w . ja v a2  s  . c o m
        saveNowInternal(serializable);
        return null;
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                FileManager.this.shutdown();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.coinomi.core.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.wallet = checkNotNull(wallet, "Cannot save a null wallet");
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file, "Cannot save to a null file");
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit, "Cannot use a null delay time unit");

    this.saver = new Callable<Void>() {
        @Override//from www  . j a v a 2 s.c o  m
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet");
            saveNowInternal();
            return null;
        }
    };
}

From source file:com.reddcoin.core.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.wallet = checkNotNull(wallet);
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file);
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = new Callable<Void>() {
        @Override//from   w w  w .  j ava 2 s  .  c  o m
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet");
            saveNowInternal();
            return null;
        }
    };
}

From source file:org.wisdom.executors.ManagedScheduledExecutorServiceImpl.java

public ManagedScheduledExecutorServiceImpl(String name, ThreadType tu, long hungTime, int coreSize,
        int priority, List<ExecutionContextService> ecs) {

    super(name, hungTime, ecs);
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(tu == ThreadType.DAEMON)
            .setNameFormat(name + "-%s").setPriority(priority)
            .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override/*w  w  w .  j a v a 2 s . com*/
                public void uncaughtException(Thread t, Throwable e) {
                    logger.error("Uncaught exception in thread '{}'", t.getName(), e);
                }
            });

    setInternalPool(new ScheduledThreadPoolExecutor(coreSize, builder.build()));
}

From source file:com.matthewmitchell.peercoinj.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.wallet = checkNotNull(wallet);
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file);
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = new Callable<Void>() {
        @Override/* w  ww .java 2  s  .co  m*/
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet, last seen block is {}/{}", wallet.getLastBlockSeenHeight(),
                    wallet.getLastBlockSeenHash());
            saveNowInternal();
            return null;
        }
    };
}

From source file:org.opendaylight.vpnservice.interfacemgr.pmcounters.NodeConnectorStatsImpl.java

private ThreadFactory getThreadFactory(String threadNameFormat) {
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setNameFormat(threadNameFormat);
    builder.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override/*w w  w. j a  v a 2 s . co  m*/
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Received Uncaught Exception event in Thread: {}", t.getName(), e);
        }
    });
    return builder.build();
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceManager.java

/**
 * Creates a replication manager and sets the watch on all the other registered region servers
 * @param replicationQueues the interface for manipulating replication queues
 * @param replicationPeers/* ww w  . j av a2s .  co m*/
 * @param replicationTracker
 * @param conf the configuration to use
 * @param stopper the stopper object for this region server
 * @param fs the file system to use
 * @param logDir the directory that contains all hlog directories of live RSs
 * @param oldLogDir the directory where old logs are archived
 * @param clusterId
 */
public ReplicationSourceManager(final ReplicationQueues replicationQueues,
        final ReplicationPeers replicationPeers, final ReplicationTracker replicationTracker,
        final Configuration conf, final Stoppable stopper, final FileSystem fs, final Path logDir,
        final Path oldLogDir, final UUID clusterId) {
    this.sources = new ArrayList<ReplicationSourceInterface>();
    this.replicationQueues = replicationQueues;
    this.replicationPeers = replicationPeers;
    this.replicationTracker = replicationTracker;
    this.stopper = stopper;
    this.hlogsById = new HashMap<String, SortedSet<String>>();
    this.oldsources = new ArrayList<ReplicationSourceInterface>();
    this.conf = conf;
    this.fs = fs;
    this.logDir = logDir;
    this.oldLogDir = oldLogDir;
    this.sleepBeforeFailover = conf.getLong("replication.sleep.before.failover", 2000);
    this.clusterId = clusterId;
    this.replicationTracker.registerListener(this);
    this.replicationPeers.getAllPeerIds();
    // It's preferable to failover 1 RS at a time, but with good zk servers
    // more could be processed at the same time.
    int nbWorkers = conf.getInt("replication.executor.workers", 1);
    // use a short 100ms sleep since this could be done inline with a RS startup
    // even if we fail, other region servers can take care of it
    this.executor = new ThreadPoolExecutor(nbWorkers, nbWorkers, 100, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
    tfb.setNameFormat("ReplicationExecutor-%d");
    this.executor.setThreadFactory(tfb.build());
    this.rand = new Random();
}