When Autoboxing Attacks!

We started using J2SE 5.0 (or “1.5″ as everyone calls it) a little while ago. Here’s a fun little autoboxing typo-bug I just did:

// in some class that implements java.io.Externalizable

  private long startDate_;
  private int intervalMinutes_;

  public void writeExternal( ObjectOutput out )
    throws IOException
    {
    out.writeLong( serialVersionUID );
    out.writeObject( startDate_ );
    out.writeInt( intervalMinutes_ );
    }

  public void readExternal( ObjectInput in )
    throws IOException
    {
    in.readLong();

    startDate_ = in.readLong();
    intervalMinutes_ = in.readInt();
    }

// When run, throws:
Caused by: java.io.EOFException
 at java.io.DataInputStream.readFully(DataInputStream.java:178)
 at java.io.DataInputStream.readLong(DataInputStream.java:380)
 at java.io.ObjectInputStream$BlockDataInputStream.readLong(ObjectInputStream.java:2748)

Yowz! WTF, dude? The problem is with that out.writeObject( startDate_ );. It’s autoboxing the long into a java.lang.Long, and then shitting the bed when it’s reading it back in as a long.

Luckily, it’s an easy enough to fix to do out.writeObject( startDate_ ); -> out.writeLong( startDate_ );.

0 thoughts on “When Autoboxing Attacks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s