List of usage examples for java.lang Thread setName
public final synchronized void setName(String name)
From source file:org.apache.lens.driver.es.ESDriver.java
@Override public void configure(Configuration conf, String driverType, String driverName) throws LensException { super.configure(conf, driverType, driverName); config = new ESDriverConfig(getConf()); Class klass;/*from www . j a v a 2 s. com*/ try { klass = Class.forName(getConf().get(ESDriverConfig.CLIENT_CLASS_KEY)); if (klass != null) { log.debug("Picked up class {}", klass); if (ESClient.class.isAssignableFrom(klass)) { final Constructor constructor = klass.getConstructor(ESDriverConfig.class, Configuration.class); esClient = (ESClient) constructor.newInstance(config, getConf()); log.debug("Successfully instantiated es client of type {}", klass); } } else { log.debug("Client class not provided, falling back to the default Jest client"); esClient = new JestClientImpl(config, conf); } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { log.error("ES driver {} cannot start!", getFullyQualifiedName(), e); throw new LensException("Cannot start es driver", e); } log.info("ES Driver {} configured", getFullyQualifiedName()); asyncQueryPool = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread th = new Thread(runnable); th.setName("lens-driver-es-" + THID.incrementAndGet()); return th; } }); }
From source file:ch.usi.da.paxos.ring.LearnerRole.java
@Override public void run() { ring.getNetwork().registerCallback(this); Thread t = new Thread(new LearnerStatsWriter(ring, this)); t.setName("LearnerStatsWriter"); t.start();/*w ww . j av a2 s . c o m*/ if (latch != null) { latch.countDown(); } while (true) { try { Decision head = delivery.peek(); // initial recovering if (!recovered && recovery && head != null) { Message m = new Message(0, ring.getNodeID(), PaxosRole.Leader, MessageType.Safe, 0, 0, new Value("", "0".getBytes())); m.setVoteCount(1); logger.debug("Send safe message to recover highest_online_instance. (" + recovered + "," + delivery.isEmpty() + ")"); ring.getNetwork().send(m); } // re-request missing decisions else if (head != null && head.getInstance() > delivered_instance) { for (long i = delivered_instance + 1; i < head.getInstance(); i++) { if (highest_online_instance == 0 || i >= highest_online_instance) { Message m = new Message(i, ring.getNodeID(), PaxosRole.Leader, MessageType.Relearn, 0, 0, null); logger.debug("Learner re-request missing instance " + i); ring.getNetwork().receive(m); } else { recovered = false; } } } Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } }
From source file:edu.umass.cs.nio.AbstractPacketDemultiplexer.java
/** * //from www.j a v a 2 s.c o m * @param threadPoolSize * Refer documentation for {@link #setThreadPoolSize(int) * setThreadPoolsize(int)}. */ public AbstractPacketDemultiplexer(int threadPoolSize) { this.executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(threadPoolSize, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setName(threadName); return thread; } }); this.myThreadPoolSize = threadPoolSize; }
From source file:org.kududb.client.MiniKuduCluster.java
/** * Starts a process using the provided command and configures it to be daemon, * redirects the stderr to stdout, and starts a thread that will read from the process' input * stream and redirect that to LOG./* w w w. jav a 2 s . c om*/ * @param command Process and options * @return The started process * @throws Exception Exception if an error prevents us from starting the process, * or if we were able to start the process but noticed that it was then killed (in which case * we'll log the exit value). */ private Process configureAndStartProcess(String[] command) throws Exception { LOG.info("Starting process: {}", Joiner.on(" ").join(command)); ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); Process proc = processBuilder.start(); ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable( proc.getInputStream()); Thread thread = new Thread(printer); thread.setDaemon(true); thread.setName(command[0]); PROCESS_INPUT_PRINTERS.add(thread); thread.start(); Thread.sleep(300); try { int ev = proc.exitValue(); throw new Exception( "We tried starting a process (" + command[0] + ") but it exited with " + "value=" + ev); } catch (IllegalThreadStateException ex) { // This means the process is still alive, it's like reverse psychology. } return proc; }
From source file:com.wallabystreet.kinjo.common.transport.protocol.jxta.Peer.java
@Override public void registerService(ServiceDescriptor s) throws RegistrationFailureException { /* Get the peer group's discovery service. */ DiscoveryService ds = this.group.getDiscoveryService(); /*//from w w w . j a v a2 s .c om * Obtain the module class advertisement for the requested service from * its service descriptor and try to publish it to the JXTA network. */ ModuleClassAdvertisement mca = (ModuleClassAdvertisement) s.getProperty("transport.jxta.adv.mc"); try { ds.publish(mca); log.debug("module class advertisement publishing (local) successful"); } catch (IOException e) { String msg = "publishing of the ModuleClassAdvertisement failed"; log.debug(msg, e); throw new RegistrationFailureException(e); } ds.remotePublish(mca); log.debug("module class advertisement publishing (remote) successful"); /* * Create the pipe advertisement for the given service, respecting the * peer group the system is connected to. */ PipeAdvertisement pa = Utilities.createPipeAdvertisement(s); pa.setPipeID(IDFactory.newPipeID(this.group.getPeerGroupID())); /* * Obtain the module spec advertisement for the requested service from * its service descriptor, add the service's pipe advertisement to it * and try to publish it to the JXTA network. */ ModuleSpecAdvertisement msa = (ModuleSpecAdvertisement) s.getProperty("transport.jxta.adv.ms"); msa.setPipeAdvertisement(pa); try { ds.publish(msa); log.debug("module spec advertisement publishing (local) successful"); } catch (IOException e) { String msg = "publishing of the ModuleSpecAdvertisement failed"; log.debug(msg, e); throw new RegistrationFailureException(e); } ds.remotePublish(msa); log.debug("module spec advertisement publishing (remote) successful"); // deploy the service to the WS engine. try { WSEngine.getInstance().deploy(s); } catch (DeploymentException e) { log.debug("service deployment failed", e); throw new RegistrationFailureException(e); } /* * Create a listener thread for the JXTA server pipe, using a * ServiceHandler instance, name it and keep the object in the classes */ JXTAServiceHandler h = new JXTAServiceHandler(s, pa); Thread handler = new Thread(h); handler.setName(s.getName() + " (service handler)"); this.serviceHandlers.put(s, h); handler.start(); log.debug("service registration complete"); }
From source file:com.hubcap.task.TaskRunner.java
/** * Starts the ThreadPoolExecutor which builds a set of TaskRunner instances * which will wait for inputs (from the user) */// w w w . j a va 2 s . co m public static void startThreadPool() { if (!isTaskSystemReady) { System.out.println("startThreadPool()"); isTaskSystemReady = true; // used to id the threads 'atomically' final AtomicLong count = new AtomicLong(0); if (TaskRunner.taskRunnerThreadFactory == null) { TaskRunner.taskRunnerThreadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { if (runningTasks.contains(r)) { throw new IllegalStateException("Cannot add duplicate runnable to running tasks"); } Thread thread = new Thread(r); thread.setDaemon(false); thread.setName("HubcapTaskRunnerThread-" + count.getAndIncrement()); taskThreads.add(thread); return thread; } }; // calculates the current stable thread count based on the // assumption // that it takes 'X' times the amount of time to transfer data // (from github) // as it does to process said data (including Gson // transformation) // and the limit of Y% use of CPU. MAX_THREADS provides a safe // and stable cap for // systems that are so 'badass' that we would break the cap. \ // (i.e. i have 32 cores and 12 disks = (2*32*12*1(1+5/1) = // 4600 threads, a bit high)...) int numThreads = ThreadUtils.getStableThreadCount(CPU_LOAD_TR, CPU_WAIT_TR, CPU_COMPUTE_TR, Constants.MAX_TASK_RUNNER_THREADS); System.out.println("creating: " + numThreads + " threads for hubcap"); TaskRunner.taskRunnerThreadPool = Executors.newFixedThreadPool(numThreads, TaskRunner.taskRunnerThreadFactory); for (int i = 0; i < numThreads; ++i) { TaskRunner tr = new TaskRunner(); taskRunnerThreadPool.execute(tr); } // pass the monitoring code to another thread // so we don't block the REPL loop monitorThread = new Thread(new Runnable() { @Override public void run() { while (!taskRunnerThreadPool.isShutdown()) { try { TaskRunner.rebalance(); Thread.sleep(Constants.POOL_SHUTDOWN_CHECK_INTERVAL); } catch (InterruptedException ex) { if (ProcessModel.instance().getVerbose()) { ErrorUtils.printStackTrace(ex); } break; } } System.out.println("Thread Pool was shutdown"); while (!taskRunnerThreadPool.isTerminated()) { try { Thread.sleep(Constants.POOL_TERM_CHECK_INTERVAL); } catch (InterruptedException ex) { ErrorUtils.printStackTrace(ex); break; } } System.out.println("Thread pool terminated."); } }); monitorThread.setName("TaskMonDaemon"); monitorThread.setDaemon(false); // start monitoring monitorThread.start(); System.out.println("Thread pool started!"); } } else { throw new IllegalStateException("Hubcap task runner can only be initialized once!"); } }
From source file:mServer.crawler.sender.MediathekSwr.java
@Override public synchronized void addToList() { meldungStart();/*ww w . ja v a2 s . c o m*/ //Theman suchen listeThemen.clear(); addToList__(); if (CrawlerTool.loadLongMax()) { addToList_verpasst(); // brauchst eigentlich nicht und dauer zu lange } if (Config.getStop()) { meldungThreadUndFertig(); } else if (listeThemen.isEmpty()) { meldungThreadUndFertig(); } else { meldungAddMax(listeThemen.size()); for (int t = 0; t < getMaxThreadLaufen(); ++t) { Thread th = new ThemaLaden(); th.setName(SENDERNAME + t); th.start(); } } }
From source file:org.apache.hadoop.hbase.ipc.RpcExecutor.java
protected void startHandlers(final String nameSuffix, final int numHandlers, final List<BlockingQueue<CallRunner>> callQueues, final int qindex, final int qsize, final int port) { final String threadPrefix = name + Strings.nullToEmpty(nameSuffix); for (int i = 0; i < numHandlers; i++) { final int index = qindex + (i % qsize); Thread t = new Thread(new Runnable() { @Override// w w w. j a v a 2 s.c o m public void run() { consumerLoop(callQueues.get(index)); } }); t.setDaemon(true); t.setName(threadPrefix + "RpcServer.handler=" + handlers.size() + ",queue=" + index + ",port=" + port); t.start(); LOG.debug(threadPrefix + " Start Handler index=" + handlers.size() + " queue=" + index); handlers.add(t); } }
From source file:com.garyclayburg.attributes.AttributeService.java
public void setScriptRunner(ScriptRunner runner) { log.info("setting scriptrunner..."); this.runner = runner; if (runner.getRoots() != null) { initiallyScanned = false;//from w w w. j a v a 2 s . com Runnable runnable = new Runnable() { public void run() { /* loading scripts in a background thread improves startup performance, especially when scripts are located on a slow file system such as S3 */ synchronized (groovyClassMap) { initiallyScanned = true; scanGroovyClasses(); } } }; Thread t = new Thread(runnable); t.setName("pre-load" + String.valueOf(Math.random()).substring(2, 6)); log.info("starting pre-load thread: " + t.getName()); t.start(); } else { // use read-only embedded scripts log.warn( "Custom groovy policy scripts not found. Defaulting to read-only embedded groovy policy scripts"); initiallyScanned = true; ClassLoader parent = getClass().getClassLoader(); String scriptName = "embeddedgroovy/com/embedded/DefaultAttributes.groovy"; InputStream groovyIS = parent.getResourceAsStream(scriptName); StringBuilder sb = new StringBuilder(); try (Reader reader = new BufferedReader( new InputStreamReader(groovyIS, Charset.forName(StandardCharsets.UTF_8.name())))) { int c; while ((c = reader.read()) != -1) { sb.append((char) c); } // log.debug("complete default embedded groovy class:\n{}",sb.toString()); GroovyClassLoader loader = new GroovyClassLoader(parent); Class parsedDefaultClass = loader.parseClass(sb.toString(), scriptName); groovyClassMap.clear(); groovyClassMap.put(scriptName, parsedDefaultClass); } catch (IOException e) { log.warn("could not load embedded groovy scripts", e); } log.debug("finished reading embedded groovy"); } }
From source file:org.rhq.enterprise.server.plugins.alertCli.CliSender.java
private static InputStream getPackageBits(int packageId, int repoId) throws IOException { final ContentSourceManagerLocal csm = LookupUtil.getContentSourceManager(); RepoManagerLocal rm = LookupUtil.getRepoManagerLocal(); final PackageVersion versionToUse = rm.getLatestPackageVersion(LookupUtil.getSubjectManager().getOverlord(), packageId, repoId);//w w w . j av a 2 s .co m if (versionToUse == null) { throw new IllegalArgumentException("The package with id " + packageId + " either doesn't exist at all or doesn't have any version. Can't execute a CLI script without a script to run."); } PipedInputStream ret = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(ret); Thread reader = new Thread(new Runnable() { public void run() { try { csm.outputPackageVersionBits(versionToUse, out); } catch (RuntimeException e) { LOG.warn("The thread for reading the bits of package version [" + versionToUse + "] failed with exception.", e); throw e; } finally { try { out.close(); } catch (IOException e) { //doesn't happen in piped output stream LOG.error( "Failed to close the piped output stream receiving the package bits of package version " + versionToUse + ". This should never happen.", e); } } } }); reader.setName("CLI Alert download thread for package version " + versionToUse); reader.setDaemon(true); reader.start(); return ret; }