Can Java's JConsole be used to automatically configure memory?

会有一股神秘感。 提交于 2019-12-23 08:47:52

问题


I am studying about Java JMX and JConsole. I am curious about the memory management abilities of JConsole. For example, there is a "Perform GC" button in the Memory tab :

Suppose I have simple Java app that eats up memory, something like this :

public class MemoryEater
{
  public static void main(String[] args)
  {
    Vector v = new Vector();
    while (true)
    {
      byte b[] = new byte[1048576];
      v.add(b);
      Runtime rt = Runtime.getRuntime();
      System.out.println( "free memory: " + rt.freeMemory() );
    }
  }
}

Would there be a way to configure JConsole to prevent this app from consuming X amount of memory? Or do I need to make a new MBean via JMX ? thanks


回答1:


Would there be a way to configure JConsole to prevent this app from consuming X amount of memory?

From JConsole we cannot tune/control the memory limits. Only option I see is using -Xmx during startup of java process. Looking at the below screenshot, JConsole exposes memory parameters as only as readable but not writable.


Or do I need to make a new MBean via JMX ?

Even if we write our own MBean I don't think it is possible to change the memory limits of java process at runtime. The only way is to configure the memory limits during the start up using -Xms and -Xmx.

Unless the question is specific to your example code, where in you want to limit the number of elements that can be added to the Vector through JMX Bean and there by limiting the memory consumption, which is do-able, but I doubt if that is what you are looking for.




回答2:


No, you can't. Java memory management is a responsibility of garbage collector and actual software developers. You can tweak memory allocation with different reference types (like Soft references), tune GC parameters and algorithm or try to force GC invocation with JMX or jcmd GC.run utility command. But you can't alter memory boundaries for running JVM or set high-water-mark for a heap occupancy.

If you need another strategy for memory management in Java take a look at products like Terracotta BigMemory.




回答3:


you can only add MBean functions and call on them from JConsole - under operations.

public void add(){
   byte b[] = new byte[1048576];
   v.add(b);
   Runtime rt = Runtime.getRuntime();
   System.out.println( "free memory: " + rt.freeMemory() );
}

see here https://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html



来源:https://stackoverflow.com/questions/35713157/can-javas-jconsole-be-used-to-automatically-configure-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!