Created
May 26, 2020 14:39
-
-
Save horitaku1124/f6dfbed357042bb7801f7d2c4a29d41e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
import static java.lang.Thread.sleep; | |
public class MemoryLimit { | |
private static final int TRY_COUNT = 5; | |
public static void main(String[] args) throws IOException, InterruptedException { | |
double memory = 10_000_000; | |
double lastSuccessMemory = memory; | |
double lastFailedMemory; | |
while(true) { | |
int mem = (int) memory; | |
boolean succeed = tryProcess( | |
"java", | |
"-Xmx" + mem, | |
"-jar", | |
"./build/libs/demo-0.0.1-SNAPSHOT.jar"); | |
System.out.format("% 10d\t%b\n", mem, succeed); | |
if (succeed) { | |
lastSuccessMemory = memory; | |
memory = memory * 0.95; | |
} else { | |
lastFailedMemory = memory; | |
break; | |
} | |
} | |
double startMem = (lastSuccessMemory + lastFailedMemory) / 2; | |
System.out.println("center=" + startMem); | |
double div = 0.01; | |
boolean upper = true; | |
for (int j = 0;j < 10;j++) { | |
int mem = (int)startMem; | |
int success = 0; | |
System.out.format("% 10d ", mem); | |
for (int i = 0;i < TRY_COUNT;i++) { | |
boolean succeed = tryProcess( | |
"java", | |
"-Xmx" + mem, | |
"-jar", | |
"./build/libs/demo-0.0.1-SNAPSHOT.jar"); | |
System.out.format(" %b", succeed); | |
if (succeed) { | |
success++; | |
} | |
} | |
int successRate = (success * 100 / TRY_COUNT); | |
System.out.println(" success rate = " + successRate + "% div=" + div + " upper=" + upper); | |
if (successRate < 50) { | |
startMem = startMem * (1 + div); | |
if (!upper) { | |
div = div / 2; | |
} | |
upper = true; | |
} else { | |
startMem = startMem * (1 - div); | |
if (upper) { | |
div = div / 2; | |
} | |
upper = false; | |
} | |
} | |
} | |
private static boolean tryProcess(String... args) throws IOException, InterruptedException { | |
final Process process = new | |
ProcessBuilder(args).start(); | |
boolean succeed = false; | |
InputStream inputStream = process.getInputStream(); | |
byte[] buff = new byte[10000]; | |
for (int i = 0;i < 100 && process.isAlive();i++) { | |
if (inputStream.available() > 0) { | |
int len = inputStream.read(buff); | |
String line = new String(buff, 0, len); | |
// System.out.print(line); | |
if (line.contains("Tomcat started on port")) { | |
succeed = true; | |
break; | |
} | |
} | |
sleep(100); | |
} | |
process.destroy(); | |
return succeed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment