List of usage examples for java.lang Thread getName
public final String getName()
From source file:com.android.exchange.ExchangeService.java
static public void reloadFolderList(Context context, long accountId, boolean force) { ExchangeService exchangeService = INSTANCE; if (exchangeService == null) return;/*from w w w. j a v a 2 s . c o m*/ Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + "=?", new String[] { Long.toString(accountId), Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) }, null); try { if (c.moveToFirst()) { synchronized (sSyncLock) { Mailbox mailbox = new Mailbox(); mailbox.restore(c); Account acct = Account.restoreAccountWithId(context, accountId); if (acct == null) { reloadFolderListFailed(accountId); return; } String syncKey = acct.mSyncKey; // No need to reload the list if we don't have one if (!force && (syncKey == null || syncKey.equals("0"))) { reloadFolderListFailed(accountId); return; } // Change all ping/push boxes to push/hold ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD); context.getContentResolver().update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX, new String[] { Long.toString(accountId) }); log("Set push/ping boxes to push/hold"); long id = mailbox.mId; AbstractSyncService svc = exchangeService.mServiceMap.get(id); // Tell the service we're done if (svc != null) { synchronized (svc.getSynchronizer()) { svc.stop(); // Interrupt the thread so that it can stop Thread thread = svc.mThread; if (thread != null) { thread.setName(thread.getName() + " (Stopped)"); thread.interrupt(); } } // Abandon the service exchangeService.releaseMailbox(id); // And have it start naturally kick("reload folder list"); } } } } finally { c.close(); } }
From source file:edu.wisc.commons.httpclient.CleanShutdownPoolingClientConnectionManager.java
@Override public void shutdown() { if (shutdownComplete.get() || !this.shutdownLock.tryLock()) { //Already shutdown or shutdown in progress return;/*from ww w. j a v a 2 s.com*/ } try { //Create Thread to call shutdown final Thread shutdownThread = new Thread(new Runnable() { @Override public void run() { try { logger.info("PoolingClientConnectionManager shutdown started"); CleanShutdownPoolingClientConnectionManager.super.shutdown(); } finally { shutdownComplete.set(true); logger.info("PoolingClientConnectionManager shutdown complete"); } } }); shutdownThread.setName("PoolingClientConnectionManager Shutdown Monitor"); shutdownThread.setDaemon(true); //start shutdown thread shutdownThread.start(); //track initial shutdown start time and time spent by the shutdown thread waiting or blocked final long shutdownStart = System.nanoTime(); long waitStart = shutdownStart; //Monitor the shutdown thread while (!shutdownComplete.get()) { final long now = System.nanoTime(); final long shutdownTime = TimeUnit.NANOSECONDS.toMillis(now - shutdownStart); //if time spent shutting down is greater than kill time forcibly stop the shutdown thread if (shutdownTime > this.shutdownThreadKillTime) { final String stackTrace = getStackTrace(shutdownThread); logger.error("Shutdown thread " + shutdownThread.getName() + " has been stopping for " + shutdownTime + "ms, killing it. THIS IS BAD. \n" + stackTrace); shutdownThread.stop(); //break out of the monitoring loop break; } //if time spent shutting down is greater than max time immediately interrupt the thread else if (shutdownTime > this.shutdownThreadMaxTime) { logger.warn("Shutdown thread " + shutdownThread.getName() + " has been stopping for " + shutdownTime + "ms, interrupting immediately"); shutdownThread.interrupt(); } //otherwise check the state of the thread else { //If the thread is blocked or waiting and has been for longer than the max wait time //interrupt the thread. If not in blocked or waiting state update the wait-start time final State state = shutdownThread.getState(); switch (state) { case BLOCKED: case TIMED_WAITING: case WAITING: { final long waitTime = TimeUnit.NANOSECONDS.toMillis(now - waitStart); if (waitTime > shutdownThreadMaxWaitTime) { logger.info("Shutdown thread " + shutdownThread.getName() + " has been waiting for " + waitTime + "ms, interrupting"); shutdownThread.interrupt(); } else { break; } } default: { waitStart = now; break; } } } //Sleep between state checks, don't want to overload anything try { Thread.sleep(shutdownThreadPollRate); } catch (InterruptedException e) { //ignore } } } finally { this.shutdownLock.unlock(); } }
From source file:org.soaplab.gowlab.GowlabJob.java
/************************************************************************** * Create (but not start it yet) and return a thread that will do * the data fetching. It is rarely overwritten - but still it is * possible to create here your own thread. Make sure that your * thread also notifies other threads at its end (as it is done * here)./* w ww. j av a 2 s .co m*/ * * The subclasses usually just overwrite method 'fetch' (which is * called from this thread) in order to do their fetching job. **************************************************************************/ protected Thread getExecuteThread() throws SoaplabException { Thread executeThread = new Thread() { public void run() { try { try { fetch(); reporter.getState().set(JobState.COMPLETED); } catch (SoaplabException e) { error(e.getMessage()); reporter.getState().set(JobState.TERMINATED_BY_ERROR); } } catch (RuntimeException e) { reporter.getState().set(JobState.TERMINATED_BY_ERROR); SoaplabException.formatAndLog(e, log); } finally { try { reporter.setDetailedStatusResult(); reporter.setReportResult(); } catch (SoaplabException e) { log.error("Setting special results failed. " + e.getMessage()); } // release connection if (httpMethod != null) httpMethod.releaseConnection(); // inform other threads waiting for the termination that // it has been done synchronized (reporter) { reporter.notifyAll(); } } } }; executeThread.setName(executeThread.getName().replace("Thread", "GowlabFetcher")); return executeThread; }
From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.views.loader.TableComposite.java
public void processMetadata(final Label theStatus, final Label theStatus2, final Display theDisplay, final Thread thisThread) throws Exception { // pass data and metadata table name. OntologyResponseMessage msg = new OntologyResponseMessage(); StatusType procStatus = null;/* www . j a va 2s. c o m*/ CSVFileReader reader = null; try { String file = RunData.getInstance().getMetadataFile(); reader = new CSVFileReader(RunData.getInstance().getMetadataFile(), '|', '"'); // Read in header.. reader.readFields(); int count = 0; int start = 1; int end = 1000; MetadataLoadType metadata = new MetadataLoadType(); metadata.setTableName(RunData.getInstance().getMetadataTable()); Vector<String> fields = null; while (count < end) { try { if (thisThread.getName().equals("stop")) { reader.close(); I2B2Exception e2 = new I2B2Exception( "User cancelled load of table " + metadata.getTableName()); throw e2; } fields = reader.readFields(); if ((fields == null) || (fields.isEmpty())) { if (metadata.getMetadata().isEmpty()) break; System.out.println("Loading " + metadata.getTableName() + " metadata records " + start + " to " + count); final String theMsg = "Loading " + metadata.getTableName() + " metadata records " + start + " to " + count; theDisplay.syncExec(new Runnable() { public void run() { theStatus2.setText(theMsg); IActionBars bars = ((WorkbenchWindow) PlatformUI.getWorkbench() .getActiveWorkbenchWindow()).getActionBars(); bars.getStatusLineManager().setMessage(theMsg); } }); String response = OntServiceDriver.loadMetadata(metadata, "ONT"); procStatus = msg.processResult(response); if (procStatus.getType().equals("ERROR")) { System.setProperty("errorMessage", procStatus.getValue()); reader.close(); System.out.println("Error loading metadata records: exiting"); I2B2Exception e = new I2B2Exception(procStatus.getValue()); throw e; } // This one loads data reached when end of file found. // String response = MapperServiceDriver.getUnmappedTerms(unmap); //persistDao.batchUpdateMetadata(dbInfo, list); // This is call to ONT to load the table access data. break; } } catch (Exception e) { // TODO Auto-generated catch block reader.close(); System.out.println("Error loading metadata records: exiting"); I2B2Exception e2 = new I2B2Exception("Error loading metadata records for table " + metadata.getTableName() + "; exiting: " + e.getMessage()); throw e2; } if (fields.size() < 25) { System.out.println("problem; too few fields."); I2B2Exception e2 = new I2B2Exception( "Error processing metadata records: too few fields in file; exiting "); throw e2; } MetadataLoaderType term = new MetadataLoaderType(); metadata.getMetadata().add(term.fromMetadata(fields)); count++; if (end == count) { System.out.println("Loading metadata records " + start + " to " + count); final String theMsg = "Loading " + metadata.getTableName() + " metadata records " + start + " to " + count; theDisplay.syncExec(new Runnable() { public void run() { theStatus2.setText(theMsg); IActionBars bars = ((WorkbenchWindow) PlatformUI.getWorkbench() .getActiveWorkbenchWindow()).getActionBars(); bars.getStatusLineManager().setMessage(theMsg); } }); try { String response = OntServiceDriver.loadMetadata(metadata, "ONT"); procStatus = msg.processResult(response); if (procStatus.getType().equals("ERROR")) { System.setProperty("errorMessage", procStatus.getValue()); reader.close(); System.out.println("Error loading metadata records: exiting"); I2B2Exception e = new I2B2Exception(procStatus.getValue()); throw e; } //persistDao.batchUpdateMetadata(dbInfo, list); // This is call to ONT to load the table access data. // This one loads the incremental chunks of data. } catch (Exception e) { // TODO Auto-generated catch block reader.close(); System.out.println("Error loading metadata records: exiting"); I2B2Exception e2 = new I2B2Exception("Error loading metadata records for table " + metadata.getTableName() + "; exiting: " + e.getMessage()); throw e2; } metadata.getMetadata().clear(); end += 1000; start += 1000; if (thisThread.getName().equals("stop")) { reader.close(); I2B2Exception e2 = new I2B2Exception( "User cancelled load of table " + metadata.getTableName()); throw e2; } } } reader.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("Metadata loader complete"); }
From source file:com.inmobi.grill.driver.hive.TestRemoteHiveDriver.java
@Test public void testMultiThreadClient() throws Exception { LOG.info("@@ Starting multi thread test"); // Launch two threads createTestTable("test_multithreads"); HiveConf thConf = new HiveConf(conf, TestRemoteHiveDriver.class); thConf.setLong(HiveDriver.GRILL_CONNECTION_EXPIRY_DELAY, 10000); final HiveDriver thrDriver = new HiveDriver(); thrDriver.configure(thConf);/* w w w . ja v a 2s . c o m*/ QueryContext ctx = new QueryContext("USE " + TestRemoteHiveDriver.class.getSimpleName(), null, conf); thrDriver.execute(ctx); // Launch a select query final int QUERIES = 5; int launchedQueries = 0; final int THREADS = 5; final long POLL_DELAY = 500; List<Thread> thrs = new ArrayList<Thread>(); final AtomicInteger errCount = new AtomicInteger(); for (int q = 0; q < QUERIES; q++) { final QueryContext qctx; try { qctx = new QueryContext("SELECT * FROM test_multithreads", null, conf); thrDriver.executeAsync(qctx); } catch (GrillException e) { errCount.incrementAndGet(); LOG.info(q + " executeAsync error: " + e.getCause()); continue; } LOG.info("@@ Launched query: " + q + " " + qctx.getQueryHandle()); launchedQueries++; // Launch many threads to poll for status final QueryHandle handle = qctx.getQueryHandle(); for (int i = 0; i < THREADS; i++) { int thid = q * THREADS + i; Thread th = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 1000; i++) { try { thrDriver.updateStatus(qctx); if (qctx.getDriverStatus().isFinished()) { LOG.info("@@ " + handle.getHandleId() + " >> " + qctx.getDriverStatus().getState()); thrDriver.closeQuery(handle); break; } Thread.sleep(POLL_DELAY); } catch (GrillException e) { LOG.error("Got Exception", e.getCause()); e.printStackTrace(); errCount.incrementAndGet(); break; } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); thrs.add(th); th.setName("Poller#" + (thid)); th.start(); } } for (Thread th : thrs) { try { th.join(10000); } catch (InterruptedException e) { LOG.warn("Not ended yet: " + th.getName()); } } Assert.assertEquals(0, thrDriver.getHiveHandleSize()); LOG.info("@@ Completed all pollers. Total thrift errors: " + errCount.get()); assertEquals(launchedQueries, QUERIES); assertEquals(thrs.size(), QUERIES * THREADS); assertEquals(errCount.get(), 0); }
From source file:org.apache.lens.driver.hive.TestRemoteHiveDriver.java
/** * Test multi thread client.//from ww w.ja va 2s.c o m * * @throws Exception the exception */ @Test public void testMultiThreadClient() throws Exception { log.info("@@ Starting multi thread test"); SessionState.get().setCurrentDatabase(dataBase); final SessionState state = SessionState.get(); // Launch two threads createTestTable("test_multithreads"); Configuration thConf = new Configuration(driverConf); thConf.setLong(HiveDriver.HS2_CONNECTION_EXPIRY_DELAY, 10000); final HiveDriver thrDriver = new HiveDriver(); thrDriver.configure(thConf, "hive", "hive1"); QueryContext ctx = createContext("USE " + dataBase, queryConf, thrDriver); thrDriver.execute(ctx); // Launch a select query final int QUERIES = 5; int launchedQueries = 0; final int THREADS = 5; final long POLL_DELAY = 500; List<Thread> thrs = new ArrayList<Thread>(); List<QueryContext> queries = new ArrayList<>(); final AtomicInteger errCount = new AtomicInteger(); for (int q = 0; q < QUERIES; q++) { final QueryContext qctx; try { qctx = createContext("SELECT * FROM test_multithreads", queryConf, thrDriver); thrDriver.executeAsync(qctx); queries.add(qctx); } catch (LensException e) { errCount.incrementAndGet(); log.info(q + " executeAsync error: " + e.getCause()); continue; } log.info("@@ Launched query: " + q + " " + qctx.getQueryHandle()); launchedQueries++; // Launch many threads to poll for status final QueryHandle handle = qctx.getQueryHandle(); for (int i = 0; i < THREADS; i++) { int thid = q * THREADS + i; Thread th = new Thread(new Runnable() { @Override public void run() { SessionState.setCurrentSessionState(state); for (int i = 0; i < 1000; i++) { try { thrDriver.updateStatus(qctx); if (qctx.getDriverStatus().isFinished()) { log.info("@@ " + handle.getHandleId() + " >> " + qctx.getDriverStatus().getState()); break; } Thread.sleep(POLL_DELAY); } catch (LensException e) { log.error("Got Exception " + e.getCause(), e); errCount.incrementAndGet(); break; } catch (InterruptedException e) { log.error("Encountred Interrupted exception", e); break; } } } }); thrs.add(th); th.setName("Poller#" + (thid)); th.start(); } } for (Thread th : thrs) { try { th.join(10000); } catch (InterruptedException e) { log.warn("Not ended yet: " + th.getName()); } } for (QueryContext queryContext : queries) { thrDriver.closeQuery(queryContext.getQueryHandle()); } Assert.assertEquals(0, thrDriver.getHiveHandleSize()); log.info("@@ Completed all pollers. Total thrift errors: " + errCount.get()); assertEquals(launchedQueries, QUERIES); assertEquals(thrs.size(), QUERIES * THREADS); assertEquals(errCount.get(), 0); }
From source file:com.intuit.tank.harness.APITestHarness.java
/** * check the agent threads if simulation time has been met. *//*from w w w . j a va 2 s . c om*/ public void checkAgentThreads() { int activeCount = threadGroup.activeCount(); Thread[] threads = new Thread[activeCount]; threadGroup.enumerate(threads); int activeThreads = 0; for (Thread t : threads) { if (t != null) { if (t.getState() == Thread.State.TIMED_WAITING || t.getState() == Thread.State.WAITING) { activeThreads++; } } } LOG.info(LogUtil.getLogMessage("Have " + activeThreads + " of " + activeCount + " active Threads in thread group " + threadGroup.getName(), LogEventType.System)); if (agentRunData.getSimulationTime() != 0 && hasMetSimulationTime() && doneSignal.getCount() != 0) { boolean exceededTimeLimit = System.currentTimeMillis() > getMaxSimulationEndTimeMillis(); if (exceededTimeLimit) { LOG.info(LogUtil.getLogMessage("Max simulation time has been met and there are " + doneSignal.getCount() + " threads not reporting done.")); for (Thread t : sessionThreads) { if (t.isAlive()) { if (exceededTimeLimit) { LOG.warn( LogUtil.getLogMessage( "thread " + t.getName() + '-' + t.getId() + " is still running with a State of " + t.getState().name(), LogEventType.System)); t.interrupt(); doneSignal.countDown(); } } } } } }
From source file:ml.shifu.shifu.core.processor.TrainModelProcessor.java
private TailThread startTailThread(final String[] progressLog) { TailThread thread = new TailThread(progressLog); thread.setName("Training Progress"); thread.setDaemon(true);//from ww w .j a v a2 s. co m thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.warn(String.format("Error in thread %s: %s", t.getName(), e.getMessage())); } }); thread.start(); return thread; }
From source file:org.apache.slider.server.appmaster.SliderAppMaster.java
/** * Handle any exception in a thread. If the exception provides an exit * code, that is the one that will be used * @param thread thread throwing the exception * @param exception exception// ww w . j a v a 2 s . c o m */ public void onExceptionInThread(Thread thread, Throwable exception) { log.error("Exception in {}: {}", thread.getName(), exception, exception); // if there is a teardown in progress, ignore it if (amCompletionFlag.get()) { log.info("Ignoring exception: shutdown in progress"); } else { int exitCode = EXIT_EXCEPTION_THROWN; if (exception instanceof ExitCodeProvider) { exitCode = ((ExitCodeProvider) exception).getExitCode(); } signalAMComplete( new ActionStopSlider("stop", exitCode, FinalApplicationStatus.FAILED, exception.toString())); } }