List of usage examples for java.lang Thread setName
public final synchronized void setName(String name)
From source file:com.frostwire.android.gui.Librarian.java
public void syncMediaStore(final WeakReference<Context> contextRef) { if (!SystemUtils.isPrimaryExternalStorageMounted()) { return;/* ww w . j av a 2 s . c o m*/ } Thread t = new Thread(() -> syncMediaStoreSupport(contextRef)); t.setName("syncMediaStore"); t.setDaemon(true); t.start(); }
From source file:com.btoddb.fastpersitentqueue.JournalMgr.java
/** * * @throws IOException/*from ww w. j ava 2s .com*/ */ 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:escada.tpc.common.clients.jmx.ClientEmulationStartup.java
private void startClientEmulation(boolean exit) { ClientEmulation e = null;// ww w .j a v a 2 s . c om Vector<ClientEmulation> ebs = new Vector<ClientEmulation>(); DatabaseManager dbManager = null; try { logger.info("Starting up the client application."); logger.info("Remote Emulator for Database Benchmark ..."); logger.info("Universidade do Minho (Grupo de Sistemas Distribuidos)"); logger.info("Version 0.1"); Class cl = null; Constructor co = null; cl = Class.forName(this.workloadResources.getDbClass()); try { co = cl.getConstructor(new Class[] { Integer.TYPE }); } catch (Exception ex) { } if (co == null) { dbManager = (DatabaseManager) cl.newInstance(); } else { dbManager = (DatabaseManager) co .newInstance(new Object[] { new Integer(this.workloadResources.getClients()) }); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD_HH_mm"); String date = sdf.format(new Date()); PerformanceLogger.setPrintWriter("TPCC-" + date + "-" + this.workloadResources.getPrefix() + "-time-" + this.workloadResources.getMeasurementTime() + "-clients-" + this.workloadResources.getClients() + "-frag-" + this.workloadResources.getFrag() + "-think-" + this.workloadResources.isThinkTime() + ".dat"); PerformanceCounters.getReference();//Initialize instance dbManager.setConnectionPool(this.workloadResources.isConnectionPoolEnabled()); dbManager.setMaxConnection(this.workloadResources.getPoolSize()); dbManager.setDriverName(this.databaseResources.getDriver()); dbManager.setjdbcPath(this.databaseResources.getConnectionString()); dbManager.setUserInfo(this.databaseResources.getUserName(), this.databaseResources.getPassword()); for (int i = 0; i < this.workloadResources.getClients(); i++) { e = new ClientEmulation(); e.setFinished(false); e.setTraceInformation(this.workloadResources.getTrace()); e.setNumberConcurrentEmulators(this.workloadResources.getClients()); e.setStatusThinkTime(this.workloadResources.isThinkTime()); e.setStatusReSubmit(this.workloadResources.isResubmit()); e.setDatabase(dbManager); e.setEmulationName(this.workloadResources.getPrefix()); e.setHostId(Integer.toString(this.workloadResources.getHostId())); e.create(this.workloadResources.getEbClass(), this.workloadResources.getStClass(), i, this.workloadResources.getFrag(), this, this.workloadResources.getPrefix()); Thread t = new Thread(e); t.setName(this.workloadResources.getPrefix() + "-" + i); e.setThread(t); t.start(); ebs.add(e); } synchronized (this) { server.setClientEmulations(this.workloadResources.getPrefix(), ebs); server.attachClientToServer(this.workloadResources.getPrefix(), this.databaseResources.getConnectionString()); } logger.info("Running simulation for " + this.workloadResources.getMeasurementTime() + " minute(s)."); waitForRampDown(this.workloadResources.getPrefix(), 0, this.workloadResources.getMeasurementTime()); for (int i = 0; i < this.workloadResources.getClients(); i++) { e = (ClientEmulation) ebs.elementAt(i); //logger.info("Waiting for the eb " + i + " to finish its job.."); //try { e.setCompletion(true); //e.getThread().join(); /*} catch (InterruptedException inte) { inte.printStackTrace(); continue; }*/ } for (int i = 0; i < this.workloadResources.getClients(); i++) { e = (ClientEmulation) ebs.elementAt(i); logger.info("Waiting for the eb " + i + " to finish its job.."); try { // e.setCompletion(true); e.getThread().join(); } catch (InterruptedException inte) { inte.printStackTrace(); continue; } } logger.info("EBs finished."); PerformanceLogger.info("-------------------- SUMMARY ---------------------------"); PerformanceLogger.info("Abort rate:" + PerformanceCounters.getReference().getTotalAbortRate()); PerformanceLogger.info("Average latency:" + PerformanceCounters.getReference().getAverageLatency()); PerformanceLogger .info("Measured tpmC:" + PerformanceCounters.getReference().getTotalNewOrderCommitRate()); PerformanceLogger.close(); } catch (Exception ex) { logger.info("Error while creating clients: ", ex); } finally { synchronized (this) { this.server.removeClientEmulations(this.workloadResources.getPrefix()); this.server.removeClientStage(this.workloadResources.getPrefix()); this.server.detachClientToServer(this.workloadResources.getPrefix(), this.databaseResources.getConnectionString()); notifyAll(); } try { dbManager.releaseConnections(); } catch (SQLException e1) { e1.printStackTrace(); } logger.info("Ebs finished their jobs.."); if (exit) System.exit(0); } }
From source file:com.hubcap.task.helpers.DefaultSearchHelper.java
@Override public void run() { if (taskModel == null) { if (this.listener != null) { this.listener.processTaskHelperError( new Exception("No Task Model Provided to DefaultSearchHelper, cannot run!"), false); }/*from w w w . ja v a2 s . co m*/ die(); return; } CommandLine cmd = taskModel.getCommandLine(); int cLen = cmd.getArgs().length; // default search arguments are in the format // orgname (String) count (int) if (cLen < 1) { if (this.listener != null) { this.listener.processTaskHelperError( new Exception("Default Search requires 1 argument, Organization (optional) Count"), false); } die(); } if (cLen % 2 == 0) { // each helper has its own HttpClient ProcessModel.instance().updateRateLimitData(); for (int i = 0; i < cLen; i += 2) { String orgName = cmd.getArgs()[i]; int count = 10; try { count = Integer.parseInt(cmd.getArgs()[i + 1]); } catch (NumberFormatException ex) { ErrorUtils.printStackTrace(ex); } final long remainingRate = ProcessModel.instance().getRateLimitData().rate.remaining; final long maxResults = opts.containsKey("maxResults") ? Integer.parseInt((String) opts.get("maxResults")) : (remainingRate - 1); int maxPages = 100; if (remainingRate >= maxResults) { // pound that API until we get what we want!! // breaks out of the loop after // max pages searchHelperId.incrementAndGet(); if (searchHelperId.get() > maxPages) { break; } try { synchronized (droneThreads) { Thread t = new Thread( new GitHubOrgScavengerDrone(sewingMachine, this.taskModel, orgName, count)); droneThreads.add(t); t.setName("drone" + String.valueOf(owner.getTaskId()) + "-" + String.valueOf(new Date().getTime())); t.setDaemon(false); t.start(); } } catch (RejectedExecutionException ex) { ErrorUtils.printStackTrace(ex); break; } } else { System.err.println("Your rate limit is exhausted, try again later!"); } } } if (ProcessModel.instance().getVerbose()) { System.out.println("Waiting for Drone Threads: " + droneThreads.size()); } // wait for all threads to complete while (droneThreads.size() > 0) { Iterator<Thread> it = droneThreads.iterator(); while (it.hasNext()) { Thread currDroneThread = it.next(); if (currDroneThread.getState() == State.TERMINATED) { if (ProcessModel.instance().getVerbose()) { System.err.println("Removing Drone Thread: " + currDroneThread.getName()); } it.remove(); } } // sleep and do it again if (!ThreadUtils.safeSleep( Constants.NEW_THREAD_SPAWN_BREATHING_TIME + Constants.NEW_THREAD_SPAWN_BREATHING_TIME * 1 / SewingMachine.MAX_THREADS_PER_MACHINE, ProcessModel.instance().getVerbose())) { System.err.println("INTERRUPTED WAIT FOR DRONE THREADS!"); break; } } System.out.println("No More Drones!"); // wait a tad synchronized (taskModel) { Map<String, Object> aggData = taskModel.getAggregateDataMap(); if (aggData != null) { for (String key : aggData.keySet()) { Object value = aggData.get(key); if (value instanceof ScavengerModel == false) { continue; } // ask the model to calculate from its current state ScavengerModel model = (ScavengerModel) value; synchronized (model) { model.calculate(); } } listener.processTaskHelperData(taskModel); } } die(); }
From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java
public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests, Map<String, String> aggregateArgs) { try {//w w w . ja v a2 s. com List<String> mainClassNames = new ArrayList<>(); LinkedHashSet<URL> jarURLs = new LinkedHashSet<>(); List<String> seenArchives = new ArrayList<>(); final List<String[]> arguments = new ArrayList<>(); final ClassLoader classLoader; if (!(aggregateArgs.containsKey(EXCLUDE_DEPENDENCIES_ARG) || aggregateArgs.containsKey(INCLUDE_DEPENDENCIES_ARG))) { for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) { Resource resource = resolveModule(moduleLaunchRequest.getModule()); JarFileArchive jarFileArchive = new JarFileArchive(resource.getFile()); jarURLs.add(jarFileArchive.getUrl()); for (Archive archive : jarFileArchive.getNestedArchives(ArchiveMatchingEntryFilter.FILTER)) { // avoid duplication based on unique JAR names String urlAsString = archive.getUrl().toString(); String jarNameWithExtension = urlAsString.substring(0, urlAsString.lastIndexOf("!/")); String jarNameWithoutExtension = jarNameWithExtension .substring(jarNameWithExtension.lastIndexOf("/") + 1); if (!seenArchives.contains(jarNameWithoutExtension)) { seenArchives.add(jarNameWithoutExtension); jarURLs.add(archive.getUrl()); } } mainClassNames.add(jarFileArchive.getMainClass()); arguments.add(toArgArray(moduleLaunchRequest.getArguments())); } classLoader = ClassloaderUtils.createModuleClassloader(jarURLs.toArray(new URL[jarURLs.size()])); } else { // First, resolve modules and extract main classes - while slightly less efficient than just // doing the same processing after resolution, this ensures that module artifacts are processed // correctly for extracting their main class names. It is not possible in the general case to // identify, after resolution, whether a resource represents a module artifact which was part of the // original request or not. We will include the first module as root and the next as direct dependencies Coordinates root = null; ArrayList<Coordinates> includeCoordinates = new ArrayList<>(); for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) { Coordinates moduleCoordinates = toCoordinates(moduleLaunchRequest.getModule()); if (root == null) { root = moduleCoordinates; } else { includeCoordinates.add(toCoordinates(moduleLaunchRequest.getModule())); } Resource moduleResource = resolveModule(moduleLaunchRequest.getModule()); JarFileArchive moduleArchive = new JarFileArchive(moduleResource.getFile()); mainClassNames.add(moduleArchive.getMainClass()); arguments.add(toArgArray(moduleLaunchRequest.getArguments())); } for (String include : StringUtils .commaDelimitedListToStringArray(aggregateArgs.get(INCLUDE_DEPENDENCIES_ARG))) { includeCoordinates.add(toCoordinates(include)); } // Resolve all artifacts - since modules have been specified as direct dependencies, they will take // precedence in the resolution order, ensuring that the already resolved artifacts will be returned as // part of the response. Resource[] libraries = moduleResolver.resolve(root, includeCoordinates.toArray(new Coordinates[includeCoordinates.size()]), StringUtils.commaDelimitedListToStringArray(aggregateArgs.get(EXCLUDE_DEPENDENCIES_ARG))); for (Resource library : libraries) { jarURLs.add(library.getURL()); } classLoader = new URLClassLoader(jarURLs.toArray(new URL[jarURLs.size()])); } final List<Class<?>> mainClasses = new ArrayList<>(); for (String mainClass : mainClassNames) { mainClasses.add(ClassUtils.forName(mainClass, classLoader)); } Runnable moduleAggregatorRunner = new ModuleAggregatorRunner(classLoader, mainClasses, toArgArray(aggregateArgs), arguments); Thread moduleAggregatorRunnerThread = new Thread(moduleAggregatorRunner); moduleAggregatorRunnerThread.setContextClassLoader(classLoader); moduleAggregatorRunnerThread.setName(MODULE_AGGREGATOR_RUNNER_THREAD_NAME); moduleAggregatorRunnerThread.start(); } catch (Exception e) { throw new RuntimeException("failed to start aggregated modules: " + StringUtils.collectionToCommaDelimitedString(moduleLaunchRequests), e); } }
From source file:org.apache.hadoop.contrib.bkjournal.TestBookKeeperSpeculativeRead.java
/** * Sleep a bookie until I count down the latch * * @param latch// www . ja v a2 s . c o m * latch to wait on * @param bookie * bookie server * @throws Exception */ private void sleepBookie(final CountDownLatch latch, final BookieServer bookie) throws Exception { Thread sleeper = new Thread() { public void run() { try { bookie.suspendProcessing(); latch.await(2, TimeUnit.MINUTES); bookie.resumeProcessing(); } catch (Exception e) { LOG.error("Error suspending bookie", e); } } }; sleeper.setName("BookieServerSleeper-" + bookie.getBookie().getId()); sleeper.start(); }
From source file:bq.jpa.demo.lock.LockTester.java
@Test public void test4() { test();/*from ww w . j a va 2s . c o m*/ System.out.println("---- do statistic during writing ----"); Thread thread1 = new Thread(new Runnable() { @Override public void run() { service.doReadWhileModify(); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { service.doModify(); } }); thread1.setName("readthread"); thread2.setName("writethread"); thread1.start(); try { Thread.sleep(1000); } catch (InterruptedException e1) { } thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:bq.jpa.demo.lock.LockTester.java
public void test2() { System.out.println("---- modify salary while do statistic ----"); Thread thread1 = new Thread(new Runnable() { @Override//from w w w . j a v a 2s . co m public void run() { service.doStatisticSalary(); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { service.doUpdateSalary(); } }); thread1.setName("dostatistic"); thread2.setName("doupdatesalary"); try { thread2.start(); Thread.sleep(1000); thread1.start(); } catch (InterruptedException e1) { } try { thread1.join(); thread2.join(); } catch (InterruptedException e) { } }
From source file:com.adaptris.core.AdaptrisMessageWorkerImp.java
/** * @see com.adaptris.core.AdaptrisMessageWorker #handleConnectionException() *///ww w .jav a 2s . com @Override public void handleConnectionException() throws CoreException { if (hasActiveErrorHandler()) { // spin off exception handler Thread Thread thread = new ManagedThreadFactory(getClass().getSimpleName()).newThread(new Runnable() { @Override public void run() { retrieveConnection(AdaptrisConnection.class).connectionErrorHandler() .handleConnectionException(); } }); thread.setName("Connection Exc: " + Thread.currentThread().getName()); log.trace("Handling Connection Exception"); thread.start(); } }
From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java
static void infiniteRetry() { Thread thread = new Thread(new Runnable() { private boolean done = false; @Override/* ww w. j a v a 2 s . c o m*/ public void run() { while (!done) { LOGGER.trace("attempting to reconnect to HornetQ"); try { connectInternal(); LOGGER.trace("reconnect to HornetQ is successful"); INIT_READY.countDown(); done = true; } catch (Exception e) { LOGGER.trace("failed to reconnect. retrying...", e); try { Thread.sleep(ConfigurationFactory.getConfiguration() .getInt("service.hornetq.attachRetryDelay", 10000)); } catch (InterruptedException e1) { LOGGER.trace("thread interrupted!!!", e1); } } } } }); thread.setName("hornetq-reconnect"); thread.setDaemon(true); thread.start(); }