package org.etsi.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MemoryTest {

	public static void main(String[] args) {
		try {
			int heap = 512;
			int heapIncrement = 128;
			while(startSecondJVM(heap+heapIncrement)==0){
				heap+=heapIncrement;
			}
			System.out.println(heap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static int startSecondJVM(int heap) throws Exception {
	    String separator = System.getProperty("file.separator");
	    String classpath = System.getProperty("java.class.path");
	    String path = System.getProperty("java.home")
	            + separator + "bin" + separator + "java";
	    ProcessBuilder processBuilder = 
	            new ProcessBuilder(path, "-Xmx"+heap+"m", "-Xss128m", "-cp",
	            classpath, 
	            MemoryTestDummy.class.getName());
	    Process process = processBuilder.start();
	    process.waitFor();
//	    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//	    String line;
//	    while((line = br.readLine())!=null){
//	    	System.out.println(":"+line);
//	    }
	    process.destroy();
	    return process.exitValue();
	}
}
