Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

In this page you can find the example usage for java.lang Thread setName.

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:org.zenoss.zep.index.impl.lucene.LuceneEventIndexBackend.java

public void init() {
    //Do Zenoss' default query to warm the cache on a thread, as not to delay startup
    class CacheWarmer implements Runnable {
        @Override// ww  w  .j a  v a2  s  . c  o  m
        public void run() {
            logger.info("Warming cache for {}", name);
            IndexSearcher searcher = null;
            try {
                searcher = getSearcher();
                EventFilter filter = EventFilter.newBuilder()
                        .addAllStatus(Lists.newArrayList(EventStatus.values()))
                        .addAllSeverity(Lists.newArrayList(EventSeverity.values())).build();
                Query query = buildQuery(searcher.getIndexReader(), filter, null);
                List<EventSort> sortList = new ArrayList<EventSort>(2);
                sortList.add(EventSort.newBuilder().setField(EventSort.Field.SEVERITY)
                        .setDirection(Direction.DESCENDING).build());
                sortList.add(EventSort.newBuilder().setField(EventSort.Field.LAST_SEEN)
                        .setDirection(Direction.DESCENDING).build());
                Sort sort = buildSort(sortList);
                logger.info("Warming cache for {}", name);
                searchToEventSummaryResult(searcher, query, sort, Sets.newHashSet(FIELD_PROTOBUF), 0, 1000);
                logger.info("Done warming cache for {}!", name);
                ready = true;
            } catch (Exception e) {
                logger.error("Failed to warm cache for {}", name);
                e.printStackTrace();
            } finally {
                try {
                    returnSearcher(searcher);
                } catch (ZepException e) {
                    logger.error("Failed to return searcher");
                    e.printStackTrace();
                }
            }
        }
    }
    Thread warmer = new Thread(new CacheWarmer());
    warmer.setName(name + " Cache Warmer Thread");
    warmer.start();
}

From source file:org.lsc.AbstractSynchronize.java

public final synchronized void startAsynchronousSynchronize2Ldap(Task task) {

    AsynchronousRunner asyncRunner = new AsynchronousRunner(task, this);
    String taskName = task.getName();

    Thread thread = new Thread(asyncRunner);
    thread.setName(taskName);
    asynchronousThreads.put(taskName, thread);
    mapSTasks.put(taskName, asyncRunner);
    thread.start();//from   ww w .  j a  va  2s. c o  m
}

From source file:com.mirth.connect.donkey.server.channel.DestinationConnector.java

public void startQueue() {
    if (isQueueEnabled()) {
        // Remove any items in the queue's buffer because they may be outdated and refresh the queue size
        queue.invalidate(true, true);//ww  w  .  j a  v  a  2 s .  co  m

        for (int i = 1; i <= destinationConnectorProperties.getThreadCount(); i++) {
            Thread thread = new Thread(this);
            thread.setName("Destination Queue Thread " + i + " on " + channel.getName() + " (" + getChannelId()
                    + "), " + destinationName + " (" + getMetaDataId() + ")");
            thread.start();
            queueThreads.put(thread.getId(), thread);
        }
    }
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private Thread newCloserThread() {
    final Thread closeThread = new Thread(new Runnable() {
        @Override//from  www.j a v a  2s.  c  om
        public void run() {
            try {
                Closeables.close(EmbeddedPostgres.this, true);
            } catch (IOException ex) {
                LOG.error("Unexpected IOException from Closeables.close", ex);
            }
        }
    });
    closeThread.setName("postgres-" + instanceId + "-closer");
    return closeThread;
}

From source file:com.chicm.cmraft.rpc.RpcServer.java

public void startTPSReport() {
    if (tpsReportStarted)
        return;//from   w w w  . j  a  v a  2s  .  com

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long calls = callCounter.get();
                long starttm = System.currentTimeMillis();
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    LOG.error("exception", e);
                }
                long sec = (System.currentTimeMillis() - starttm) / 1000;
                if (sec == 0)
                    sec = 1;
                long n = callCounter.get() - calls;
                LOG.info("TPS: " + (n / sec));
                LOG.info("request queue: " + requestQueue.size() + " response queue: " + responseQueue.size());
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("TPS report");
    thread.start();
    tpsReportStarted = true;
    LOG.info("TPS report started");
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.UpdateLeverageHandler.java

@SuppressWarnings("unchecked")
private void doUpdateLeverageForTask(final Long p_taskId, final String p_reApplyRefTms,
        final String p_updateFromJobs, final String p_reTryMT, final String p_selectedJobIds,
        final int p_ipTmPenalty, final String p_currentUserId) {
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                Task task = taskManager.getTask(p_taskId);
                long jobId = task.getJobId();
                Workflow workflow = task.getWorkflow();
                List<TargetPage> targetPages = workflow.getTargetPages(PrimaryFile.EXTRACTED_FILE);
                percentageMap.put(jobId, 0);
                int count = 0;
                int total = targetPages.size() * 3;
                for (TargetPage tp : targetPages) {
                    // 1.Re-leverage reference TMs
                    if ("on".equals(p_reApplyRefTms)) {
                        reApplyRefTms(task.getWorkflow(), tp, p_currentUserId);
                    }/*from  ww w.  j  av a 2s  .  c o  m*/
                    count++;
                    percentageMap.put(jobId, Math.round(count * 100 / total));
                    // 2. Update from jobs
                    if ("on".equals(p_updateFromJobs)) {
                        String[] selectedJobs = StringUtils.split(p_selectedJobIds, " ");
                        updateFromJobs(task.getWorkflow(), selectedJobs, p_ipTmPenalty, tp, p_currentUserId);
                    }
                    count++;
                    percentageMap.put(jobId, Math.round(count * 100 / total));
                    // 3. Re-try MT
                    if ("on".equals(p_reTryMT)) {
                        updateFromMT(task.getWorkflow(), tp, p_currentUserId);
                    }
                    count++;
                    percentageMap.put(jobId, Math.round(count * 100 / total));
                }
                percentageMap.put(jobId, 100);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    };

    try {
        // Set the percentage to 0 to ensure previous operation won't impact
        // this time.
        Task task = taskManager.getTask(p_taskId);
        long jobId = task.getJobId();
        percentageMap.put(jobId, 0);
    } catch (Exception ex) {
        logger.warn("Failed to set the update leverage percentage to 0");
        ex.printStackTrace();
    }

    Thread t = new MultiCompanySupportedThread(runnable);
    t.setName("Update Leverage " + String.valueOf(p_currentUserId));
    t.start();
}

From source file:org.dasein.cloud.rackspace.compute.CloudServerImages.java

@Override
public void captureImageAsync(final @Nonnull ImageCreateOptions options,
        final @Nonnull AsynchronousTask<MachineImage> taskTracker) throws CloudException, InternalException {
    Thread t = new Thread() {
        public void run() {
            try {
                capture(options, taskTracker);
            } catch (Throwable t) {
                taskTracker.complete(t);
            } finally {
                provider.release();/*from www . ja v a2s.co  m*/
            }
        }
    };
    provider.hold();

    t.setName("Image Capture: " + options.getVirtualMachineId());
    t.setDaemon(true);
    t.start();
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.UpdateLeverageHandler.java

@SuppressWarnings("unchecked")
private void doUpdateLeverageForWfs(final List<Long> p_workflowIds, final String p_reApplyRefTms,
        final String p_updateFromJobs, final String p_reTryMT, final String p_selectedJobIds,
        final int p_ipTmPenalty, final String p_currentUserId) throws Exception {
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                Job job = workflowManager.getWorkflowById(p_workflowIds.get(0)).getJob();
                int sourcePageNumber = job.getSourcePages(PrimaryFile.EXTRACTED_FILE).size();
                long jobId = job.getId();
                percentageMap.put(jobId, 0);
                // Only ready workflows should be updated leverage from job
                // details UI.
                List<Long> validWfIds = UpdateLeverageHelper.filterWorkflowsByState(p_workflowIds,
                        Workflow.READY_TO_BE_DISPATCHED);
                if (validWfIds != null && validWfIds.size() > 0) {
                    int count = 0;
                    int total = validWfIds.size() * sourcePageNumber * 3;
                    for (Iterator<Long> it = validWfIds.iterator(); it.hasNext();) {
                        Long wfId = it.next();
                        Workflow wf = workflowManager.getWorkflowById(wfId);
                        List<TargetPage> targetPages = wf.getTargetPages(PrimaryFile.EXTRACTED_FILE);
                        for (TargetPage tp : targetPages) {
                            // 1.Re-leverage reference TMs
                            if ("on".equals(p_reApplyRefTms)) {
                                reApplyRefTms(wf, tp, p_currentUserId);
                            }//www .ja  v  a  2  s  .c o m
                            count++;
                            percentageMap.put(jobId, Math.round(count * 100 / total));
                            // 2. Update from jobs
                            if ("on".equals(p_updateFromJobs)) {
                                String[] selectedJobs = StringUtils.split(p_selectedJobIds, " ");
                                selectedJobs = filterJobs(selectedJobs, wf);
                                if (selectedJobs.length > 0) {
                                    updateFromJobs(wf, selectedJobs, p_ipTmPenalty, tp, p_currentUserId);
                                }
                            }
                            count++;
                            percentageMap.put(jobId, Math.round(count * 100 / total));

                            //3.Re try MT
                            if ("on".equals(p_reTryMT)) {
                                updateFromMT(wf, tp, p_currentUserId);
                            }
                            count++;
                            percentageMap.put(jobId, Math.round(count * 100 / total));
                        }
                    }
                }
                // Anyway, set this to ensure the process bar will end.
                percentageMap.put(jobId, 100);
                logger.info("========== Update Leverage finished ==========");
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    };

    // Set the percentage to 0 to ensure previous operation won't impact
    // this time.
    Job job = workflowManager.getWorkflowById(p_workflowIds.get(0)).getJob();
    percentageMap.put(job.getId(), 0);
    Thread t = new MultiCompanySupportedThread(runnable);
    t.setName("Update Leverage " + String.valueOf(p_currentUserId));
    t.start();
}

From source file:password.pwm.http.servlet.ConfigManagerServlet.java

private void outputZipDebugFile(final PwmRequest pwmRequest, final ZipOutputStream zipOutput,
        final String pathPrefix) throws IOException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();

    { // kick off health check so that it might be faster later..
        Thread healthThread = new Thread() {
            public void run() {
                pwmApplication.getHealthMonitor().getHealthRecords();
            }/*from   w  w w .  ja v  a  2  s  .co m*/
        };
        healthThread
                .setName(Helper.makeThreadName(pwmApplication, ConfigManagerServlet.class) + "-HealthCheck");
        healthThread.setDaemon(true);
        healthThread.start();
    }
    final StoredConfiguration storedConfiguration = readCurrentConfiguration(pwmRequest);
    storedConfiguration.resetAllPasswordValues(
            "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export");
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + PwmConstants.DEFAULT_CONFIG_FILE_FILENAME));
        storedConfiguration.resetAllPasswordValues(
                "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export");

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        storedConfiguration.toXml(outputStream);
        zipOutput.write(outputStream.toByteArray());
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "configuration-debug.txt"));
        zipOutput.write(storedConfiguration.toString(true).getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        final String aboutJson = JsonUtil.serialize(AdminServlet.makeInfoBean(pwmApplication),
                JsonUtil.Flag.PrettyPrint);
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "about.json"));
        zipOutput.write(aboutJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pwmApplication.getAuditManager().outputVaultToCsv(baos, pwmRequest.getLocale(), true);
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "audit.csv"));
        zipOutput.write(baos.toByteArray());
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "info.json"));
        final LinkedHashMap<String, Object> outputMap = new LinkedHashMap<>();

        { // services info
            final LinkedHashMap<String, Object> servicesMap = new LinkedHashMap<>();
            for (final PwmService service : pwmApplication.getPwmServices()) {
                final LinkedHashMap<String, Object> serviceOutput = new LinkedHashMap<>();
                serviceOutput.put("name", service.getClass().getSimpleName());
                serviceOutput.put("status", service.status());
                serviceOutput.put("health", service.healthCheck());
                serviceOutput.put("serviceInfo", service.serviceInfo());
                servicesMap.put(service.getClass().getSimpleName(), serviceOutput);
            }
            outputMap.put("services", servicesMap);
        }

        // java threads
        outputMap.put("threads", Thread.getAllStackTraces());

        final String recordJson = JsonUtil.serializeMap(outputMap, JsonUtil.Flag.PrettyPrint);
        zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    if (pwmApplication.getApplicationPath() != null) {
        try {
            zipOutput.putNextEntry(new ZipEntry(pathPrefix + "fileMd5sums.json"));
            final Map<String, String> fileChecksums = BuildChecksumMaker
                    .readDirectorySums(pwmApplication.getApplicationPath());
            final String json = JsonUtil.serializeMap(fileChecksums, JsonUtil.Flag.PrettyPrint);
            zipOutput.write(json.getBytes(PwmConstants.DEFAULT_CHARSET));
            zipOutput.closeEntry();
            zipOutput.flush();
        } catch (Exception e) {
            LOGGER.error(pwmSession,
                    "unable to generate fileMd5sums during zip debug building: " + e.getMessage());
        }
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "debug.log"));
        final int maxCount = 100 * 1000;
        final int maxSeconds = 30 * 1000;
        final LocalDBLogger.SearchParameters searchParameters = new LocalDBLogger.SearchParameters(
                PwmLogLevel.TRACE, maxCount, null, null, maxSeconds, null);
        final LocalDBLogger.SearchResults searchResults = pwmApplication.getLocalDBLogger()
                .readStoredEvents(searchParameters);
        int counter = 0;
        while (searchResults.hasNext()) {
            final PwmLogEvent event = searchResults.next();
            zipOutput.write(event.toLogString().getBytes(PwmConstants.DEFAULT_CHARSET));
            zipOutput.write("\n".getBytes(PwmConstants.DEFAULT_CHARSET));
            counter++;
            if (counter % 100 == 0) {
                zipOutput.flush();
            }
        }
        zipOutput.closeEntry();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "health.json"));
        final Set<HealthRecord> records = pwmApplication.getHealthMonitor().getHealthRecords();
        final String recordJson = JsonUtil.serializeCollection(records, JsonUtil.Flag.PrettyPrint);
        zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

@Test
public void configureClientSSLSocketCanTimeOut() throws Exception {
    final Semaphore serverCoordination = new Semaphore(0);

    // configure a non-SSL server socket. We will connect
    // a client SSL socket to it and demonstrate that the
    // handshake times out
    final ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0));
    Thread serverThread = new Thread() {
        public void run() {
            serverCoordination.release();
            try (Socket clientSocket = serverSocket.accept()) {
                System.out.println("server thread accepted a connection");
                serverCoordination.acquire();
            } catch (Exception e) {
                System.err.println("accept failed");
                e.printStackTrace();//from   w  w  w  .  j a v a2 s.com
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                // ignored
            }
            System.out.println("server thread is exiting");
        }
    };
    serverThread.setName("SocketCreatorJUnitTest serverSocket thread");
    serverThread.setDaemon(true);
    serverThread.start();

    serverCoordination.acquire();

    SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER);

    int serverSocketPort = serverSocket.getLocalPort();
    try {
        Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> {
            try {
                Socket clientSocket = socketCreator.connectForClient(
                        SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000);
                clientSocket.close();
                System.err.println(
                        "client successfully connected to server but should not have been able to do so");
                return false;
            } catch (SocketTimeoutException e) {
                // we need to verify that this timed out in the handshake
                // code
                System.out.println("client connect attempt timed out - checking stack trace");
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement element : trace) {
                    if (element.getMethodName().equals("configureClientSSLSocket")) {
                        System.out.println("client connect attempt timed out in the appropriate method");
                        return true;
                    }
                }
                // it wasn't in the configuration method so we need to try again
            } catch (IOException e) {
                // server socket may not be in accept() yet, causing a connection-refused
                // exception
            }
            return false;
        });
    } finally {
        serverCoordination.release();
    }
}