Example usage for java.lang.management ManagementFactory getThreadMXBean

List of usage examples for java.lang.management ManagementFactory getThreadMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getThreadMXBean.

Prototype

public static ThreadMXBean getThreadMXBean() 

Source Link

Document

Returns the managed bean for the thread system of the Java virtual machine.

Usage

From source file:eu.planets_project.tb.gui.backing.exp.ExpTypeMigrate.java

public static void main(String args[]) {

    Properties p = System.getProperties();

    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {//from  w w  w .  j  a va  2 s.  c  om
        p.storeToXML(byos, "Automatically generated for PLANETS Service ", "UTF-8");
        String res = byos.toString("UTF-8");
        System.out.println(res);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // This.
    List<String> pl = new ArrayList<String>();
    for (Object key : p.keySet()) {
        pl.add((String) key);
    }
    Collections.sort(pl);

    //
    for (String key : pl) {
        System.out.println(key + " = " + p.getProperty(key));
    }

    /*
     * http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html#getCurrentThreadCpuTime()
     * 
     * http://www.java-forums.org/new-java/5303-how-determine-cpu-usage-using-java.html
     * 
     */

    ThreadMXBean TMB = ManagementFactory.getThreadMXBean();
    int mscale = 1000000;
    long time = 0, time2 = 0;
    long cput = 0, cput2 = 0;
    double cpuperc = -1;

    //Begin loop.
    for (int i = 0; i < 10; i++) {

        if (TMB.isThreadCpuTimeSupported()) {
            if (!TMB.isThreadCpuTimeEnabled()) {
                TMB.setThreadCpuTimeEnabled(true);
            }

            //                if(new Date().getTime() * mscale - time > 1000000000) //Reset once per second
            //                {
            System.out.println("Resetting...");
            time = System.currentTimeMillis() * mscale;
            cput = TMB.getCurrentThreadCpuTime();
            //                cput = TMB.getCurrentThreadUserTime();
            //                }

        }

        //Do cpu intensive stuff
        for (int k = 0; k < 10; k++) {
            for (int j = 0; j < 100000; j++) {
                double a = Math.pow(i, j);
                double b = a / j + Math.random();
                a = b * Math.random();
                b = a * Math.random();
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        if (TMB.isThreadCpuTimeSupported()) {
            //                if(new Date().getTime() * mscale - time != 0) {
            cput2 = TMB.getCurrentThreadCpuTime();
            System.out.println("cpu: " + (cput2 - cput) / (1000.0 * mscale));
            //                cput2 = TMB.getCurrentThreadUserTime();

            time2 = System.currentTimeMillis() * mscale;
            System.out.println("time: " + (time2 - time) / (1000.0 * mscale));

            cpuperc = 100.0 * (cput2 - cput) / (double) (time2 - time);
            System.out.println("cpu perc = " + cpuperc);
            //                }
        }
        //End Loop
    }
    System.out.println("Done.");
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void measureTimes(ArrayList<Runnable> profilingQueue) {
    try {/* ww  w .j a v  a 2 s . c  o m*/
        this.element = new TimeElement("");

        // get the MXBean
        final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

        // wait till the warm up period is over
        while (!this.running) {
            try {
                Thread.sleep(1);
            } catch (final InterruptedException e) {
            }
        }

        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
        }

        // initialize the start times of the threads
        for (int i = 0; i < this.threadIds.length; i++) {
            this.currentThreadTimes[i] = mxBean.getThreadCpuTime(this.threadIds[i]);
        }

        BenchmarkTest.LOG.info("Sampling interval: {0} millisec(s)", BenchmarkTest.SAMPLING_INT);

        long lastTime = System.currentTimeMillis();

        // profile until the benchmark is over
        while (BenchmarkTest.this.running) {
            try {
                final long now = System.currentTimeMillis();
                final long diff = Math.abs(now - lastTime);
                if (diff > BenchmarkTest.SAMPLING_INT) {
                    this.measureTimes(mxBean, profilingQueue);

                    lastTime = now;
                } else {
                    Thread.sleep(1);
                }
            } catch (final InterruptedException e) {
            }
        }

        this.samplingFinished = true;
    } catch (final Exception e) {
        BenchmarkTest.LOG.fatal(e, "");
    }
}

From source file:com.eurelis.opencms.admin.systeminformation.CmsCPUThreadsClassesOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *///from   ww w .j a  v  a2  s.c om
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    setCpuCount("" + osBean.getAvailableProcessors());
    double usage = com.eurelis.opencms.admin.systeminformation.CmsCPUThreadsClassesOverviewDialog
            .getCPUUsage(getSession());
    usage = Math.round(usage * 100) / 100;
    setCpuUsage("" + 100 * usage + "%");

    setLoadedClassesCount("" + classesBean.getLoadedClassCount());
    setUnloadedClassesCount("" + classesBean.getUnloadedClassCount());
    setTotalLoadedClassesCount("" + classesBean.getTotalLoadedClassCount());

    setThreadsCount("" + threadBean.getThreadCount());
    setThreadsStartedCount("" + threadBean.getTotalStartedThreadCount());
    setThreadsPeakCount("" + threadBean.getPeakThreadCount());
    setThreadsDaemonCount("" + threadBean.getDaemonThreadCount());

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

    setParamCloseLink(getJsp().link(
            "/system/workplace/views/admin/admin-main.jsp?path=/eurelis_system_information/cpu_and_threads.jsp"));

}

From source file:jenkins.metrics.api.MetricsRootAction.java

/**
 * Binds the thread dump to the CORS aware URL {@code /metrics/threads} where the metrics access key is
 * provided in the form field {@code key} or an {@code Authorization: Jenkins-Metrics-Key {key}} header
 *
 * @param req the request// w w w . ja v  a 2s  .c om
 * @param key the key from the form field.
 * @return the {@link HttpResponse}
 * @throws IllegalAccessException if the access attempt is invalid.
 */
@SuppressWarnings("unused") // stapler binding
@Restricted(NoExternalUse.class) // stapler binding
@RequirePOST
public HttpResponse doThreads(StaplerRequest req, @QueryParameter("key") String key)
        throws IllegalAccessException {
    requireCorrectMethod(req);
    if (StringUtils.isBlank(key)) {
        key = getKeyFromAuthorizationHeader(req);
    }
    Metrics.checkAccessKeyThreadDump(key);
    return Metrics.cors(key, new ThreadDumpResponse(new ThreadDump(ManagementFactory.getThreadMXBean())));
}

From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java

/**
 * Process 'getstacktraces' request//from  www  . j  ava  2 s  . co m
 *
 * Response parameters:
 *   locks   - An array of lock objects for locks with waiters
 *   threads - An array of thread objects
 *
 * Lock object:
 *   name   - Lock class name
 *   hash   - Lock identity hash code
 *   thread - Identifier of thread holding the lock
 *
 * Monitor object:
 *   name    - Monitor class name
 *   hash    - Monitor identity hash
 *   depth   - Stack depth where monitor locked
 *   trace   - Stack element where monitor locked
 *
 * Thread object:
 *   blocked - Lock object if thread is waiting on a lock
 *   id      - Thread identifier
 *   locks   - Array of monitor objects for locks held by this thread
 *   name    - Thread name
 *   state   - Thread state
 *   trace   - Array of stack trace elements
 *
 * @return                              Response as a JSONObject
 */
private JSONObject getStackTraces() {
    JSONArray threadsJSON = new JSONArray();
    JSONArray locksJSON = new JSONArray();
    ThreadMXBean tmxBean = ManagementFactory.getThreadMXBean();
    boolean tmxMI = tmxBean.isObjectMonitorUsageSupported();
    ThreadInfo[] tList = tmxBean.dumpAllThreads(tmxMI, false);
    //
    // Generate the response
    //
    for (ThreadInfo tInfo : tList) {
        JSONObject threadJSON = new JSONObject();
        //
        // General thread information
        //
        threadJSON.put("id", tInfo.getThreadId());
        threadJSON.put("name", tInfo.getThreadName());
        threadJSON.put("state", tInfo.getThreadState().toString());
        //
        // Gather lock usage
        //
        if (tmxMI) {
            MonitorInfo[] mList = tInfo.getLockedMonitors();
            if (mList.length > 0) {
                JSONArray monitorsJSON = new JSONArray();
                for (MonitorInfo mInfo : mList) {
                    JSONObject lockJSON = new JSONObject();
                    lockJSON.put("name", mInfo.getClassName());
                    lockJSON.put("hash", mInfo.getIdentityHashCode());
                    lockJSON.put("depth", mInfo.getLockedStackDepth());
                    lockJSON.put("trace", mInfo.getLockedStackFrame().toString());
                    monitorsJSON.add(lockJSON);
                }
                threadJSON.put("locks", monitorsJSON);
            }
            if (tInfo.getThreadState() == Thread.State.BLOCKED) {
                LockInfo lInfo = tInfo.getLockInfo();
                if (lInfo != null) {
                    JSONObject lockJSON = new JSONObject();
                    lockJSON.put("name", lInfo.getClassName());
                    lockJSON.put("hash", lInfo.getIdentityHashCode());
                    lockJSON.put("thread", tInfo.getLockOwnerId());
                    threadJSON.put("blocked", lockJSON);
                    boolean addLock = true;
                    for (Object lock : locksJSON) {
                        if (((String) ((JSONObject) lock).get("name")).equals(lInfo.getClassName())) {
                            addLock = false;
                            break;
                        }
                    }
                    if (addLock)
                        locksJSON.add(lockJSON);
                }
            }
        }
        //
        // Add the stack trace
        //
        StackTraceElement[] elements = tInfo.getStackTrace();
        JSONArray traceJSON = new JSONArray();
        for (StackTraceElement element : elements)
            traceJSON.add(element.toString());
        threadJSON.put("trace", traceJSON);
        //
        // Add the thread to the response
        //
        threadsJSON.add(threadJSON);
    }
    //
    // Return the response
    //
    JSONObject response = new JSONObject();
    response.put("threads", threadsJSON);
    response.put("locks", locksJSON);
    return response;
}

From source file:logdruid.util.DataMiner.java

public static FileMineResult fileMine(FileRecord fileRecord, Repository repo, Source source, boolean stats,
        boolean timings) {
    ExtendedTimeSeries ts = null;/*from  w  ww . jav  a 2 s  .  c o  m*/
    PatternCache patternCache = new PatternCache();
    Date startDate = null;
    Date endDate = null;

    DecimalFormat decimalFormat = new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US));

    FastDateFormat fastDateFormat = null;
    FileReader flstr = null;
    BufferedReader buf1st;
    Matcher matcher;
    Matcher matcher2;
    FixedMillisecond fMS = null;
    Boolean successMatch = false;
    DateFormat df = null;
    int statHit = 0;
    int statMatch = 0;
    int eventHit = 0;
    int eventMatch = 0;
    long[] arrayBefore;
    Map<Recording, String> recMatch = new HashMap<Recording, String>();
    Map<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();
    Map<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();
    Map<String, long[]> matchTimings = new HashMap<String, long[]>();

    long recordingMatchStart = 0;
    long recordingMatchEnd = 0;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("++file: " + repo.getBaseSourcePath() + " + "
                    + (String) fileRecord.getCompletePath().toString());
        }
        flstr = new FileReader(fileRecord.getCompletePath());
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    buf1st = new BufferedReader(flstr);
    String line;
    try {
        recMatch = getRegexp(repo, source);
        int lineCount = 1;
        while ((line = buf1st.readLine()) != null) {
            // check against one Recording pattern at a tim
            // if (logger.isDebugEnabled()) {
            // logger.debug("line " + line);
            // }
            Iterator recMatchIte = recMatch.entrySet().iterator();
            while (recMatchIte.hasNext()) {
                if (timings) {
                    recordingMatchStart = ManagementFactory.getThreadMXBean()
                            .getThreadCpuTime(Thread.currentThread().getId());
                }
                Map.Entry me = (Map.Entry) recMatchIte.next();
                Recording rec = (Recording) me.getKey();
                matcher = patternCache.getPattern((String) (rec.getRegexp())).matcher(line);
                if (matcher.find()) {
                    Boolean isStatRecording = rec.getClass().equals(StatRecording.class);
                    if (stats) {
                        if (isStatRecording) {
                            statMatch++;
                        } else {
                            eventMatch++;
                        }
                    }
                    // logger.info("1**** matched: " + line);
                    ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();
                    int cnt = 0;
                    matcher2 = patternCache.getPattern((String) me.getValue()).matcher(line);
                    successMatch = false;
                    if (matcher2.find()) {
                        if (stats) {
                            if (isStatRecording) {
                                statHit++;
                            } else {
                                eventHit++;
                            }
                        }
                        int count = 1;
                        Date date1 = null;

                        // handling capture for each recording item
                        Iterator<RecordingItem> recItemIte2 = recordingItem.iterator();
                        while (recItemIte2.hasNext()) {
                            RecordingItem recItem2 = recItemIte2.next();
                            // logger.info("3A**** " +
                            // recItem2.getType());
                            if (recItem2.getType().equals("date")) {
                                try {
                                    df = repo.getDateFormat(rec.getDateFormatID());
                                    if (logger.isDebugEnabled())
                                        logger.debug("4**** rec name" + rec.getName() + " df: " + df.getId());
                                    fastDateFormat = FastDateFormat.getInstance(df.getDateFormat());
                                    date1 = fastDateFormat.parse(matcher2.group(count));
                                    if (logger.isDebugEnabled())
                                        logger.debug(
                                                "4b**** " + df.getDateFormat() + " date: " + date1.toString());
                                    // logger.info("4**** " +
                                    // date1.toString());
                                } catch (ParseException e) {
                                    // TODO Auto-generated catch
                                    // block
                                    e.printStackTrace();
                                }
                            } else if (date1 != null) {
                                if (recItem2.isSelected()) {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("FileRecord: " + fileRecord.getFile().getName()
                                                + ", Source: " + source.getSourceName() + ", "
                                                + recItem2.getName() + ", " + fileRecord.getFile().getName()
                                                + ", " + lineCount);
                                    }
                                    // recording line of match in file in map RIFileLineDateMap - note the FileLine object use an int to identify the files to save memory 
                                    Map<Date, FileLine> dateFileLineMap = null;
                                    if (RIFileLineDateMap.containsKey(recItem2.getName())) {
                                        dateFileLineMap = RIFileLineDateMap.get(recItem2.getName());
                                    } else {
                                        dateFileLineMap = new HashMap<Date, FileLine>();
                                    }
                                    dateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));
                                    if (logger.isDebugEnabled()) {
                                        logger.debug(fileRecord.getFile().getName() + " dateFileLineMap put: "
                                                + date1 + "fileLine: "
                                                + new FileLine(fileRecord.getId(), lineCount));
                                        logger.debug(fileRecord.getFile().getName() + " FileRecord: "
                                                + fileRecord.getFile().getName() + ", RIFileLineDateMap.put: "
                                                + recItem2.getName() + ", line: " + lineCount
                                                + " RIFileLineDateMap size: " + RIFileLineDateMap.size()
                                                + " dateFileLineMap size: " + dateFileLineMap.size());
                                    }
                                    RIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);

                                    if (startDate == null) {
                                        startDate = date1;
                                    }
                                    if (endDate == null) {
                                        endDate = date1;
                                    }
                                    if (date1.after(startDate)) {
                                        endDate = date1;
                                    } else if (date1.before(startDate)) {
                                        startDate = date1;
                                    }

                                    if (isStatRecording) {
                                        if (statMap.containsKey(recItem2.getName())) {
                                            ts = statMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);
                                        if (matcher2.group(count) == null) {
                                            logger.info("null in match on " + recItem2.getName() + " at "
                                                    + fileRecord.getFile().getName() + " line cnt:"
                                                    + lineCount);
                                            logger.info("line : " + line);
                                        }
                                        try {

                                            if (recItem2.getType().equals("long")) {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Long.valueOf((String) matcher2.group(count)))));
                                            } else {
                                                ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS,
                                                        Double.parseDouble(String.valueOf(decimalFormat
                                                                .parse((String) matcher2.group(count)))))));
                                            }
                                        } catch (ParseException e) {
                                            // TODO Auto-generated catch
                                            // block
                                            e.printStackTrace();
                                        }
                                        if (stats) {
                                            //int[] array = { statMatch, statHit };
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }

                                        statMap.put(recItem2.getName(), ts);
                                        // performance: add the
                                        // TmeSeriesDataItem to the
                                        // TimeSeries instead of updating
                                        // the TimeSeries in the Map

                                    } else { // rec.getClass().equals(EventRecording.class)
                                        if (eventMap.containsKey(recItem2.getName())) {
                                            ts = eventMap.get(recItem2.getName());
                                        } else {
                                            ts = new ExtendedTimeSeries(recItem2.getName(),
                                                    FixedMillisecond.class);
                                            if (logger.isDebugEnabled())
                                                logger.debug(
                                                        "5**** Adding record to Map: " + recItem2.getName());
                                        }
                                        fMS = new FixedMillisecond(date1);

                                        if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("occurrences")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                ts.getTimeSeries()
                                                        .addOrUpdate((new TimeSeriesDataItem(fMS, 101))); // +
                                                // (double)t.getValue()
                                                // need some way to show several occurrences
                                            } else {
                                                ts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 100)));
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("sum")) {
                                            TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);
                                            if (t != null) {
                                                if (!recItem2.getType().equals("date")) {
                                                    try {
                                                        ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(
                                                                fMS,
                                                                Double.parseDouble(String
                                                                        .valueOf(decimalFormat
                                                                                .parse(matcher2.group(count)))
                                                                        + ts.getTimeSeries().getDataItem(fMS)
                                                                                .getValue()))));
                                                        logger.info(
                                                                ts.getTimeSeries().getDataItem(fMS).getValue());
                                                    } catch (ParseException e) {
                                                        // TODO
                                                        // Auto-generated
                                                        // catch block
                                                        e.printStackTrace();
                                                    }
                                                }
                                            } else {
                                                try {
                                                    ts.getTimeSeries()
                                                            .add((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }

                                        } else if (((RecordingItem) recItem2).getProcessingType()
                                                .equals("capture")) {

                                        } else {
                                            if (!recItem2.getType().equals("date")) {
                                                try {
                                                    ts.getTimeSeries()
                                                            .addOrUpdate((new TimeSeriesDataItem(fMS, Double
                                                                    .parseDouble(String.valueOf(decimalFormat
                                                                            .parse(matcher2.group(count)))))));
                                                } catch (ParseException e) {
                                                    // TODO Auto-generated
                                                    // catch block
                                                    e.printStackTrace();
                                                }
                                            }
                                            // ts.addOrUpdate((new
                                            // TimeSeriesDataItem(fMS,
                                            // 100)));
                                        }
                                        // logger.debug(recItem2.getName() +
                                        // " " +
                                        // Double.parseDouble((matcher2.group(count))));
                                        if (stats) {
                                            int[] array = ts.getStat();
                                            array[1] = array[1] + 1;
                                            array[0] = array[0] + 1;
                                            ts.setStat(array);
                                            if (logger.isDebugEnabled())
                                                logger.debug("stats " + array[0] + " " + array[1]);
                                        }
                                        eventMap.put(recItem2.getName(), ts);

                                    }
                                }
                            }
                            count++;
                            // logger.info("event statistics: "+eventMatch +
                            // " and " +eventHit +
                            // " ; stat statistics: "+statMatch + " and "
                            // +statHit);
                        }
                    }
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // logger.info(file.getName() + " contains " +
                            // arrayBefore);
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts

                            long[] array = { arrayBefore[0] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[1], arrayBefore[2] + 1, arrayBefore[3] + 1 };
                            // logger.info(file.getName() +
                            // " add success to" + rec.getName() + " 0: "+
                            // array[0] + " 1: "+ array[1]+ " 2: "+ array[2]
                            // +" 3: "+ array[3]);
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };
                            matchTimings.put(rec.getName(), array);
                            // logger.info(file.getName() + " first success"
                            // + rec.getName() + " 0: "+ array[0] + " 1: "+
                            // array[1]+ " 2: "+ array[2] +" 3: "+
                            // array[3]);
                        }
                    }
                } else {
                    if (timings) {
                        recordingMatchEnd = ManagementFactory.getThreadMXBean()
                                .getThreadCpuTime(Thread.currentThread().getId());
                        if (matchTimings.containsKey(rec.getName())) {
                            arrayBefore = matchTimings.get(rec.getName());
                            // 0-> sum of time for success matching of given
                            // recording ; 1-> sum of time for failed
                            // matching ; 2-> count of match attempts,
                            // 3->count of success attempts
                            long[] array = { arrayBefore[0],
                                    arrayBefore[1] + recordingMatchEnd - recordingMatchStart,
                                    arrayBefore[2] + 1, arrayBefore[3] };
                            matchTimings.put(rec.getName(), array);
                        } else {
                            long[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };
                            matchTimings.put(rec.getName(), array);
                        }
                    }
                }

            }
            lineCount++;

            // timing
        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            buf1st.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * if (logger.isInfoEnabled()) { Iterator Ite =
     * matchTimings.entrySet().iterator(); long successTotalTime=0; long
     * failedTotalTime=0; // 0-> sum of time for success matching of given
     * // recording ; 1-> sum of time for failed // matching ; 2-> count of
     * match attempts, // 3->count of success attempts // long[] array;
     * while (Ite.hasNext()) { Map.Entry pairs = (Map.Entry) Ite.next();
     * long[] array = (long[]) pairs.getValue(); logger.info(file.getName()
     * + " - "+ pairs.getKey() + " / success all time: " + array[0] +
     * " failed all time: " + array[1] + " attempt count: " + array[2] +
     * " success count: " + array[3] + " failed count:"
     * +(array[2]-array[3])); successTotalTime=successTotalTime+array[0];
     * failedTotalTime=failedTotalTime+array[1]; } logger.info("success: "
     * +successTotalTime + " failed: " + failedTotalTime); Ite =
     * matchTimings.entrySet().iterator(); while (Ite.hasNext()) { Map.Entry
     * pairs = (Map.Entry) Ite.next(); long[] array = (long[])
     * pairs.getValue(); logger.info(file.getName() + " percents - "+
     * pairs.getKey() + " / % success time: " + (( successTotalTime!=0) ?
     * ((double)((double)array[0] / successTotalTime)*100) : 0 ) +
     * " % failed time: " + (( failedTotalTime!=0) ?((double)array[1]/
     * failedTotalTime)*100 :0) + " attempt cost: " + ((array[2]!=0) ?
     * ((double)successTotalTime + failedTotalTime ) /array[2]:0 )+
     * " success cost: " + ((array[3]!=0) ? ((double)successTotalTime )
     * /array[3] : 0) + " failed cost:" + ((array[2]-array[3]!=0) ?
     * ((double)failedTotalTime/(array[2]-array[3])) : 0) ); } }
     */
    return new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate,
            endDate);
}

From source file:org.apache.hadoop.test.GenericTestUtils.java

/**
 * Determine if there are any threads whose name matches the regex.
 * @param pattern a Pattern object used to match thread names
 * @return true if there is any thread that matches the pattern
 *//*from  w  w  w. ja v a 2s  .  c  om*/
public static boolean anyThreadMatching(Pattern pattern) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
    for (ThreadInfo info : infos) {
        if (info == null)
            continue;
        if (pattern.matcher(info.getThreadName()).matches()) {
            return true;
        }
    }
    return false;
}

From source file:org.jahia.tools.jvm.ThreadMonitor.java

/**
 * reset mbean server connection/*  ww  w .  jav a2s. co m*/
 * 
 * @param mbs
 */
void setMBeanServerConnection(MBeanServerConnection mbs) {
    this.tmbean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
}

From source file:rpc.TestRPC.java

/**
 * Count the number of threads that have a stack frame containing the given
 * string//from  w  w w  . j a v a  2 s  .  c  om
 */
private static int countThreads(String search) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    int count = 0;
    ThreadInfo[] infos = threadBean.getThreadInfo(threadBean.getAllThreadIds(), 20);
    for (ThreadInfo info : infos) {
        if (info == null)
            continue;
        for (StackTraceElement elem : info.getStackTrace()) {
            if (elem.getClassName().contains(search)) {
                count++;
                break;
            }
        }
    }
    return count;
}

From source file:com.eurelis.opencms.admin.systeminformation.CmsMemoryOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *//*  ww  w .j ava2s.c o  m*/
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    for (java.lang.management.MemoryPoolMXBean item : ManagementFactory.getMemoryPoolMXBeans()) {
        java.lang.management.MemoryUsage mu = item.getUsage();
        String name = item.getName();

        if (name.toLowerCase().contains("perm")) {
            setMemPermMax("" + mu.getMax());
            setMemPermTotal("" + mu.getCommitted());
            setMemPermUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("old")) {
            setMemOldMax("" + mu.getMax());
            setMemOldTotal("" + mu.getCommitted());
            setMemOldUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("eden")) {
            setMemEdenMax("" + mu.getMax());
            setMemEdenTotal("" + mu.getCommitted());
            setMemEdenUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("survivor")) {
            setMemSurvivorMax("" + mu.getMax());
            setMemSurvivorTotal("" + mu.getCommitted());
            setMemSurvivorUsed("" + mu.getUsed());
        } else {
            //LOG.debug("MemoryPoolMXBean name = " + name.toLowerCase());
        }
    }

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

    setParamCloseLink(getJsp()
            .link("/system/workplace/views/admin/admin-main.jsp?path=/eurelis_system_information/memory.jsp"));
}