title: Throttling CPU/Memory usage of a Thread in Java?
body: <p>I'm writing an application that will have multiple threads running, and want to throttle the CPU/memory usage of those threads.</p>
  
  <p>There is a <a href="https://stackoverflow.com/questions/1982/cpu-throttling-in-c">similar question for C++</a>, but I want to try and avoid using C++ and JNI if possible.  I realize this might not be possible using a higher level language, but I'm curious to see if anyone has any ideas.</p>
  
  <p><strong>EDIT:</strong> Added a bounty; I'd like some really good, well thought out ideas on this.</p>
  
  <p><strong>EDIT 2:</strong> The situation I need this for is executing other people's code on my server.    Basically it is completely arbitrary code, with the only guarantee being that there will be a main method on the class file.  Currently, multiple completely disparate classes, which are loaded in at runtime, are executing concurrently as separate threads.</p>
  
  <p>The way it's written, it would be a pain to refactor to create separate processes for each class that gets executed.  If that's the only good way to limit memory usage via the VM arguments, then so be it.  But I'd like to know if there's a way to do it with threads.  Even as a separate process, I'd like to be able to somehow limit its CPU usage, since as I mentioned earlier, several of these will be executing at once.  I don't want an infinite loop to hog up all the resources.</p>
  
  <p><strong>EDIT 3:</strong> An easy way to approximate object size is with java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/Instrumentation.html" rel="noreferrer">Instrumentation</a> classes; specifically, the getObjectSize method.  Note that there is some special setup needed to use this tool.</p>