Example usage for java.lang Thread getId

List of usage examples for java.lang Thread getId

Introduction

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

Prototype

public long getId() 

Source Link

Document

Returns the identifier of this Thread.

Usage

From source file:org.apache.ambari.server.testing.DeadlockWarningThread.java

@Override
public void run() {
    while (true) {
        try {//from  w  ww . ja va 2  s  . c  o  m
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
        }
        long[] ids = mbean.findMonitorDeadlockedThreads();
        StringBuilder errBuilder = new StringBuilder();
        if (ids != null && ids.length > 0) {
            errBuilder.append(getThreadsStacktraces(Arrays.asList(ArrayUtils.toObject(ids))));
            errorMessages.add(errBuilder.toString());
            System.out.append(errBuilder.toString());
            //Exit if deadlocks have been found         
            deadlocked = true;
            break;
        } else {
            //Exit if all monitored threads were finished
            boolean hasLive = false;
            boolean hasRunning = false;
            for (Thread monTh : monitoredThreads) {
                State state = monTh.getState();
                if (state != State.TERMINATED && state != State.NEW) {
                    hasLive = true;
                }
                if (state == State.RUNNABLE || state == State.TIMED_WAITING) {
                    hasRunning = true;
                    break;
                }
            }

            if (!hasLive) {
                deadlocked = false;
                break;
            } else if (!hasRunning) {
                List<Long> tIds = new ArrayList<Long>();
                for (Thread monitoredThread : monitoredThreads) {
                    State state = monitoredThread.getState();
                    if (state == State.WAITING || state == State.BLOCKED) {
                        tIds.add(monitoredThread.getId());
                    }
                }
                errBuilder.append(getThreadsStacktraces(tIds));
                errorMessages.add(errBuilder.toString());
                deadlocked = true;
                break;
            }
        }
    }
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void cpuUsageRoughlyAdheredTo_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();

    float expectedCpuUsage = MAX_USAGE;

    BatchCpuThrottlingExecutor e = getExecutor(1, expectedCpuUsage, factory);

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);// w ww . jav  a2 s. co  m
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("Singlethreaded overall usage: " + actualUsage);

    //this CPU throttling stuff might not be too precise, so let's fail only on huge difference.
    float min = expectedCpuUsage * .5f;
    float max = expectedCpuUsage * 1.5f;

    Assert.assertTrue(min < actualUsage && actualUsage < max, "Actual CPU usage out of expected range: (" + min
            + ", " + expectedCpuUsage + ", " + max + ") != " + actualUsage);
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void cpuUsageRoughlyAdheredTo_MultiThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();

    float expectedCpuUsage = MAX_USAGE;

    BatchCpuThrottlingExecutor e = getExecutor(10, expectedCpuUsage, factory);

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);/*from   w w w  .  j  a  v  a 2s. c o m*/
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("Multithreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("Multithreaded overall usage: " + actualUsage);

    //this CPU throttling stuff might not be too precise, so let's fail only on huge difference.
    float min = expectedCpuUsage * .5f;
    float max = expectedCpuUsage * 1.5f;

    Assert.assertTrue(min < actualUsage && actualUsage < max, "Actual CPU usage out of expected range: (" + min
            + ", " + expectedCpuUsage + ", " + max + ") != " + actualUsage);
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * releases read lock/* w ww.j ava 2 s.c  o  m*/
 */
public void releaseReadLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Releasing read lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    lock.readLock().unlock();

    if (readWriteLockMonitorEnabled) {
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        lockTypeLongMap.remove(LockType.Read);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Read lock released: [lock-name] %s [thread-id] %d [thread-name] %s", getName(),
                currentThread.getId(), currentThread.getName()));
    }
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * acquires read lock/*from   w  w  w .  j  a  va 2s .  co  m*/
 */
public void acquireReadLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Acquiring read lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    lock.readLock().lock();

    if (readWriteLockMonitorEnabled) {
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        LockMetadata lockMetadata = new LockMetadata(getName(), LockType.Read, currentThread.getId(),
                currentThread.getName(), currentThread.getStackTrace(), System.currentTimeMillis());
        lockTypeLongMap.put(lockMetadata.getLockType(), lockMetadata);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Read lock acquired: [lock-name] %s [thread-id] %d [thread-name] %s", getName(),
                currentThread.getId(), currentThread.getName()));
    }
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * releases write lock//  w w  w  . j  a  v  a  2  s.c o  m
 */
public void releaseWriteLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Releasing write lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    if (lock.writeLock().isHeldByCurrentThread()) {
        lock.writeLock().unlock();

        if (readWriteLockMonitorEnabled) {
            Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
            lockTypeLongMap.remove(LockType.Write);
        }

        if (log.isDebugEnabled()) {
            log.debug(String.format("Write lock released: [lock-name] %s [thread-id] %d [thread-name] %s",
                    getName(), currentThread.getId(), currentThread.getName()));
        }
    } else {
        log.warn(String.format(
                "System warning! Trying to release a lock which has not been taken by the same thread: "
                        + "[lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }
}

From source file:com.urremote.classifier.common.ExceptionHandler.java

public void uncaughtException(Thread t, Throwable e) {
    String timestamp = String.valueOf(System.currentTimeMillis());
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    printWriter.println("Exception Thrown By Thread:" + t.getId() + " '" + t.getName() + "'");
    e.printStackTrace(printWriter);/*from  w  ww. j av a 2  s .c o m*/
    String stacktrace = result.toString();
    printWriter.close();
    String filename = timestamp + ".stacktrace";
    writeToFile(stacktrace, filename);

    FlurryAgent.onError(e.getMessage(), stacktrace, e.getClass().getCanonicalName());
    //sendToServer(stacktrace, filename);

    defaultUEH.uncaughtException(t, e);
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * acquires write lock//from  www  . j  av  a  2 s. c om
 */
public void acquireWriteLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Acquiring write lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    if (readWriteLockMonitorEnabled) {
        // Check whether the thread has already taken a read lock before requesting a write lock
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        if (lockTypeLongMap.containsKey(LockType.Read)) {
            String message = String.format(
                    "System error, cannot acquire a write lock while having a "
                            + "read lock on the same thread: [lock-name] %s [thread-id] %d [thread-name] %s",
                    getName(), currentThread.getId(), currentThread.getName());
            InvalidLockRequestedException exception = new InvalidLockRequestedException(message);
            log.error(exception);
            throw exception;
        }
    }

    lock.writeLock().lock();

    if (readWriteLockMonitorEnabled) {
        LockMetadata lockMetadata = new LockMetadata(getName(), LockType.Write, currentThread.getId(),
                currentThread.getName(), currentThread.getStackTrace(), System.currentTimeMillis());
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        lockTypeLongMap.put(lockMetadata.getLockType(), lockMetadata);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Write lock acquired: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }
}

From source file:de.slub.elasticsearch.river.fedora.FedoraRiver.java

private void safeStart(Thread thread) {
    if (thread != null && thread.getState().equals(Thread.State.NEW)) {
        thread.start();/*ww w .j  a  va  2s  . c  om*/
        logger.info("Started thread: [{}] {}", thread.getId(), thread.getName());
    }
}

From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java

public void printActiveThreads() {
    System.out.println("=========================================");
    System.out.println("Thread.activeCount() = " + Thread.activeCount());

    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    Set<String> groups = allStackTraces.keySet().stream()
            .filter(t -> t.getThreadGroup() == null || !t.getThreadGroup().getName().equals("system"))
            .map(t -> String.valueOf(t.getThreadGroup())).collect(Collectors.toSet());

    for (String group : groups) {
        System.out.println("group = " + group);
        for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
            Thread thread = entry.getKey();
            if (String.valueOf(thread.getThreadGroup()).equals(group)) {
                System.out.println("\t[" + thread.getId() + "] " + thread.toString() + ":" + thread.getState());
            }/*from   w  w w. j  a va  2s. c  o m*/
        }
    }
    System.out.println("=========================================");
}