0

I've been pulling my hair out over this. My program is supposed to measure the CPU time in searching a hashtable that uses a simple double hashing algorithm. However, ThreadMXBean keeps returning me -1. Any help is appreciated.

Snippet of "main"

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    //CREATE A THREAD
    DoubleHashThread doubleThread = 
            new DoubleHashThread("doublethread"); //CREATE DOUBLE HASHING THREAD
    doubleThread.setDaemon(true);
    doubleThread.start();

    getCpuTime(doubleThread);
    doubleThread.run(hashTable,data); //RUN SEARCH FUNCTION
    getCpuTime(doubleThread);

GetCpuTime Method

public static long getCpuTime(DoubleHashThread dt)
{
    ThreadMXBean bean = ManagementFactory.getThreadMXBean(); //GET THREAD BEAN
    long cpuTime = 0;

    if (bean.isThreadCpuTimeSupported()) //if grabbing it is supported, continue
    {
        System.out.println("CPU time for " + dt.getId() + " " + dt.getName() + 
                           " is " + bean.getThreadCpuTime(dt.getId()));
    }

    return cpuTime;

}

DoubleHashThread.java

import doubleHash.DoubleHash;
public class DoubleHashThread extends Thread
{
    public DoubleHashThread(String s) 
    {
        this.setName(s);
    }

    //RUNS SEARCH FUNCTION
    public void run(String[] hashTable, String data)
    {
        DoubleHash.searchTable(hashTable,data); //run Double Hash's search
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Cheryl
  • 67
  • 12
  • Your thread is dead by the time you call `getCpuTime` the second time, hence `-1` is returned. Note that your `run` method should not take arguments and if you want your loop to not die it should contain an "infinite" loop. Right now you basically create a thread that dies immediately, then you call the `run` method (which actually executes on the main thread). – Giacomo Alzetta Sep 12 '18 at 10:28
  • "_If the thread of the specified ID is not alive or does not exist, this method returns `-1`._" - Javadoc of [`ThreadMXBean.getThreadCpuTime`](https://docs.oracle.com/javase/10/docs/api/java/lang/management/ThreadMXBean.html#getThreadCpuTime(long)) – Slaw Sep 12 '18 at 10:34
  • Thank you for the replies, apologies if the question seemed ignorant, I had to crash course the topic and didn't have any foundation. – Cheryl Sep 13 '18 at 06:01

0 Answers0