Example usage for java.lang Thread getPriority

List of usage examples for java.lang Thread getPriority

Introduction

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

Prototype

public final int getPriority() 

Source Link

Document

Returns this thread's priority.

Usage

From source file:org.apache.bookkeeper.common.testing.util.TimedOutTestsListener.java

static String buildThreadDump() {
    StringBuilder dump = new StringBuilder();
    Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> e : stackTraces.entrySet()) {
        Thread thread = e.getKey();
        dump.append(String.format("\"%s\" %s prio=%d tid=%d %s\njava.lang.Thread.State: %s", thread.getName(),
                (thread.isDaemon() ? "daemon" : ""), thread.getPriority(), thread.getId(),
                Thread.State.WAITING.equals(thread.getState()) ? "in Object.wait()"
                        : StringUtils.lowerCase(thread.getState().name()),
                Thread.State.WAITING.equals(thread.getState()) ? "WAITING (on object monitor)"
                        : thread.getState()));
        for (StackTraceElement stackTraceElement : e.getValue()) {
            dump.append("\n        at ");
            dump.append(stackTraceElement);
        }/*w ww  .  j a  va  2s .c om*/
        dump.append("\n");
    }
    return dump.toString();
}

From source file:org.apache.hadoop.fs.s3r.S3RFileSystem.java

/**
 * Get a named {@link ThreadFactory} that just builds daemon threads.
 * @param prefix name prefix for all threads created from the factory
 * @return a thread factory that creates named, daemon threads with
 *         the supplied exception handler and normal priority
 *///from   ww  w.  ja  v a  2s  .  c o m
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    };
}

From source file:org.jumpmind.symmetric.service.impl.DataLoaderService.java

public void start() {
    dataLoadWorkers = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-data-load-worker-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);// w  w  w  .  j a  va2 s . com
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });
}

From source file:org.jumpmind.symmetric.service.impl.NodeCommunicationService.java

protected ThreadPoolExecutor getExecutor(final CommunicationType communicationType) {
    ThreadPoolExecutor service = executors.get(communicationType);

    String threadCountParameter = "";
    switch (communicationType) {
    case PULL:/*from  w w  w .  j a  v  a2s . com*/
        threadCountParameter = ParameterConstants.PULL_THREAD_COUNT_PER_SERVER;
        break;
    case PUSH:
        threadCountParameter = ParameterConstants.PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PULL:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case FILE_PUSH:
        threadCountParameter = ParameterConstants.FILE_PUSH_THREAD_COUNT_PER_SERVER;
        break;
    case EXTRACT:
        threadCountParameter = ParameterConstants.INITIAL_LOAD_EXTRACT_THREAD_COUNT_PER_SERVER;
        break;
    default:
        break;
    }
    int threadCount = parameterService.getInt(threadCountParameter, 1);

    if (service != null && service.getCorePoolSize() != threadCount) {
        log.info("{} has changed from {} to {}.  Restarting thread pool",
                new Object[] { threadCountParameter, service.getCorePoolSize(), threadCount });
        stop();
        service = null;
    }

    if (service == null) {
        synchronized (this) {
            service = executors.get(communicationType);
            if (service == null) {
                if (threadCount <= 0) {
                    log.warn("{}={} is not a valid value. Defaulting to 1", threadCountParameter, threadCount);
                    threadCount = 1;
                } else if (threadCount > 1) {
                    log.info("{} will use {} threads", communicationType.name().toLowerCase(), threadCount);
                }
                service = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
                    final AtomicInteger threadNumber = new AtomicInteger(1);
                    final String namePrefix = parameterService.getEngineName().toLowerCase() + "-"
                            + communicationType.name().toLowerCase() + "-";

                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName(namePrefix + threadNumber.getAndIncrement());
                        if (t.isDaemon()) {
                            t.setDaemon(false);
                        }
                        if (t.getPriority() != Thread.NORM_PRIORITY) {
                            t.setPriority(Thread.NORM_PRIORITY);
                        }
                        return t;
                    }
                });
                executors.put(communicationType, service);
            }
        }
    }
    return service;
}

From source file:org.jumpmind.symmetric.service.impl.PushService.java

public void start() {
    nodeChannelExtractForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-extract-for-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);/*w w  w . j  a  v a  2 s  .com*/
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });

    nodeChannelTransportForPushWorker = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix = parameterService.getEngineName().toLowerCase() + "-push-";

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    });
}

From source file:org.jumpmind.symmetric.service.impl.RouterService.java

protected IDataToRouteReader startReading(ChannelRouterContext context) {
    IDataToRouteReader reader = new DataGapRouteReader(context, engine);
    if (parameterService.is(ParameterConstants.SYNCHRONIZE_ALL_JOBS)) {
        reader.run();/*from   w w w .j a v  a  2 s .  co m*/
    } else {
        if (readThread == null) {
            readThread = Executors.newCachedThreadPool(new ThreadFactory() {
                final AtomicInteger threadNumber = new AtomicInteger(1);
                final String namePrefix = parameterService.getEngineName().toLowerCase() + "-router-reader-";

                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName(namePrefix + threadNumber.getAndIncrement());
                    if (t.isDaemon()) {
                        t.setDaemon(false);
                    }
                    if (t.getPriority() != Thread.NORM_PRIORITY) {
                        t.setPriority(Thread.NORM_PRIORITY);
                    }
                    return t;
                }
            });
        }
        readThread.execute(reader);
    }

    return reader;
}

From source file:org.kuali.kfs.sys.context.SpringContext.java

static void initMonitoringThread() {
    if (KRADServiceLocator.getKualiConfigurationService().getPropertyValueAsBoolean("periodic.thread.dump")) {
        final long sleepPeriod = Long.parseLong(KRADServiceLocator.getKualiConfigurationService()
                .getPropertyValueAsString("periodic.thread.dump.seconds")) * 1000;
        final File logDir = new File(
                KRADServiceLocator.getKualiConfigurationService().getPropertyValueAsString("logs.directory"));
        final File monitoringLogDir = new File(logDir, "monitoring");
        if (!monitoringLogDir.exists()) {
            monitoringLogDir.mkdir();/*from   w w  w  . j a va  2s. co  m*/
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("Starting the Periodic Thread Dump thread - dumping every " + (sleepPeriod / 1000)
                    + " seconds");
            LOG.info("Periodic Thread Dump Logs: " + monitoringLogDir.getAbsolutePath());
        }
        final DateFormat df = new SimpleDateFormat("yyyyMMdd");
        final DateFormat tf = new SimpleDateFormat("HH-mm-ss");
        Runnable processWatch = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Date now = new Date();
                    File todaysLogDir = new File(monitoringLogDir, df.format(now));
                    if (!todaysLogDir.exists()) {
                        todaysLogDir.mkdir();
                    }
                    File logFile = new File(todaysLogDir, "process-" + tf.format(now) + ".log");
                    try {
                        createParentDirs(logFile);
                        BufferedWriter w = new BufferedWriter(new FileWriter(logFile));
                        StringBuilder logStatement = new StringBuilder(10240);
                        logStatement.append("Threads Running at: ").append(now).append("\n\n\n");
                        Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
                        List<Thread> sortedThreads = new ArrayList<Thread>(threads.keySet());
                        Collections.sort(sortedThreads, new Comparator<Thread>() {
                            @Override
                            public int compare(Thread o1, Thread o2) {
                                return o1.getName().compareTo(o2.getName());
                            }
                        });
                        for (Thread t : sortedThreads) {
                            logStatement.append("\tThread: name=").append(t.getName()).append(", id=")
                                    .append(t.getId()).append(", priority=").append(t.getPriority())
                                    .append(", state=").append(t.getState());
                            logStatement.append('\n');
                            for (StackTraceElement stackTraceElement : threads.get(t)) {
                                logStatement.append("\t\t" + stackTraceElement).append('\n');
                            }
                            logStatement.append('\n');
                        }
                        w.write(logStatement.toString());
                        w.close();
                    } catch (IOException ex) {
                        LOG.error("Unable to write the ProcessWatch output file: " + logFile.getAbsolutePath(),
                                ex);
                    }
                    try {
                        Thread.sleep(sleepPeriod);
                    } catch (InterruptedException ex) {
                        LOG.error("woken up during sleep of the ProcessWatch thread", ex);
                    }
                }
            }
        };
        processWatchThread = new Thread(processWatch, "ProcessWatch thread");
        processWatchThread.setDaemon(true);
        processWatchThread.start();
    }
}

From source file:org.kuali.ole.sys.context.SpringContext.java

static void initMonitoringThread() {
    ConfigurationService configurationService = GlobalResourceLoader.getService("kualiConfigurationService");
    if (configurationService.getPropertyValueAsBoolean("periodic.thread.dump")) {
        final long sleepPeriod = Long.parseLong(
                configurationService.getPropertyValueAsString("periodic.thread.dump.seconds")) * 1000;
        final File logDir = new File(configurationService.getPropertyValueAsString("logs.directory"));
        final File monitoringLogDir = new File(logDir, "monitoring");
        if (!monitoringLogDir.exists()) {
            monitoringLogDir.mkdir();//from ww w  .  ja  v a 2  s  .  c  om
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("Starting the Periodic Thread Dump thread - dumping every " + (sleepPeriod / 1000)
                    + " seconds");
            LOG.info("Periodic Thread Dump Logs: " + monitoringLogDir.getAbsolutePath());
        }
        final DateFormat df = new SimpleDateFormat("yyyyMMdd");
        final DateFormat tf = new SimpleDateFormat("HH-mm-ss");
        Runnable processWatch = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Date now = new Date();
                    File todaysLogDir = new File(monitoringLogDir, df.format(now));
                    if (!todaysLogDir.exists()) {
                        todaysLogDir.mkdir();
                    }
                    File logFile = new File(todaysLogDir, "process-" + tf.format(now) + ".log");
                    try {
                        StringBuilder logStatement = new StringBuilder(10240);
                        logStatement.append("Threads Running at: ").append(now).append("\n\n\n");
                        Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
                        List<Thread> sortedThreads = new ArrayList<Thread>(threads.keySet());
                        Collections.sort(sortedThreads, new Comparator<Thread>() {
                            @Override
                            public int compare(Thread o1, Thread o2) {
                                return o1.getName().compareTo(o2.getName());
                            }
                        });
                        for (Thread t : sortedThreads) {
                            logStatement.append("\tThread: name=").append(t.getName()).append(", id=")
                                    .append(t.getId()).append(", priority=").append(t.getPriority())
                                    .append(", state=").append(t.getState());
                            logStatement.append('\n');
                            for (StackTraceElement stackTraceElement : threads.get(t)) {
                                logStatement.append("\t\t" + stackTraceElement).append('\n');
                            }
                            logStatement.append('\n');
                        }
                        FileUtils.writeStringToFile(logFile, logStatement.toString(), "UTF-8");
                    } catch (IOException ex) {
                        LOG.error("Unable to write the ProcessWatch output file: " + logFile.getAbsolutePath(),
                                ex);
                    }
                    try {
                        Thread.sleep(sleepPeriod);
                    } catch (InterruptedException ex) {
                        LOG.error("woken up during sleep of the ProcessWatch thread", ex);
                    }
                }
            }
        };
        processWatchThread = new Thread(processWatch, "ProcessWatch thread");
        processWatchThread.setDaemon(true);
        processWatchThread.start();
    }
}

From source file:org.midonet.midolman.Midolman.java

public static void dumpStacks() {
    Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Thread thread : traces.keySet()) {
        System.err.print("\"" + thread.getName() + "\" ");
        if (thread.isDaemon())
            System.err.print("daemon ");
        System.err.print(String.format("prio=%x tid=%x %s [%x]\n", thread.getPriority(), thread.getId(),
                thread.getState(), System.identityHashCode(thread)));

        StackTraceElement[] trace = traces.get(thread);
        for (StackTraceElement e : trace) {
            System.err.println("        at " + e.toString());
        }/*from   w ww . j av a 2s.  c o m*/
    }
}

From source file:org.rhq.core.pc.util.LoggingThreadFactory.java

/**
 * @see java.util.concurrent.ThreadFactory#newThread(Runnable)
 *///from ww  w.ja v a 2s .c  o m
public Thread newThread(Runnable r) {
    Thread t = new Thread(group, r, poolName + "-" + threadNumber.getAndIncrement());

    t.setDaemon(this.daemon);

    if (t.getPriority() != Thread.NORM_PRIORITY) {
        t.setPriority(Thread.NORM_PRIORITY);
    }

    t.setUncaughtExceptionHandler(this);

    return t;
}