Linux

人为提高Linux系统CPU及内存使用率

Posted by dm on September 19, 2022

提高内存使用率方法

  1. 编辑代码

    package com.example.JVMProject;
       
    import org.springframework.boot.autoconfigure.SpringBootApplication;
       
    import java.util.ArrayList;
       
    @SpringBootApplication
    public class JvmProjectApplication {
       
    	public static void main(String[] args) {
    		//xxx是大量的文本文字
    		String str = "该应用脚本是为了提高机器的CPU使用率,它会根据当前机器CPU (会自动排除本程序进程所占用CPU%) 决定是否需要”协助“已提高当前机器的CPU的使用率;\n" +
    				"\n该应用脚本是为了提高机器的CPU使用率,它会根据当前机器CPU (会自动排除本程序进程所占用CPU%) 决定是否需要”协助“已提高当前机器的CPU的使用率;\n" +
    				"\n该应用脚本是为了提高机器的CPU使用率,它会根据当前机器CPU (会自动排除本程序进程所占用CPU%) 决定是否需要”协助“已提高当前机器的CPU的使用率;\n" +
    				"\n该应用脚本是为了提高机器的CPU使用率,它会根据当前机器CPU (会自动排除本程序进程所占用CPU%) 决定是否需要”协助“已提高当前机器的CPU的使用率;\n";
    		ArrayList<String> list = new ArrayList<>();
    		int flag = 0;
    		long num =20L;
    		//long num = 200000000000L;
    		while (flag < num) {
    			list.add(str);
    			flag++;
    		}
    		System.out.println("循环执行完毕...");
    		try {
    			Thread.sleep(2000L);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		System.out.println("内存高负载......");
    		try {
          // 30天
    			Thread.sleep(86400000L*30);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		System.out.println("one month");
    	}
    }
       
    
  2. 打包jar包,执行idea中maven-complie-package

  3. 运行jar包

    java -jar -Xms15360m -Xmx16384m xxx.jar
    
  4. 查看内存上升情况free -h

  5. 内存使用率上升后执行后台运行

    nohup java -jar -Xms15360m -Xmx16384m xxx.jar &
    
  6. 执行后报错nohup: ignoring input and appending output to ‘nohup.out’

    原因:利用nohup命令运行程序,nohup会产生日志文件,所以需要我们把日志文件写到nohup.out, 需要运行的程序是 nohup java -jar -Xms15360m -Xmx16384m xxx.jar &

    nohup java -jar -Xms15360m -Xmx16384m xxx.jar > /dev/null 2 > /dev/null 2>&1 &
    
  7. 创建restart.sh脚本,当进行停止后自动启动

    #! /bin/bash
       
    while true
    do
    	jvmproject=`ps -ef | grep JVMProject-0.0.1-SNAPSHOT.jar | grep -v grep | wc -l ` 
    	if [ $jvmproject -eq 0 ] 
    	then
    		echo "JVMProject program is not running, restart JVMProject"
                    java -jar -Xms18432m -Xmx20480m /starsino/project/JVMProject-0.0.1-SNAPSHOT.jar
    	else
    		echo "JVMProject program is running"
    	fi
    	sleep 5
    done