List of usage examples for java.lang Thread getName
public final String getName()
From source file:Main.java
public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); t.start();// w w w . ja v a2s . c om // waits for this thread to die t.join(); System.out.print(t.getName()); // checks if this thread is alive System.out.println(", status = " + t.isAlive()); }
From source file:grakn.core.server.Grakn.java
public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler( (Thread t, Throwable e) -> LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(t.getName()), e)); try {/* w w w . j a v a 2 s . c o m*/ String graknPidFileProperty = Optional.ofNullable(SystemProperty.GRAKN_PID_FILE.value()).orElseThrow( () -> new RuntimeException(ErrorMessage.GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED.getMessage())); Path pidfile = Paths.get(graknPidFileProperty); PIDManager pidManager = new PIDManager(pidfile); pidManager.trackGraknPid(); // Start Server with timer Stopwatch timer = Stopwatch.createStarted(); boolean benchmark = parseBenchmarkArg(args); Server server = ServerFactory.createServer(benchmark); server.start(); LOG.info("Grakn started in {}", timer.stop()); } catch (RuntimeException | IOException e) { LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()), e); System.err.println(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage())); } }
From source file:Main.java
public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); t.start();/*from ww w . ja v a 2 s . c o m*/ t.join(2000, 500); //after waiting for 2000 milliseconds plus 500 nanoseconds ... System.out.print(t.getName()); System.out.println(", status = " + t.isAlive()); }
From source file:sample.SampleApp.java
public static void main(String[] args) throws InterruptedException { final Log logger = LogFactory.getLog(SampleApp.class); //create AWSCloudTrailProcessingExecutor and start it final AWSCloudTrailProcessingExecutor executor = new AWSCloudTrailProcessingExecutor.Builder( new SampleEventsProcessor(), "/sample/awscloudtrailprocessinglibrary.properties") .withSourceFilter(new SampleSourceFilter()).withEventFilter(new SampleEventFilter()) .withProgressReporter(new SampleProgressReporter()) .withExceptionHandler(new SampleExceptionHandler()).build(); executor.start();// ww w . ja va2 s .com // add shut down hook to gracefully stop executor (optional) Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { logger.info("Shut Down Hook is called."); executor.stop(); } }); // register a Default Uncaught Exception Handler (optional) Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logger.error("Handled by global Exception handler. " + e.getMessage() + " " + t.getName()); //Two options here: //First, we can call System.exit(1); in such case shut down hook will be called. //Second, we can optionally restart another executor and start. final AWSCloudTrailProcessingExecutor executor = new AWSCloudTrailProcessingExecutor.Builder( new SampleEventsProcessor(), "/sample/awscloudtrailprocessinglibrary.properties") .withSourceFilter(new SampleSourceFilter()).withEventFilter(new SampleEventFilter()) .withProgressReporter(new SampleProgressReporter()) .withExceptionHandler(new SampleExceptionHandler()).build(); executor.start(); } }); //can optionally limit running time, or remove both lines so it is running forever. (optional) Thread.sleep(24 * 60 * 60 * 1000); executor.stop(); }
From source file:com.microsoft.tfs.client.clc.vc.Main.java
public static void main(final String[] args) { TELoggingConfiguration.configure();// ww w . ja v a 2 s .c om final Log log = LogFactory.getLog(Main.class); log.debug("Entering Main"); //$NON-NLS-1$ Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { log.error("Unhandled exception in the thread " + t.getName() + " : ", e); //$NON-NLS-1$ //$NON-NLS-2$ /* * Let the shutdown manager clean up any registered items. */ try { log.debug("Shutting down"); //$NON-NLS-1$ ShutdownManager.getInstance().shutdown(); log.debug("Has shut down"); //$NON-NLS-1$ } catch (final Exception ex) { log.error("Unhandled exception during shutdown: ", ex); //$NON-NLS-1$ } } }); /* * Please don't do any fancy work in this method, because we have a CLC * test harness that calls Main.run() directly, and we can't test * functionality in this method (because this method can't return a * status code but exits the process directly, which kind of hoses any * test framework). */ final Main main = new Main(); int ret = ExitCode.FAILURE; try { ret = main.run(args); } catch (final Throwable e) { log.error("Unhandled exception reached Main: ", e); //$NON-NLS-1$ } finally { /* * Let the shutdown manager clean up any registered items. */ try { log.info("Shutting down"); //$NON-NLS-1$ ShutdownManager.getInstance().shutdown(); log.info("Has shut down"); //$NON-NLS-1$ } catch (final Exception e) { log.error("Unhandled exception during shutdown: ", e); //$NON-NLS-1$ } } System.exit(ret); }
From source file:Main.java
public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); t.start();/*from ww w . j a v a 2 s.co m*/ // waits at most 2000 milliseconds for this thread to die. t.join(2000); // after waiting for 2000 milliseconds... System.out.print(t.getName()); System.out.println(", status = " + t.isAlive()); }
From source file:org.apache.rya.export.client.MergeDriverClient.java
public static void main(final String[] args) throws ParseException, MergeConfigurationException, UnknownHostException, MergerException, java.text.ParseException, SailException, AccumuloException, AccumuloSecurityException, InferenceEngineException, RepositoryException, MalformedQueryException, UpdateExecutionException { final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration"); if (StringUtils.isNotBlank(log4jConfiguration)) { final String parsedConfiguration = StringUtils.removeStart(log4jConfiguration, "file:"); final File configFile = new File(parsedConfiguration); if (configFile.exists()) { DOMConfigurator.configure(parsedConfiguration); } else {// w w w . j a v a2 s .c o m BasicConfigurator.configure(); } } final MergeConfigurationCLI config = new MergeConfigurationCLI(args); try { configuration = config.createConfiguration(); } catch (final MergeConfigurationException e) { LOG.error("Configuration failed.", e); } final boolean useTimeSync = configuration.getUseNtpServer(); Optional<Long> offset = Optional.absent(); if (useTimeSync) { final String tomcat = configuration.getChildTomcatUrl(); final String ntpHost = configuration.getNtpServerHost(); try { offset = Optional .<Long>fromNullable(TimeUtils.getNtpServerAndMachineTimeDifference(ntpHost, tomcat)); } catch (final IOException e) { LOG.error("Unable to get time difference between time server: " + ntpHost + " and the server: " + tomcat, e); } } final StatementStoreFactory storeFactory = new StatementStoreFactory(configuration); try { final RyaStatementStore parentStore = storeFactory.getParentStatementStore(); final RyaStatementStore childStore = storeFactory.getChildStatementStore(); LOG.info("Starting Merge Tool"); if (configuration.getParentDBType() == ACCUMULO && configuration.getChildDBType() == ACCUMULO) { final AccumuloRyaStatementStore childAStore = (AccumuloRyaStatementStore) childStore; final AccumuloRyaStatementStore parentAStore = (AccumuloRyaStatementStore) parentStore; //do map reduce merging. //TODO: Run Merger } else { if (configuration.getMergePolicy() == TIMESTAMP) { final TimestampPolicyMergeConfiguration timeConfig = (TimestampPolicyMergeConfiguration) configuration; final Long timeOffset; if (offset.isPresent()) { timeOffset = offset.get(); } else { timeOffset = 0L; } final MemoryTimeMerger merger = new MemoryTimeMerger(parentStore, childStore, new VisibilityStatementMerger(), timeConfig.getToolStartTime(), configuration.getParentRyaInstanceName(), timeOffset); merger.runJob(); } } } catch (final Exception e) { LOG.error("Something went wrong creating a Rya Statement Store connection.", e); } Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { LOG.error("Uncaught exception in " + thread.getName(), throwable); } }); LOG.info("Finished running Merge Tool"); System.exit(1); }
From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java
/** * @param args/* ww w.j a v a2s . co m*/ */ public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logger.error("Thread {} caught unhandled exception.", t.getName()); logger.error("Unhandled exception.", e); } }); if (args.length != 2) { logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file", "path/to/out/folder"); System.exit(1); } String exptPathStr = args[0]; String outPathStr = args[1]; // Verify path points to something. Path exptPath = Paths.get(exptPathStr); if (!Files.exists(exptPath)) { logger.error("File: {} does not exist. Re-run with the correct path to " + " the experiment 2 column file. See README.md."); System.exit(1); } logger.info("Experiment map located at: {}", exptPathStr); // Create output dir if not yet created. Path outPath = Paths.get(outPathStr); if (!Files.exists(outPath)) { logger.info("Creating directory: {}", outPath.toString()); try { Files.createDirectories(outPath); } catch (IOException e) { logger.error("Caught an IOException when creating output dir.", e); System.exit(1); } } logger.info("Output directory located at: {}", outPathStr); // Read in expt map. See README.md. Map<String, Set<String>> exptMap = null; try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) { exptMap = ExperimentUtils.createFilenameToIdMap(br); } catch (IOException e) { logger.error("Caught an IOException when creating expt map.", e); System.exit(1); } // Start a timer. logger.info("Gigaword -> Concrete beginning."); StopWatch sw = new StopWatch(); sw.start(); // Iterate over expt map. exptMap.entrySet() // .parallelStream() .forEach(p -> { final String pathStr = p.getKey(); final Set<String> ids = p.getValue(); final Path lp = Paths.get(pathStr); logger.info("Converting path: {}", pathStr); // Get the file name and immediate folder it is under. int nElements = lp.getNameCount(); Path fileName = lp.getName(nElements - 1); Path subFolder = lp.getName(nElements - 2); String newFnStr = fileName.toString().split("\\.")[0] + ".tar"; // Mirror folders in output dir. Path localOutFolder = outPath.resolve(subFolder); Path localOutPath = localOutFolder.resolve(newFnStr); // Create output subfolders. if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) { logger.info("Creating out file: {}", localOutFolder.toString()); try { Files.createDirectories(localOutFolder); } catch (IOException e) { throw new RuntimeException("Caught an IOException when creating output dir.", e); } } // Iterate over communications. Iterator<Communication> citer; try (OutputStream os = Files.newOutputStream(localOutPath); BufferedOutputStream bos = new BufferedOutputStream(os); Archiver archiver = new TarArchiver(bos);) { citer = new ConcreteGigawordDocumentFactory().iterator(lp); while (citer.hasNext()) { Communication c = citer.next(); String cId = c.getId(); // Document ID must be in the set. Remove. boolean wasInSet = ids.remove(cId); if (!wasInSet) { // Some IDs are duplicated in Gigaword. // See ERRATA. logger.debug( "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.", cId, pathStr); // Attempt to create a duplicate id (append .duplicate to the id). // Then, try to remove again. String newId = RepairDuplicateIDs.repairDuplicate(cId); boolean dupeRemoved = ids.remove(newId); // There are not nested duplicates, so this should never fire. if (!dupeRemoved) { logger.info("Failed to remove dupe."); return; } else // Modify the communication ID to the unique version. c.setId(newId); } archiver.addEntry(new ArchivableCommunication(c)); } logger.info("Finished path: {}", pathStr); } catch (ConcreteException ex) { logger.error("Caught ConcreteException during Concrete mapping.", ex); logger.error("Path: {}", pathStr); } catch (IOException e) { logger.error("Error archiving communications.", e); logger.error("Path: {}", localOutPath.toString()); } }); sw.stop(); logger.info("Finished."); Minutes m = new Duration(sw.getTime()).toStandardMinutes(); logger.info("Runtime: Approximately {} minutes.", m.getMinutes()); }
From source file:Main.java
public static void main(String[] args) { Thread t = Thread.currentThread(); Main t1 = new Main(3); t1.createThread("Child 1"); t1.createThread("Child 2"); for (int i = 0; i <= 5; i++) { try {//from w w w. ja v a2s . c om Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } System.out.println("The cirrent Thread is " + t.getName() + " and thread ID is " + t.getId()); } }
From source file:com.framework.infrastructure.utils.ReflectionUtils.java
public static void main(String args[]) { Worker worker = new Worker(); Thread thread = new Thread(); thread.setName("nihao"); worker.setTask(thread);//from w w w. j a va 2 s . co m Thread thread2 = (Thread) ReflectionUtils.getFieldValue(worker, "firstTask"); System.out.println(thread2.getName()); }