List of usage examples for java.util.concurrent ThreadFactory ThreadFactory
ThreadFactory
From source file:org.jwebsocket.util.Tools.java
/** * *//*from w w w . j a v a 2s . c o m*/ public static void startUtilityThreadPool() { if (System.getProperties().contains("JWEBSOCKET_HOME")) { AccessController.checkPermission(stringToPermission( "permission java.util.PropertyPermission \"" + "org.jwebsocket.tools.threadpool\", \"write\"")); } if (null == mThreadPool) { mThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "jWebSocket Utility ThreadPool"); } }); } }
From source file:org.jumpmind.symmetric.service.impl.RouterService.java
protected IDataToRouteReader startReading(ChannelRouterContext context) { IDataToRouteReader reader = new DataGapRouteReader(context, engine); if (parameterService.is(ParameterConstants.SYNCHRONIZE_ALL_JOBS)) { reader.run();//from www . j a va2 s .c o m } else { if (readThread == null) { readThread = Executors.newCachedThreadPool(new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix = parameterService.getEngineName().toLowerCase() + "-router-reader-"; public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName(namePrefix + threadNumber.getAndIncrement()); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }); } readThread.execute(reader); } return reader; }
From source file:de.hybris.platform.test.TransactionTest.java
@Test public void testLocking() throws Exception { if (Config.isHSQLDBUsed()) { LOG.warn("HDSQLDB doesnt seem to support SELECT FOR UPDATE properly so we don't test it any more"); return;/*from w w w. j av a 2 s. c o m*/ } final ProductManager productManager = ProductManager.getInstance(); final Currency curr = C2LManager.getInstance().createCurrency("TestCurr"); /** Verify that we can begin a transaction, lock an entity, then commit without an exception occurring. */ { final Transaction transaction = Transaction.current(); try { assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); transaction.begin(); final Product productForTest1 = productManager.createProduct("transactionLockingTest1"); transaction.commit(); transaction.begin(); transaction.lock(productForTest1); transaction.commit(); } catch (final Exception e) { transaction.rollback(); throw e; } } { /** Verify that an IllegalStateException is thrown if we attempt to lock outside of a transaction. */ final Transaction transaction = Transaction.current(); try { assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); final Product productForTest2 = productManager.createProduct("transactionLockingTest2"); transaction.lock(productForTest2); fail("Expected IllegalStateException to occur when attempting to lock an item outside of a transaction."); } // An IllegalStateException is expected for this test to pass. catch (final IllegalStateException e) { // } } /** * Verify that if we attempt to acquire a lock on the same entity multiple times from the same transaction, that * no errors occur. */ { final Transaction transaction = Transaction.current(); try { assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); final Product productForTest3 = productManager.createProduct("transactionLockingTest3"); transaction.begin(); for (int i = 0; i < 10; i++) { transaction.lock(productForTest3); } transaction.commit(); } catch (final Exception e) { transaction.rollback(); throw e; } } /** * Verify that if we begin a transaction, lock an entity, then commit multiple times that a lock can be acquired * each time. */ { final Transaction transaction = Transaction.current(); try { final Product productForTest4 = productManager.createProduct("transactionLockingTest4"); for (int i = 0; i < 10; i++) { assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); transaction.begin(); transaction.lock(productForTest4); transaction.commit(); } } catch (final Exception e) { transaction.rollback(); throw e; } } /** * Verify that if we begin a transaction, lock an entity, then rollback multiple times that a lock can be acquired * each time. */ { final Transaction transaction = Transaction.current(); try { final Product productForTest5 = productManager.createProduct("transactionLockingTest5"); for (int i = 0; i < 10; i++) { assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); transaction.begin(); transaction.lock(productForTest5); transaction.rollback(); } } catch (final Exception e) { transaction.rollback(); throw e; } } /** * Verify that we can not lock after a transaction has been committed. */ { final Transaction transaction = Transaction.current(); try { final Product productForTest6 = productManager.createProduct("transactionLockingTest6"); assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); transaction.begin(); transaction.commit(); transaction.lock(productForTest6); fail("A lock was acquired after the transaction has been committed."); } // An IllegalStateException is expected for the test to pass catch (final IllegalStateException e) { // } } /** * Verify that we can not lock after a transaction has been rolled back. */ { final Transaction transaction = Transaction.current(); try { final Product productForTest7 = productManager.createProduct("transactionLockingTest7"); assertNotNull("Transaction object is null", transaction); assertFalse("A previous transaction is already running.", transaction.isRunning()); transaction.begin(); transaction.rollback(); transaction.lock(productForTest7); fail("A lock was acquired after the transaction has been rolled back."); } // An IllegalStateException is expected for the test to pass catch (final IllegalStateException e) { // } } /** * Verify multiple threads attempting to lock the same object and the behavior that occurs. */ try { final Order lockedOrder = OrderManager.getInstance().createOrder(// "lockedOrder", // JaloSession.getCurrentSession().getUser(), // curr, // Calendar.getInstance().getTime(), // true); lockedOrder.setTotal(0.0d); final ComposedType composedType = lockedOrder.getComposedType(); final String checkQuery = "SELECT " + composedType.getAttributeDescriptorIncludingPrivate(Order.TOTAL).getDatabaseColumn() + " FROM " + composedType.getTable() + " WHERE PK = ?"; final int THREADS = 16; // Create an executor service that uses 16 threads to test // the transaction locking final ExecutorService executor = Executors.newFixedThreadPool(// THREADS, // new ThreadFactory() { final Tenant threadFactoryTenant = Registry.getCurrentTenant(); @Override public Thread newThread(final Runnable runnable) { return new Thread() { protected void prepareThread() { Registry.setCurrentTenant(threadFactoryTenant); } protected void unprepareThread() { JaloSession.deactivate(); Registry.unsetCurrentTenant(); } @Override public void run() { try { prepareThread(); runnable.run(); } finally { unprepareThread(); } } }; } }); // Create 8 callables that will concurrently // attempt to lock the same object. final AtomicInteger stackCounter = new AtomicInteger(); final List<Callable<Object>> callables = new ArrayList<Callable<Object>>(); for (int j = 0; j < THREADS; j++) { callables.add(new Callable<Object>() { @Override public Object call() throws Exception { final PK pk = lockedOrder.getPK(); if (pk == null) { throw new IllegalStateException(); } for (int k = 0; k < 100; k++) { final Transaction transaction = Transaction.current(); assertNotNull("Transaction object is null", transaction); PreparedStatement statement = null; ResultSet resultSet = null; try { transaction.begin(); transaction.setTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); transaction.lock(lockedOrder); final int stack = stackCounter.incrementAndGet(); if (stack > 1) { stackCounter.decrementAndGet(); throw new IllegalStateException("Got " + stack + " threads in protected area!"); } statement = transaction.getTXBoundConnection().prepareStatement(checkQuery); statement.setLong(1, lockedOrder.getPK().getLongValue()); resultSet = statement.executeQuery(); if (!resultSet.next()) { throw new IllegalStateException("Expected result set"); } final double dbValue = resultSet.getDouble(1); final double jaloValue = lockedOrder.getTotal(); if (Math.abs(dbValue - jaloValue) >= 1d) { throw new IllegalStateException( "Jalo value differs from db value : " + jaloValue + "<>" + dbValue); } lockedOrder.setTotal(jaloValue + 1.0d); stackCounter.decrementAndGet(); transaction.commit(); } catch (final Exception e) { e.printStackTrace(); transaction.rollback(); throw e; } finally { Utilities.tryToCloseJDBC(null, statement, resultSet, true); } } return null; } }); } // Get the value of each future to determine if an exception was thrown. for (final Future<Object> future : executor.invokeAll(callables)) { future.get(); } final double expected = THREADS * 100; assertEquals(// "Total value of order after all transaction differs", // expected, // ((Order) JaloSession.getCurrentSession().getItem(lockedOrder.getPK())).getTotal(), 0.000001); } catch (final IllegalStateException e) { e.printStackTrace(); throw e; } /** * Verify changes to a value on a lock */ // TODO: /** * Tests related to caching */ // TODO: }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
/** * returns workersExecutorService./*from w w w .j a v a 2s.co m*/ * * returns the service stored in the appContext or creates it if * necessary. If the last one it triggers autoShutdown thread to * get started. * * @return ExecutorService for the {@code SwingWorkers} * @see #startAutoShutdownThread */ private static synchronized ExecutorService getWorkersExecutorService() { if (executorService == null) { //this creates non-daemon threads. ThreadFactory threadFactory = new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger(1); public Thread newThread(final Runnable r) { StringBuilder name = new StringBuilder("SwingWorker-pool-"); name.append(System.identityHashCode(this)); name.append("-thread-"); name.append(threadNumber.getAndIncrement()); Thread t = new Thread(r, name.toString());; if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }; /* * We want a to have no more than MAX_WORKER_THREADS * running threads. * * We want a worker thread to wait no longer than 1 second * for new tasks before terminating. */ executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory) { private final ReentrantLock pauseLock = new ReentrantLock(); private final Condition unpaused = pauseLock.newCondition(); private boolean isPaused = false; private final ReentrantLock executeLock = new ReentrantLock(); @Override public void execute(Runnable command) { /* * ThreadPoolExecutor first tries to run task * in a corePool. If all threads are busy it * tries to add task to the waiting queue. If it * fails it run task in maximumPool. * * We want corePool to be 0 and * maximumPool to be MAX_WORKER_THREADS * We need to change the order of the execution. * First try corePool then try maximumPool * pool and only then store to the waiting * queue. We can not do that because we would * need access to the private methods. * * Instead we enlarge corePool to * MAX_WORKER_THREADS before the execution and * shrink it back to 0 after. * It does pretty much what we need. * * While we changing the corePoolSize we need * to stop running worker threads from accepting new * tasks. */ //we need atomicity for the execute method. executeLock.lock(); try { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } setCorePoolSize(MAX_WORKER_THREADS); super.execute(command); setCorePoolSize(0); pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } finally { executeLock.unlock(); } } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); pauseLock.lock(); try { while(isPaused) { unpaused.await(); } } catch(InterruptedException ignore) { } finally { pauseLock.unlock(); } } }; } return executorService; }
From source file:org.hyperic.hq.measurement.agent.server.ScheduleThread.java
private ThreadFactory getFactory(final String plugin) { final SecurityManager s = System.getSecurityManager(); final ThreadGroup group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); return new ThreadFactory() { private final AtomicLong num = new AtomicLong(); public Thread newThread(Runnable r) { final Thread rtn = new Thread(group, r); rtn.setDaemon(true);//from ww w .ja v a 2s. c om rtn.setName(plugin + "-" + num.getAndIncrement()); return rtn; } }; }
From source file:org.apache.cxf.cwiki.SiteExporter.java
public static void main(String[] args) throws Exception { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); }/*from ww w .java2s . c om*/ }); ListIterator<String> it = Arrays.asList(args).listIterator(); List<String> files = new ArrayList<String>(); boolean forceAll = false; int maxThreads = -1; while (it.hasNext()) { String s = it.next(); if ("-debug".equals(s)) { debug = true; } else if ("-user".equals(s)) { userName = it.next(); } else if ("-password".equals(s)) { password = it.next(); } else if ("-d".equals(s)) { rootOutputDir = new File(it.next()); } else if ("-force".equals(s)) { forceAll = true; } else if ("-svn".equals(s)) { svn = true; } else if ("-commit".equals(s)) { commit = true; } else if ("-maxThreads".equals(s)) { maxThreads = Integer.parseInt(it.next()); } else if (s != null && s.length() > 0) { files.add(s); } } List<SiteExporter> exporters = new ArrayList<SiteExporter>(); for (String file : files) { exporters.add(new SiteExporter(file, forceAll)); } List<SiteExporter> modified = new ArrayList<SiteExporter>(); for (SiteExporter exporter : exporters) { if (exporter.initialize()) { modified.add(exporter); } } // render stuff only if needed if (!modified.isEmpty()) { setSiteExporters(exporters); if (maxThreads <= 0) { maxThreads = modified.size(); } ExecutorService executor = Executors.newFixedThreadPool(maxThreads, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }); List<Future<?>> futures = new ArrayList<Future<?>>(modified.size()); for (SiteExporter exporter : modified) { futures.add(executor.submit(exporter)); } for (Future<?> t : futures) { t.get(); } } if (commit) { File file = FileUtils.createTempFile("svncommit", "txt"); FileWriter writer = new FileWriter(file); writer.write(svnCommitMessage.toString()); writer.close(); callSvn(rootOutputDir, "commit", "-F", file.getAbsolutePath(), rootOutputDir.getAbsolutePath()); svnCommitMessage.setLength(0); } }
From source file:org.apache.hadoop.hive.metastore.cache.CachedStore.java
@VisibleForTesting /**//from w w w . j a v a2 s . co m * This starts a background thread, which initially populates the SharedCache and later * periodically gets updates from the metastore db * * @param conf * @param runOnlyOnce * @param shouldRunPrewarm */ static synchronized void startCacheUpdateService(Configuration conf, boolean runOnlyOnce, boolean shouldRunPrewarm) { if (cacheUpdateMaster == null) { initBlackListWhiteList(conf); if (!MetastoreConf.getBoolVar(conf, ConfVars.HIVE_IN_TEST)) { cacheRefreshPeriodMS = MetastoreConf.getTimeVar(conf, ConfVars.CACHED_RAW_STORE_CACHE_UPDATE_FREQUENCY, TimeUnit.MILLISECONDS); } LOG.info("CachedStore: starting cache update service (run every {} ms", cacheRefreshPeriodMS); cacheUpdateMaster = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setName("CachedStore-CacheUpdateService: Thread-" + t.getId()); t.setDaemon(true); return t; } }); if (!runOnlyOnce) { cacheUpdateMaster.scheduleAtFixedRate(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0, cacheRefreshPeriodMS, TimeUnit.MILLISECONDS); } } if (runOnlyOnce) { // Some tests control the execution of the background update thread cacheUpdateMaster.schedule(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0, TimeUnit.MILLISECONDS); } }
From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java
/** * Creates a new instance of GemFireCache and populates it according to the * <code>cache.xml</code>, if appropriate. * //from www . ja v a2 s . c o m * @param typeRegistry: currently only unit tests set this parameter to a non-null value */ private GemFireCacheImpl(boolean isClient, PoolFactory pf, DistributedSystem system, CacheConfig cacheConfig, boolean asyncEventListeners, TypeRegistry typeRegistry) { this.isClient = isClient; this.clientpf = pf; this.cacheConfig = cacheConfig; // do early for bug 43213 this.pdxRegistry = typeRegistry; // Synchronized to prevent a new cache from being created // before an old one has finished closing synchronized (GemFireCacheImpl.class) { // start JTA transaction manager within this synchronized block // to prevent race with cache close. fixes bug 43987 JNDIInvoker.mapTransactions(system); this.system = (InternalDistributedSystem) system; this.dm = this.system.getDistributionManager(); if (!this.isClient && PoolManager.getAll().isEmpty()) { // We only support management on members of a distributed system // Should do this: if (!getSystem().isLoner()) { // but it causes quickstart.CqClientTest to hang this.listener = new ManagementListener(); this.system.addResourceListener(listener); if (this.system.isLoner()) { this.system.getInternalLogWriter() .info(LocalizedStrings.GemFireCacheImpl_RUNNING_IN_LOCAL_MODE); } } else { getLogger().info("Running in client mode"); this.listener = null; } // Don't let admin-only VMs create Cache's just yet. DM dm = this.system.getDistributionManager(); if (dm instanceof DistributionManager) { if (((DistributionManager) dm).getDMType() == DistributionManager.ADMIN_ONLY_DM_TYPE) { throw new IllegalStateException( LocalizedStrings.GemFireCache_CANNOT_CREATE_A_CACHE_IN_AN_ADMINONLY_VM .toLocalizedString()); } } this.rootRegions = new HashMap(); this.cqService = CqServiceProvider.create(this); this.rmqFactory = new ReliableMessageQueueFactoryImpl(); // Create the CacheStatistics this.cachePerfStats = new CachePerfStats(system); CachePerfStats.enableClockStats = this.system.getConfig().getEnableTimeStatistics(); this.txMgr = new TXManagerImpl(this.cachePerfStats, this); dm.addMembershipListener(this.txMgr); this.creationDate = new Date(); this.persistentMemberManager = new PersistentMemberManager(); if (asyncEventListeners) { final ThreadGroup group = LoggingThreadGroup.createThreadGroup("Message Event Threads", logger); ThreadFactory tf = new ThreadFactory() { public Thread newThread(final Runnable command) { final Runnable r = new Runnable() { public void run() { ConnectionTable.threadWantsSharedResources(); command.run(); } }; Thread thread = new Thread(group, r, "Message Event Thread"); thread.setDaemon(true); return thread; } }; ArrayBlockingQueue q = new ArrayBlockingQueue(EVENT_QUEUE_LIMIT); this.eventThreadPool = new PooledExecutorWithDMStats(q, EVENT_THREAD_LIMIT, this.cachePerfStats.getEventPoolHelper(), tf, 1000); } else { this.eventThreadPool = null; } // Initialize the advisor here, but wait to exchange profiles until cache is fully built this.resourceAdvisor = ResourceAdvisor.createResourceAdvisor(this); // Initialize the advisor here, but wait to exchange profiles until cache is fully built this.jmxAdvisor = JmxManagerAdvisor.createJmxManagerAdvisor(new JmxManagerAdvisee(this)); resourceManager = InternalResourceManager.createResourceManager(this); this.serialNumber = DistributionAdvisor.createSerialNumber(); getResourceManager().addResourceListener(ResourceType.HEAP_MEMORY, getHeapEvictor()); /* * Only bother creating an off-heap evictor if we have off-heap memory enabled. */ if (null != getOffHeapStore()) { getResourceManager().addResourceListener(ResourceType.OFFHEAP_MEMORY, getOffHeapEvictor()); } recordedEventSweeper = EventTracker.startTrackerServices(this); tombstoneService = TombstoneService.initialize(this); TypeRegistry.init(); basicSetPdxSerializer(this.cacheConfig.getPdxSerializer()); TypeRegistry.open(); if (!isClient()) { // Initialize the QRM thread freqeuncy to default (1 second )to prevent spill // over from previous Cache , as the interval is stored in a static // volatile field. HARegionQueue.setMessageSyncInterval(HARegionQueue.DEFAULT_MESSAGE_SYNC_INTERVAL); } FunctionService.registerFunction(new PRContainsValueFunction()); this.expirationScheduler = new ExpirationScheduler(this.system); // uncomment following line when debugging CacheExistsException if (DEBUG_CREATION_STACK) { this.creationStack = new Exception( LocalizedStrings.GemFireCache_CREATED_GEMFIRECACHE_0.toLocalizedString(toString())); } this.txEntryStateFactory = TXEntryState.getFactory(); if (xmlParameterizationEnabled) { /** If product properties file is available replace properties from there */ Properties userProps = this.system.getConfig().getUserDefinedProps(); if (userProps != null && !userProps.isEmpty()) { resolver = new CacheXmlPropertyResolver(false, PropertyResolver.NO_SYSTEM_PROPERTIES_OVERRIDE, userProps); } else { resolver = new CacheXmlPropertyResolver(false, PropertyResolver.NO_SYSTEM_PROPERTIES_OVERRIDE, null); } } SystemFailure.signalCacheCreate(); diskMonitor = new DiskStoreMonitor(); } // synchronized }
From source file:org.openstreetmap.josm.tools.Utils.java
/** * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}. * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)} * @return a new {@link ThreadFactory}/* w w w . ja v a 2 s . co m*/ */ public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) { return new ThreadFactory() { final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(final Runnable runnable) { final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); thread.setPriority(threadPriority); return thread; } }; }
From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java
private boolean initCheckpointServer() { this.executor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, new ThreadFactory() { @Override/*from ww w . j ava2 s . com*/ public Thread newThread(Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName(SQLReconfiguratorDB.class.getSimpleName() + myID); return thread; } }); try { InetAddress addr = null; try { this.serverSock = new ServerSocket(); // first try the configured address, else fall back to wildcard this.serverSock .bind(new InetSocketAddress(addr = this.consistentNodeConfig.getBindAddress(myID), 0)); } catch (IOException ioe) { log.info(this + " unable to open large checkpoint server socket on " + addr + "; trying wildcard address instead"); this.serverSock = new ServerSocket(0); } checkpointServerFuture = executor.submit(new CheckpointServer()); return true; } catch (IOException e) { log.severe(this + " unable to open server socket for large checkpoint transfers"); e.printStackTrace(); } return false; }