在JAR中设置VM选项(-Xmx)[JVM启动参数]

时间:2014-04-09 15:34:06

标签: java jar jvm

我搜索了这个问题并在stackoverflow本身上获得了很多匹配,但是那里的答案有点矛盾。

在问:How to add VM options to jar?最高投票+被接受表示这是不可能的,并且在Ques中的大多数答案:Can I set Java max heap size for running from a jar file?说不,这是不可能的。大多数这些答案说“不可能”是由声誉很高的人给出的,因此我认为他们不可能巧合都错。

一个人说可以通过使用this 其他人说要为它安装一个安装程序来完成,或者使用Launch4J或制作批处理文件或制作另一个JAR并通过此运行主要但是大部分都没有与那些说“不”的人相比,获得了很多选票。

这是真的可能吗?我的问题是我的堆空间不足,因此我想在JAR中增加它。

Q1。我已经设置了netbeans增加的堆空间,它也会在JAR中增加吗? (我想不,我只是确认了这一个)

Q2。我现在该怎么做才能在JAR中增加堆空间? (我正在寻找一种易于实现的方法,因为我不了解批处理脚本以及所有这些以及我已经放置安装程序来放置这些文件(高级安装程序)所以我不想让其他安装程序执行此操作)有一条简单的出路吗?

2 个答案:

答案 0 :(得分:1)

A1。从Netbeans运行应用程序时,会生成一个执行应用程序的JVM进程。从Netbeans设置堆大小只是意味着它将使用您配置的最大堆大小启动JVM。它不会以任何方式影响您正在创建的jar。

A2。您无法在jar中配置堆大小。这不能通过编程方式或通过某些Manifest配置来完成 设置最大堆只能通过在启动JVM时传递正确的JVM选项来完成,这可以通过使用某种启动脚本或使用Java启动器来完成,如stackoverflow上的许多答案中所述。
在我看来,启动脚本的选项更好,因为它允许最终用户在需要时控制内存设置。使用启动器时,内存设置通常是硬编码的,无法更改。 我建议您应该查看可用于各种开源Java产品的许多启动脚本。另一个选择是搜索“java启动脚本”或类似的。

答案 1 :(得分:1)

  

Q1。我已经设置了netbeans增加的堆空间,它也会在JAR中增加吗?

The memroy use in JVM can be explain blow:



 
  init 
  represents the initial amount of memory (in bytes) that
      the Java virtual machine requests from the operating system
      for memory management during startup.  The Java virtual machine
      may request additional memory from the operating system and
      may also release memory to the system over time.
      The value of init may be undefined.
 
 
 
  used 
  represents the amount of memory currently used (in bytes).
 
 
 
  committed 
  represents the amount of memory (in bytes) that is
      guaranteed to be available for use by the Java virtual machine.
      The amount of committed memory may change over time (increase
      or decrease).  The Java virtual machine may release memory to
      the system and committed could be less than init.
      committed will always be greater than
      or equal to used.
 
 
 
  max 
  represents the maximum amount of memory (in bytes)
      that can be used for memory management. Its value may be undefined.
      The maximum amount of memory may change over time if defined.
      The amount of used and committed memory will always be less than
      or equal to max if max is defined.
      A memory allocation may fail if it attempts to increase the
      used memory such that used > committed even
      if used <= max would still be true (for example,
      when the system is low on virtual memory).
 
 
 

  

Q2。我现在该怎么做才能在JAR中增加堆空间?

可能你可以通过一些技巧来做到这一点,比如把你的罐装在另一个罐子里。

将你的jar复制到another_project / resources /并将another_project打包到jar。

代码打击只是一个示例,可能无法运行或编译。

public static void main(String[] args) {
    String jarFile = this.getClass().getResource("/resources/you.jar").getFile();
    Runtime.getRuntime().exec("java -Xmx256m -jar "+jarFile);
}