List of usage examples for java.lang Thread Thread
public Thread()
From source file:Main.java
public static Runnable excAsync(final Runnable runnable, boolean isDeamon) { Thread thread = new Thread() { @Override/*from w ww . java 2 s . co m*/ public void run() { runnable.run(); } }; thread.setDaemon(isDeamon); thread.start(); return runnable; }
From source file:Main.java
public static Thread performOnBackgroundThread(final Runnable runnable) { final Thread t = new Thread() { @Override/*from w ww . j a v a 2 s . co m*/ public void run() { runnable.run(); } }; t.start(); return t; }
From source file:Main.java
public static void waitForMillis(final int millis, Context context) { Thread thread = new Thread() { @Override//from w w w .j a v a 2 s .c om public void run() { try { synchronized (this) { wait(millis); } } catch (InterruptedException ex) { } // TODO } }; thread.start(); }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {// w ww . j a va 2s. co m LoggingFactory.bootstrap(); logger.info("args: " + Arrays.toString(args)); ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true) .description("Photon Controller Core"); parser.addArgument("config-file").help("photon controller configuration file"); parser.addArgument("--manual").type(Boolean.class).setDefault(false) .help("If true, create default deployment."); Namespace namespace = parser.parseArgsOrFail(args); PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace); DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig(); new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure(); SSLContext sslContext; if (deployerConfig.getDeployerContext().isAuthEnabled()) { sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath())); keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); } else { KeyStoreUtils.generateKeys("/thrift/"); sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } ThriftModule thriftModule = new ThriftModule(sslContext); PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule, deployerConfig, sslContext); if ((Boolean) namespace.get("manual")) { DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(), deployerConfig, xenonHost); } // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config // so that it can match the Configuration class of dropwizard. File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp"); File source = new File(args[0]); FileInputStream fis = new FileInputStream(source); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(apiFeTempConfig, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { if (aLine.equals("apife:")) { aLine = aLine.replace("apife:", "server:"); } out.write(aLine); out.newLine(); } in.close(); out.close(); // This approach can be simplified once the apife container is gone, but for the time being // it expects the first arg to be the string "server". String[] apiFeArgs = new String[2]; apiFeArgs[0] = "server"; apiFeArgs[1] = apiFeTempConfig.getAbsolutePath(); ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs); ApiFeService.addServiceHost(xenonHost); ApiFeService.setSSLContext(sslContext); ApiFeService apiFeService = new ApiFeService(); apiFeService.run(apiFeArgs); apiFeTempConfig.deleteOnExit(); LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class); xenonHost.setApiClient(localApiClient); // in the non-auth enabled scenario we need to be able to accept any self-signed certificate if (!deployerConfig.getDeployerContext().isAuthEnabled()) { KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Shutting down"); xenonHost.stop(); logger.info("Done"); LoggingFactory.detachAndStop(); } }); } catch (Exception e) { logger.error("Failed to start photon controller ", e); throw e; } }
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 www .j a v a 2s . c o m Thread thread2 = (Thread) ReflectionUtils.getFieldValue(worker, "firstTask"); System.out.println(thread2.getName()); }
From source file:com.github.rwhogg.git_vcr.App.java
/** * main is the entry point for Git-VCR// w ww . j ava 2 s.c o m * @param args Command-line arguments */ public static void main(String[] args) { Options options = parseCommandLine(args); HierarchicalINIConfiguration configuration = null; try { configuration = getConfiguration(); } catch (ConfigurationException e) { Util.error("could not parse configuration file!"); } // verify we are in a git folder and then construct the repo final File currentFolder = new File("."); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository localRepo = null; try { localRepo = builder.findGitDir().build(); } catch (IOException e) { Util.error("not in a Git folder!"); } // deal with submodules assert localRepo != null; if (localRepo.isBare()) { FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder(); Repository parentRepo; try { parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build(); localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName()); } catch (IOException e) { Util.error("could not find parent of submodule!"); } } // if we need to retrieve the patch file, get it now URL patchUrl = options.getPatchUrl(); String patchPath = patchUrl.getFile(); File patchFile = null; HttpUrl httpUrl = HttpUrl.get(patchUrl); if (httpUrl != null) { try { patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff"); Request request = new Request.Builder().url(httpUrl).build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request); Response response = call.execute(); ResponseBody body = response.body(); if (!response.isSuccessful()) { Util.error("could not retrieve diff file from URL " + patchUrl); } String content = body.string(); org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null); } catch (IOException ie) { Util.error("could not retrieve diff file from URL " + patchUrl); } } else { patchFile = new File(patchPath); } // find the patch //noinspection ConstantConditions if (!patchFile.canRead()) { Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!"); } final Git git = new Git(localRepo); // handle the branch String branchName = options.getBranchName(); String theOldCommit = null; try { theOldCommit = localRepo.getBranch(); } catch (IOException e2) { Util.error("could not get reference to current branch!"); } final String oldCommit = theOldCommit; // needed to reference from shutdown hook if (branchName != null) { // switch to the branch try { git.checkout().setName(branchName).call(); } catch (RefAlreadyExistsException e) { // FIXME Auto-generated catch block e.printStackTrace(); } catch (RefNotFoundException e) { Util.error("the branch " + branchName + " was not found!"); } catch (InvalidRefNameException e) { Util.error("the branch name " + branchName + " is invalid!"); } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) { Util.error("there was a checkout conflict!"); } catch (GitAPIException e) { Util.error("there was an unspecified Git API failure!"); } } // ensure there are no changes before we apply the patch try { if (!git.status().call().isClean()) { Util.error("cannot run git-vcr while there are uncommitted changes!"); } } catch (NoWorkTreeException e1) { // won't happen assert false; } catch (GitAPIException e1) { Util.error("call to git status failed!"); } // list all the files changed String patchName = patchFile.getName(); Patch patch = new Patch(); try { patch.parse(new FileInputStream(patchFile)); } catch (FileNotFoundException e) { assert false; } catch (IOException e) { Util.error("could not parse the patch file!"); } ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false); try { oldResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // we're about to change the repo, so register a shutdown hook to clean it up Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cleanupGit(git, oldCommit); } }); // apply the patch try { git.apply().setPatch(new FileInputStream(patchFile)).call(); } catch (PatchFormatException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!"); } catch (PatchApplyException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!"); } catch (FileNotFoundException e) { assert false; } catch (GitAPIException e) { Util.error(e.getLocalizedMessage()); } ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true); try { newResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // generate and show the report VelocityReport report = new VelocityReport(patch, oldResults, newResults); File reportFile = null; try { reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html"); org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null); } catch (IOException e) { Util.error("could not generate the results page!"); } try { assert reportFile != null; Desktop.getDesktop().open(reportFile); } catch (IOException e) { Util.error("could not open the results page!"); } }
From source file:MainClass.java
public static void premain(final Instrumentation inst) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PrintWriter out = new PrintWriter(System.err); ThreadMXBean tb = ManagementFactory.getThreadMXBean(); out.printf("Current thread count: %d%n", tb.getThreadCount()); out.printf("Peak thread count: %d%n", tb.getPeakThreadCount()); List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean pool : pools) { MemoryUsage peak = pool.getPeakUsage(); out.printf("Peak %s memory used: %,d%n", pool.getName(), peak.getUsed()); out.printf("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted()); }//from w w w . j a v a2 s . c o m Class[] loaded = inst.getAllLoadedClasses(); out.println("Loaded classes:"); for (Class c : loaded) out.println(c.getName()); out.close(); } catch (Throwable t) { System.err.println("Exception in agent: " + t); } } }); }
From source file:edu.umn.cs.spatialHadoop.operations.RangeQuery.java
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); final Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();//from w w w . j a va2 s . c o m System.exit(1); } if (paths.length >= 2 && !params.checkInputOutput()) { printUsage(); System.exit(1); } if (params.get("rect") == null) { System.err.println("You must provide a query range"); printUsage(); System.exit(1); } final Path inPath = params.getInputPath(); final Path outPath = params.getOutputPath(); final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle()); // All running jobs final Vector<Long> resultsCounts = new Vector<Long>(); Vector<Job> jobs = new Vector<Job>(); Vector<Thread> threads = new Vector<Thread>(); long t1 = System.currentTimeMillis(); for (int i = 0; i < queryRanges.length; i++) { final OperationsParams queryParams = new OperationsParams(params); OperationsParams.setShape(queryParams, "rect", queryRanges[i]); if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) { // Run in local mode final Rectangle queryRange = queryRanges[i]; final Shape shape = queryParams.getShape("shape"); final Path output = outPath == null ? null : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i))); Thread thread = new Thread() { @Override public void run() { FSDataOutputStream outFile = null; final byte[] newLine = System.getProperty("line.separator", "\n").getBytes(); try { ResultCollector<Shape> collector = null; if (output != null) { FileSystem outFS = output.getFileSystem(queryParams); final FSDataOutputStream foutFile = outFile = outFS.create(output); collector = new ResultCollector<Shape>() { final Text tempText = new Text2(); @Override public synchronized void collect(Shape r) { try { tempText.clear(); r.toText(tempText); foutFile.write(tempText.getBytes(), 0, tempText.getLength()); foutFile.write(newLine); } catch (IOException e) { e.printStackTrace(); } } }; } else { outFile = null; } long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams, collector); resultsCounts.add(resultCount); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (outFile != null) outFile.close(); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); threads.add(thread); } else { // Run in MapReduce mode queryParams.setBoolean("background", true); Job job = rangeQueryMapReduce(inPath, outPath, queryParams); jobs.add(job); } } while (!jobs.isEmpty()) { Job firstJob = jobs.firstElement(); firstJob.waitForCompletion(false); if (!firstJob.isSuccessful()) { System.err.println("Error running job " + firstJob); System.err.println("Killing all remaining jobs"); for (int j = 1; j < jobs.size(); j++) jobs.get(j).killJob(); System.exit(1); } Counters counters = firstJob.getCounters(); Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS); resultsCounts.add(outputRecordCounter.getValue()); jobs.remove(0); } while (!threads.isEmpty()) { try { Thread thread = threads.firstElement(); thread.join(); threads.remove(0); } catch (InterruptedException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Results counts: " + resultsCounts); }
From source file:Main.java
private static boolean isRootOk(DataOutputStream output, DataInputStream input, final DataInputStream errInput) { if (output != null) { try {//from w ww.j a v a2s .c o m output.writeBytes("id\n"); output.flush(); String a = input.readLine(); if (a.contains("root") || a.contains("uid=0")) { return true; } new Thread() { @Override public void run() { try { errInput.read(); } catch (IOException e) { e.printStackTrace(); } }; }.start(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:br.com.rp.services.EmailService.java
public static void enviarEmailConfirmacaoConta() { new Thread() { public void run() { try { HtmlEmail email = configurarEmailPadrao(); email.addTo(""); // colocar o email da pessoa } catch (EmailException ex) { }//from w w w . j a v a 2s . c o m } }.start(); }