Created
September 19, 2012 05:42
-
-
Save digitalsonic/3747876 to your computer and use it in GitHub Desktop.
Try to make an OOM while reading file with an extream large buffer.
This file contains 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
package demo; | |
import java.io.File; | |
import java.io.FileInputStream; | |
/** | |
* Run the demo on Linux with 32-bit JVM | |
* Add the command line parameters -Xmx1600m -Xms1600m. | |
* | |
* readBigBuffer should fail with OOM. | |
* readSmallBuffer should be OK. | |
* | |
* @author DigitalSonic | |
*/ | |
public class ReadFileWithBufferDemo { | |
public static void main(String[] args) throws Exception { | |
System.out.println("Max mem: " + Runtime.getRuntime().maxMemory()); | |
System.out.println("Current mem: " + Runtime.getRuntime().totalMemory()); | |
File f = File.createTempFile("tmp", ".txt").getCanonicalFile(); | |
f.deleteOnExit(); | |
readBigBuffer(f); | |
readSmallBuffer(f); | |
} | |
public static void readBigBuffer(File f) throws Exception { | |
System.out.println("Read the file with 1GB buffer."); | |
FileInputStream fis = new FileInputStream(f); | |
byte[] bytes = new byte[1024 * 1024 * 1024]; // 1GB | |
try { | |
System.out.println(fis.read(bytes)); | |
} catch (OutOfMemoryError e) { | |
System.out.println("FAILED!!! OutOfMemoryError!!!"); | |
e.printStackTrace(); | |
} finally { | |
fis.close(); | |
} | |
} | |
public static void readSmallBuffer(File f) throws Exception { | |
System.out.println("Read the file with 10MB buffer."); | |
FileInputStream fis = new FileInputStream(f); | |
byte[] bytes = new byte[1024 * 1024 * 10]; // 10 MB | |
int i = 0; | |
try { | |
while ((i = fis.read(bytes)) > -1) { | |
System.out.print(i + ","); | |
} | |
} catch (OutOfMemoryError e) { | |
System.out.println("FAILED!!! OutOfMemoryError!!!"); | |
e.printStackTrace(); | |
} finally { | |
fis.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment