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:com.haulmont.cuba.core.app.scheduling.RunnerBean.java

@PostConstruct
public void init() {
    int nThreads = configuration.getConfig(ServerConfig.class).getSchedulingThreadPoolSize();
    executorService = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override//from   w  ww .j  a v a  2 s. co  m
        public Thread newThread(@Nonnull Runnable r) {
            Thread thread = new Thread(r, "ScheduledRunnerThread-" + threadNumber.getAndIncrement());
            thread.setDaemon(true);
            return thread;
        }
    });
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static ScheduledExecutorService createScheduledExecutorService(final int poolSz,
        final String threadName) {
    return Executors.newScheduledThreadPool(poolSz, new ThreadFactory() {
        private AtomicInteger threadNum = new AtomicInteger(0);

        @Override/*from   w  ww  . ja va2  s . c  o m*/
        public Thread newThread(Runnable r) {
            if (poolSz == 1)
                return new Thread(r, threadName);
            else
                return new Thread(r, threadName + threadNum.incrementAndGet());
        }
    });
}

From source file:org.killbill.bus.DefaultPersistentBus.java

@Inject
public DefaultPersistentBus(@Named(QUEUE_NAME) final IDBI dbi, final Clock clock,
        final PersistentBusConfig config, final MetricRegistry metricRegistry,
        final DatabaseTransactionNotificationApi databaseTransactionNotificationApi) {
    super("Bus", Executors.newFixedThreadPool(config.getNbThreads(), new ThreadFactory() {
        @Override/*from   w w w  . ja va2s.c  o  m*/
        public Thread newThread(final Runnable r) {
            return new Thread(new ThreadGroup(EVENT_BUS_GROUP_NAME), r, config.getTableName() + "-th");
        }
    }), config.getNbThreads(), config);
    final PersistentBusSqlDao sqlDao = dbi.onDemand(PersistentBusSqlDao.class);
    this.clock = clock;
    final String dbBackedQId = "bus-" + config.getTableName();
    this.dao = new DBBackedQueue<BusEventModelDao>(clock, sqlDao, config, dbBackedQId, metricRegistry,
            databaseTransactionNotificationApi);
    this.eventBusDelegate = new EventBusDelegate("Killbill EventBus");
    this.dispatchTimer = metricRegistry.timer(MetricRegistry.name(DefaultPersistentBus.class, "dispatch"));
    this.isStarted = new AtomicBoolean(false);
}

From source file:com.btoddb.fastpersitentqueue.JournalMgr.java

/**
 *
 * @throws IOException//from   ww  w .j a  v  a 2  s.  co  m
 */
public void init() throws IOException {
    flushExec = new ScheduledThreadPoolExecutor(numberOfFlushWorkers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.setName("FPQ-FSync");
            return t;
        }
    });
    generalExec = Executors.newFixedThreadPool(numberOfGeneralWorkers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.setName("FPQ-GeneralWork");
            return t;
        }
    });

    prepareJournaling();

    currentJournalDescriptor = createAndAddNewJournal();
}

From source file:com.clustercontrol.nodemap.util.SearchConnectionExecutor.java

/**
 * ???ExecutorService<BR>/*from  w w  w  . j  a  v a 2s  .  c o m*/
 *
 * @param scopeId ?ID
 * @param isL3 L3????true L2????false?
 * @throws HinemosUnknown
 */
public SearchConnectionExecutor(String scopeId, boolean isL3) throws HinemosUnknown {
    start = HinemosTime.currentTimeMillis();
    this.isL3 = isL3;

    // ??SNMP?
    int threadSize = HinemosPropertyUtil
            .getHinemosPropertyNum("nodemap.search.connection.thread", Long.valueOf(4)).intValue();
    m_log.info("static() : Thread Size = " + threadSize);
    m_log.info("SearchConnectionExecutor() : scopeId=" + scopeId + ",L3=" + isL3);

    // ??????OID?
    String oid = isL3 ? SearchConnectionProperties.DEFAULT_OID_ARP : SearchConnectionProperties.DEFAULT_OID_FDB;
    oidSet = new HashSet<String>();
    oidSet.add(oid);

    facilityIdList = bean.getFacilityIdList(scopeId, RepositoryControllerBean.ONE_LEVEL);

    _executor = new MonitoredThreadPoolExecutor(threadSize, threadSize, 0L, TimeUnit.MICROSECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private volatile int _count = 0;

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "SearchConnectionExecutor-" + _count++);
                }
            }, new ThreadPoolExecutor.AbortPolicy());

    now = HinemosTime.currentTimeMillis();
    m_log.debug("Constructer : " + (now - start) + "ms");
}

From source file:com.astamuse.asta4d.web.util.timeout.DefaultSessionAwareExpirableDataManager.java

@Override
public void start() {
    service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override//from  w  ww  .j a  v  a2s .  co m
        public Thread newThread(Runnable r) {
            return new Thread(r, checkThreadName);
        }
    });

    // start check thread
    service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            List<Entry<String, DataHolder>> entries = new ArrayList<>(dataMap.entrySet());
            long currentTime = System.currentTimeMillis();
            int removedCounter = 0;
            Object existing;
            for (Entry<String, DataHolder> entry : entries) {
                if (entry.getValue().isExpired(currentTime)) {
                    existing = dataMap.remove(entry.getKey());
                    if (existing != null) {// we removed it successfully
                        removedCounter++;
                    }
                }
            }
            if (removedCounter > 0) {
                addCount(-removedCounter);
            }
        }
    }, expirationCheckPeriodInMilliseconds, expirationCheckPeriodInMilliseconds, TimeUnit.MILLISECONDS);
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitor.java

public SdkCredentialsFileContentMonitor(File target, long pollingIntervalInMillis,
        FileAlterationListener listener) {

    _target = target;/*from www  . ja  v a 2  s . co  m*/

    // IllegalArgumentException is expected if target.getParentFile == null
    _observer = new FileAlterationObserver(target.getParentFile(), new FileFilter() {
        public boolean accept(File file) {
            return file.equals(_target);
        }
    });

    _monitor = new FileAlterationMonitor(pollingIntervalInMillis);
    _listener = listener;

    _observer.addListener(_listener);
    _monitor.addObserver(_observer);

    // Use daemon thread to avoid thread leakage
    _monitor.setThreadFactory(new ThreadFactory() {
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.setDaemon(true);
            t.setName("aws-credentials-file-monitor-thread");
            return t;
        }
    });
}

From source file:cloudlens.notebook.JSInterpreter.java

public InterpreterResult interpret(Callable<BlockObject> task, CL cl) {
    if (cl.out instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.out).reset();
    }//www.j a v a 2 s.  c om
    if (cl.err instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) cl.err).reset();
    }
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r) {
                @Override
                public void interrupt() {
                    stop();
                }
            };
        }
    });
    cl.future = executor.submit(task);
    final Gson gson = new GsonBuilder().create();
    try {
        final BlockObject obj = cl.future.get();
        cl.outWriter.flush();
        cl.errWriter.flush();
        if (obj instanceof InterpreterResult) {
            return (InterpreterResult) obj;
        }
        if (cl.out instanceof ByteArrayOutputStream && ((ByteArrayOutputStream) cl.out).size() == 0) {
            if (null != obj && obj.isMapArray()) {
                final Map<String, Map<String, Object>> entries = obj.asMapArray();
                cl.outWriter.print("%table\n");
                int i = 0;
                for (final Map<?, ?> entry : entries.values()) {
                    cl.outWriter.print("\n");
                    if (++i > maxResult) {
                        cl.outWriter.println(
                                "%html <font color=red>Results are limited by zeppelin.cloudlens.maxResult = "
                                        + maxResult + ".</font>");
                        break;
                    }
                    for (final Map.Entry<?, ?> field : entry.entrySet()) {
                        cl.outWriter.print("%html <font color=blue>"
                                + StringEscapeUtils.escapeHtml4(field.getKey().toString()) + "</font>:"
                                + StringEscapeUtils.escapeHtml4(gson.toJson(field.getValue()).toString())
                                + "\t");
                    }
                }
            } else {
                cl.engine.bind("__Result__", obj);
                cl.engine.eval(
                        "print(JSON.stringify(__Result__, function(key, val) { if (typeof val === 'function') return val + ''; return val; }, 2))");
            }
        }
        // }
    } catch (final InterruptedException |

            ExecutionException e) {
        return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e));
    } finally {
        cl.outWriter.flush();
        cl.errWriter.flush();
        executor.shutdownNow();
    }
    return new InterpreterResult(Code.SUCCESS, cl.out.toString());
}

From source file:com.hellblazer.jackal.configuration.ThreadConfig.java

@Bean(name = "gossipDispatchers")
@Lazy//from  w  w  w.  j  a  v a 2  s  . c om
@Autowired
public ExecutorService gossipDispatchers(Identity partitionIdentity) {
    final int id = partitionIdentity.id;
    return Executors.newCachedThreadPool(new ThreadFactory() {
        int count = 0;

        @Override
        public Thread newThread(Runnable target) {
            Thread t = new Thread(target, String.format("Gossip Dispatcher[%s] for node[%s]", count++, id));
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    log.error(String.format("Exception on %s", t), e);
                }
            });
            return t;
        }
    });
}

From source file:org.killbill.notificationq.NotificationQueueDispatcher.java

NotificationQueueDispatcher(final Clock clock, final NotificationQueueConfig config, final IDBI dbi,
        final MetricRegistry metricRegistry) {
    super("NotificationQ", Executors.newFixedThreadPool(config.getNbThreads() + 1, new ThreadFactory() {
        @Override/*ww  w.j  a v a2  s . co  m*/
        public Thread newThread(final Runnable r) {
            final Thread th = new Thread(r);
            th.setName(config.getTableName() + "-th");
            th.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(final Thread t, final Throwable e) {
                    log.error("Uncaught exception for thread " + t.getName(), e);
                }
            });
            return th;
        }
    }), 1, config);

    this.clock = clock;
    this.config = config;
    this.nbProcessedEvents = new AtomicLong();
    final NotificationSqlDao sqlDao = dbi.onDemand(NotificationSqlDao.class);
    this.dao = new DBBackedQueue<NotificationEventModelDao>(clock, sqlDao, config,
            "notif-" + config.getTableName(), metricRegistry, null);

    this.queues = new TreeMap<String, NotificationQueue>();

    this.processedNotificationsSinceStart = metricRegistry.counter(
            MetricRegistry.name(NotificationQueueDispatcher.class, "processed-notifications-since-start"));
    this.perQueueProcessingTime = new HashMap<String, Histogram>();
    this.pendingNotificationsQ = new LinkedBlockingQueue<NotificationEventModelDao>(config.getQueueCapacity());

    this.metricRegistry = metricRegistry;
    this.pendingNotifications = metricRegistry.register(
            MetricRegistry.name(NotificationQueueDispatcher.class, "pending-notifications"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return pendingNotificationsQ.size();
                }
            });

    this.runners = new NotificationRunner[config.getNbThreads()];
    for (int i = 0; i < config.getNbThreads(); i++) {
        runners[i] = new NotificationRunner(pendingNotificationsQ, clock, config, objectMapper,
                nbProcessedEvents, queues, dao, perQueueProcessingTime, metricRegistry,
                processedNotificationsSinceStart);
    }
}