有没有办法在Java中为每个线程设置最大内存使用限制? [英] Is there a way to put maximum memory usage limit on each thread in Java?

查看:476
本文介绍了有没有办法在Java中为每个线程设置最大内存使用限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在 Java 程序中启动线程时,我们有什么方法可以为每个线程分配内存限制吗?

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

我的意思是我们为新的 Java 过程分配这样的东西:

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

我们有什么方法可以用Java线程做类似的事情吗?

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.

推荐答案


有没有我们可以用Java线程做类似的事情吗?

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

没有。进程中的线程通常用于访问进程内的共享主内存(在本例中为JVM)。

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.

你可以:


  • 简单方法。产生新的JVM进程,您可以在其中指定每个进程的堆大小。

  • 困难的方式(我不推荐;这是一个可用的选项)。您可以近似在每个线程中创建的对象的大小,并且如果线程创建的对象的大小超过特定量,则停止进一步执行线程。这将要求您封装 new 关键字。简单来说,所有对象都必须从工厂实例化,这些工具将保留近似内存使用情况的选项卡。请记住,堆上的对象大小是近似值; Java没有 sizeof 运算符。如果你需要在堆栈上保留对象的数量,那么很容易这样做,使用在启动时传递给JVM的 -Xss 标志。

  • 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.

这篇关于有没有办法在Java中为每个线程设置最大内存使用限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆