如何在bash中dynamic设置java内存大小?

#!/bin/bash # module add apps/java/1.6 java -Xmx1024m HelloWorld 

我需要设置-XmxYm ,其中Y应该是Mb中系统可用内存的95%。

这是一个脚本,调用Java所需的堆大小。

 #!/bin/bash # Total memory in KB totalMemKB=$(awk '/MemTotal:/ { print $2 }' /proc/meminfo) # Percentage of memory to use for Java heap usagePercent=95 # heap size in KB let heapKB=$totalMemKB*$usagePercent/100 # heap size in MB let heapMB=$heapKB/1024 module add apps/java/1.6 java -Xmx${heapMB}m HelloWorld 

我强烈建议您使用较低的usagePercent,因为Java应用程序比堆大小(例如PermGen)使用更多的内存。

正如Peter Lawrey所说,把95%的内存分配给堆可能不是明智的。

但是,您可以通过阅读“/ proc / meminfo”文件来确定内存大小。 尝试

 cat /proc/meminfo MemTotal: 32958996 kB MemFree: 23461744 kB Buffers: 133772 kB Cached: 1651888 kB SwapCached: 0 kB Active: 8460504 kB Inactive: 740048 kB HighTotal: 0 kB HighFree: 0 kB LowTotal: 32958996 kB LowFree: 23461744 kB SwapTotal: 34996216 kB SwapFree: 34996216 kB Dirty: 372 kB Writeback: 0 kB AnonPages: 7415344 kB Mapped: 61260 kB Slab: 206896 kB PageTables: 24320 kB NFS_Unstable: 0 kB Bounce: 0 kB CommitLimit: 51475712 kB Committed_AS: 18514524 kB VmallocTotal: 34359738367 kB VmallocUsed: 282388 kB VmallocChunk: 34359454135 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 Hugepagesize: 2048 kB