My application is a Java based multi-tenant application. The application processes request of multiple users at the same time. I'm trying to limit the maximum CPU time utilized while executing a piece of code in Java. This is needed to prevent over utilization of resources as it's a multi-tenant environment.
For instance, consider an operation which has a series of tasks. We will enforce a limit that the operation should not consume more than 5 secs CPU time. After every task in the operation, we check the overall CPU utilized. If it crosses the limit, we break the operation.
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import com.sun.management.ThreadMXBean;
public class MeasureCPUTime {
public static void main(String[] args) {
ThreadMXBean threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
long threadId = Thread.currentThread().getId();
long cpuTime = threadMXBean.getThreadCpuTime(threadId);
List<String> stringList = task();
cpuTime = threadMXBean.getThreadCpuTime(threadId) - cpuTime;
System.out.println(cpuTime + " - " + stringList.size());
}
public static List<String> task() {
List<String> stringList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
stringList.add("RANDOM_" + i);
}
stringList.clear();
return stringList;
}
}
Above is a sample code which we tried out. It works good on a single threaded environment. But in a multithreaded environment particularly when there is high GC happening int the background, the results are not accurate. Only with results with high accuracy can be used for applying limitation.
When we explored on the Web, Salesforce has similar limitations enforced under their Apex governor limitations for a apex transaction. Reference. Is there any other ways to measure the CPU time with higher accuracy in JAVA?