`Monitor cpu usage per thread in java?

后端 未结 6 2064
日久生厌
日久生厌 2020-12-07 21:15

I would like to ask whether there is some simple way to determine cpu usage per thread in java. Thanks

6条回答
  •  旧时难觅i
    2020-12-07 21:36

    Option_1: Code level

    In your business logic code; in the beginning call start() API and in the finally block call stop(). So that you will get CPU time for executing your logic by the current running thread. Then log it. Reference.

    class CPUTimer 
    {
        private long _startTime = 0l;
    
        public void start ()
        {
            _startTime = getCpuTimeInMillis();
        }
    
    
        public long stop ()
        {
            long result = (getCpuTimeInMillis() - _startTime);
            _startTime = 0l;
            return result;
        }
    
        public boolean isRunning ()
        {
            return _startTime != 0l;
        }
    
        /** thread CPU time in milliseconds. */
        private long getCpuTimeInMillis ()
        {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime()/1000000: 0L;
        }
    }
    

    Option_2: Monitor level using plugins (AIX IBM box which don't have jvisualvm support)

    If you think it is delay in adding code now, then you can prefer JConsole with plugins support. I followed this article. Download the topthreads jar from that article and run ./jconsole -pluginpath topthreads-1.1.jar

    Option_3: Monitor level using TOP (shift H) + JSTACK (Unix machine which has 'Shif+H' support)

    Follow this tutorial, where top command will give option to find top CPU thread (nid). Take that check that nid in jstack output file.

提交回复
热议问题