Object accessible while being serialized?

T

Timo Nentwig

Hi!

Am I right that I can (read-only) access an object *while* it is serialized?
If so, only the serialization needs to be synchronized?

I wrote a little test app:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io_ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test
{
private static class Blah extends Thread
{
private Map m;

public Blah( final Map m )
{
this.m = m;

}

public void run()
{
System.out.println( "start." );
for( final Iterator it = m.keySet().iterator(); it.hasNext(); )
it.next();
System.out.println( "done." );

}

}

public static void main( String[] args )
{
final int size = 1000000;
final Map m = new HashMap( size );
for( int i = 0; i < size; i++ ) m.put( printable( (int
(Math.random() * 10d) ), printable( (int)(Math.random() * 20d) ) );

System.out.println( "initialized." );

try
{
long t = -System.currentTimeMillis();
Blah thread = new Blah( m );
thread.start();
serialize( m, new File( "/tmp/test" ) );
System.out.println( (t += System.currentTimeMillis()) );

}
catch( IOException e )
{
System.err.println( e );

}
}


private static synchronized final void serialize( final Object o, final
File f ) throws IOException
{
final ObjectOutputStream serializer = new ObjectOutputStream( new
BufferedOutputStream( new FileOutputStream( f ) ) );

serializer.writeObject( o );
serializer.flush();
serializer.close();
}

private static final String printable( final int length )
{
final StringBuffer buf = new StringBuffer( length );
for( int i = 0; i < length; i++ )
//            buf.append( (char)(32 | 1 + (int)(Math.random() * 125)) );  //
incl. space
buf.append( (char)((32 | 1 + (int)(Math.random() * 124)) + 1) );
return buf.toString();
}

private static final String rndstr( final int length )
{
final StringBuffer buf = new StringBuffer( length );

for( int i = 0; i < length; i++ ) buf.append( (char)(((Math.random()
< 0.5d) ? 64 : 96) | 1 + (int)(Math.random() * 26)) );
return buf.toString();
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top