Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to put maximum memory usage limit on each thread in Java?

When we start threads in a Java program, is there any way for us to assign memory limit to each one of them?

I mean we assign something like this for a new Java process:

/usr/java/default/bin/java -Xms512m -Xmx1024m -jar /opt/abc/MyProcessor/MyProcessor.jar

Is there any way we can do similar thing with Java threads?

Basically, each of my threads is going to do some task, and I wish to put some maximum limit on each one's memory usage.

like image 258
Bhushan Avatar asked Jul 06 '11 16:07

Bhushan


1 Answers

Is there any way we can do similar thing with Java threads?

No. Threads in a process are typically meant to access shared main memory within a process (the JVM in this case).

Basically, each of my threads is going to do some task, and I wish to put some maximum limit on each one's memory usage.

You do either:

  • The easy way. Spawn off new JVM processes where you can specify the heap size on each.
  • The hard way (not recommended by me; this is an option that is available). You could approximate the size of the objects that are created in each thread, and halt further execution of the thread if the size of the objects created by a thread exceeds a certain amount. This will require you to encapsulate the new keyword. In simpler words, all objects will have to be instantiated from factories that will keep tab on the approximate memory usage. Do keep in mind that object sizes on the heap are an approximation; Java does not have a sizeof operator. If you need to keep count of objects on the stack, then it is easy to do so, using the -Xss flag passed to the JVM at startup.
like image 190
Vineet Reynolds Avatar answered Oct 11 '22 12:10

Vineet Reynolds