Name: skT45625 Date: 08/18/2000
java version "1.3.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)
When using a loop to serialize objects to a file, the ObjectOutputStream object
never seems to release the references to objects that have already been written
to the file. Since the garbage collector can't clean up these objects, it's
relatively simple to generate an OutOfMemoryError.
Here is some sample code:
public class MyObject() {
static public void main(String[] args) {
try {
File file = File.createTempFile("test", null);
FileOutputStream testFile = new FileOutputStream
(file.getAbsolutePath(), true);
ObjectOutputStream testOut = new ObjectOutputStream(testFile);
// Write a bunch of double arrays to the file
for (int i = 0; i < 100; i++) {
testOut.writeObject(new double[1000000]);
testOut.flush();
}
testOut.close();
testFile.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Before the program finishes, an OutOfMemoryError is generated (using the
default memory allocation for the virtual machine). Shouldn't each double
array be marked for garbage collection once it has been written to the stream?
If so, is this an io error or a garbage collection error?
(Review ID: 108636)
======================================================================
Name: krC82822 Date: 10/13/2000
java version "1.3.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0)
Java HotSpot(TM) Client VM (build 1.3.0, mixed mode)
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.File;
import java.io.FileOutputStream;
public class MemoryTest
{
public static void main(String[] args)
{
try
{
File file = new File("/dev/null");
long quantity = Long.parseLong(args[0]);
ObjectOutputStream out
= new ObjectOutputStream(new FileOutputStream(file));
for(long i = 0; i < quantity; i++)
{
out.writeObject(new Long(i));
// eval1127: even a flush() here after every 200 objects did not help
if ((i % 50000) == 0)
{
System.out.println(""+i);
}
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
The above code produces an OutOfMemoryError when the iteration count is high
enough.
Suggest you run as:
java -Xmx10M -Xms10M MemoryTest 10000000
This produces the following output:
0
50000
100000
150000
200000
250000
Exception in thread "main" java.lang.OutOfMemoryError
<<no stack trace available>>
This has been tested on Linux, Solaris and Windows NT. All were using JDK1.3.
All produced the same output.
I'm assuming the error is something to do with Serialization as the error does
not seem to occur when the writeObject line is removed.
(Review ID: 110753)
======================================================================