如何解决内存溢出的问题
来源:不详 责任编辑:栏目编辑 发表时间:2013-07-01 23:13 点击:次
一 调整 虚拟机参数
二 立即 释放无用的对象
三 利用序列化和反序列化技术
下面是具体的代码实现
package com.free; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * @author free * */ public class OutMemorySolution { /*** * Change JVM Arguments * 调整 虚拟机参数 * * * * First Try * * -Xloggc:gc.log * -Xms256M * -Xmx256M * * throw java.lang.OutOfMemoryError: Java heap space * * * Second Try * * -Xloggc:gc.log * -Xms512M * -Xmx512M * * */ public static void changeJVMArguments() { long startTime = System.currentTimeMillis(); System.out.println("Start : " + startTime); List list = new ArrayList(0); for (int i = 0; i < 5000000; i++) { list.add(new BigInteger("1000000")); } long endTime = System.currentTimeMillis(); System.out.println("End.. : " + endTime + " Cost : " + (endTime - startTime)); } /** * Release Object Immediate * 立即 释放无用的对象 * * * Release Object * * * //First Release Object * BigInteger temp1 = null; * for (int i = 0; i < 1200000; i++) { * temp1 = array1[i]; * temp1 = null; * array1[i] = null; * } * array1 = null; * ... * //Second Release Object * temp1 = null; * for (int i = 0; i < 1200000; i++) { * temp1 = array2[i]; * temp1 = null; * array2[i] = null; * } * array2 = null; * * */ public static void releaseObjectImmediate() { long startTime = System.currentTimeMillis(); System.out.println("First Start : " + startTime); BigInteger[] array1 = new BigInteger[1200000]; for (int i = 0; i < 1200000; i++) { array1[i] = new BigInteger("10000000"); } // First Release Object BigInteger temp1 = null; for (int i = 0; i < 1200000; i++) { temp1 = array1[i]; temp1 = null; array1[i] = null; } array1 = null; long endTime = System.currentTimeMillis(); System.out.println("First End.. : " + endTime + " Cost : " + (endTime - startTime)); // do something start // do something end.. startTime = System.currentTimeMillis(); System.out.println("Second Start : " + startTime); BigInteger[] array2 = new BigInteger[1200000]; for (int i = 0; i < 1200000; i++) { array2[i] = new BigInteger("10000000"); } // Second Release Object temp1 = null; for (int i = 0; i < 1200000; i++) { temp1 = array2[i]; temp1 = null; array2[i] = null; } array2 = null; endTime = System.currentTimeMillis(); System.out.println("Second End.. : " + endTime + " Cost : " + (endTime - startTime)); } /** * delaySave * 利用序列化和反序列化技术 * Store Object * read Object * do something */ @SuppressWarnings("unchecked") public static void delaySave() { final String objectStoreFolder ="D:\\obj\\"; System.out.println("Store Object Start.."); // Store Object 序列化对象 ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream(
相关新闻>>
- 发表评论
-
- 最新评论 更多>>