• Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialize object with nio

 
Joe Nguyen
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I notice that oos.writeObject(aObject) is slow. What should I do to get better performance? What I want to do is to serialize an object to a byte array and store this byte array to a table. I know the java.nio package helps to increase i/o performance, but I could not find any sample code doing this. How do I replace stream with channel?
 
J Kneeland
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well,as you may know, you use Buffers to work with NIO channels. You can get an object into a byte array by using an ObjectOutputStream wrapped around a ByteArrayOutputStream. After you are done writing the object, you can get the array from the ByteArrayOutputStream by calling its toByteArray() method which returns a byte array. Now that you have the object in a byte array, you need to get it into a Buffer. The best choice for this is the ByteBuffer class since it is implemented using a byte array internaly. You can obtain a ByteBUffer object that contains this data by calling the static method wrap(byte[]) and passing the byte array you had. You can now send the data through the channel by calling it's write(Buffer) method and passing the buffer. In order to retrieve the data using NIO, you would do the exact opposite using the input stream complements to the output streams you used.

Done using NIO SocketChannels:
* Note, not accounting for exceptions. Catch them yourself *

 
Joe Nguyen
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sc = (SocketChannel) channel;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //make a BAOS streamObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the stream
oos.write(new Integer(5)); // write an object to the stream
byte[] objData = baos.toByteArray(); // get the byte array


1. Do I need to create a socket to do this? I don't need a socket because I just want to get a byte array.
2. The invocation of oss.write(...) is pretty slow. Is there any way I can make it run faster?
3. baos.toByteArray() is not an evil method since it returns a deep copy of the byte array.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!