NIO and object serialization

I try to use the new IO API to implement a non-blocking multi-threaded server that communicates with client applications by exchanging serialized objects. I started from the code in the JavaWorld article at http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html .
With the new features of J2SDK 1.4.0, you don't have to create a separate thread per connected client. That is a big improvement.
But when I read an object with ObjectInputStream, I get a java.nio.channels.IllegalBlockingModeException.
Has anybody successfully implemented such a server since the release of the new io API?
Thanks.
Jean-Robert

Hi,
I tried to decode it and reconstruct the object as follows:
buffer.flip();
// Decode buffer
decoder.decode(buffer, charBuffer, false);
// Display
charBuffer.flip();
String str = charBuffer.toString();
try
     ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
     ObjectInputStream ois = new ObjectInputStream(bis);
     Object obj = ois.readObject();
     if (obj != null)
     System.out.println(obj.getClass().getName());
     System.out.println("Construction successful");
catch (Exception e)
     e.printStackTrace();
I think it is constructing the object. But it gave me the following exception:
java.io.InvalidClassException: MessageValueObject; local class incompatible: stream classdesc serialVersionUID = -1062950779601993928, local class serialVersionUID = -1038743931604855240
     at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:454)
     at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1511)
     at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1425)
     at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1616)
     at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1264)
     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:322)
     at com.csxwt.zodiac.client.common.NIOPushletClient.run(NIOPushletClient.java:254)
     at java.lang.Thread.run(Thread.java:536)
Whe I compared the bytes of returned object with the actual object I noticed that two bytes were different from the orignal. They were replaced with '?' (byte code 063) in the reconstructed byte stream.
If anybody have a clue please help me too

Similar Messages

  • Servlet and Object Serialization

    Hi,
    I am developing a routing server in Java
    2 Instances of the same server will be running in 2 different data centers.
    The servers have a Jetty server embedded with a Servlet inside.
    Server 1 will use a GET method to talk to the Server 2 -> Servlet which will write the state of an object back which will read by Server 1 and reconstruct the object back.
    Do you find any issues in Object Serialization/DeSerialization in the Servlet.
    What are the factors that I need to consider in this case?
    Regards,
    Jana

    Make sure that your servlet handles the transaction in the same thread that doPost() or doGet() is called in.
    I ended up porting some old ServerSocket based code to a servlet, and was handing off the request and response objects to a handler thread on the server side. I ended up with a ton of intermittent errors like this.
    Once I started handling the transactions in the same thread things worked heartbreakingly well.

  • EOFException and Object Serialization

    Hello, I am trying to build a distributed file storing system by using Multicast Sockets and I experience a problem the past 2 days.
    I have to use multicast sockets because it is not my decision.
    The problem appears when i have to transfer a file between 2 machines via UDP Datagrams.
    I know that the size of the byte array that is contained in a datagram is quite small so I built a function that breaks the file in to small byte arrays that have the size of 9500 bytes each.
    I insert these byte arrays in a new object that I call message and has additional information and I serialize the message object
    I send this byte array through the UDP socket and when I try do deserialize it on the other side I receive an EOFException that comes from the ObjectStream and particularly the method read() of the ObjectInputStream returns -1 which means it found the EOF in message that is been transported.
    I checked the bytes that are contained in the byte array with the partition of the file that is being transferred and I noticed that inside the file there are a number of negative numbers., which, as far as I know, shouldn't be happening.
    do you have any ideas for the reason these are happening?
    Thank you.
    Vagelis

    You can get negative bytes in an object stream.
    Try ensuring you have sent the length of the data and the data has been received in the correct order. Note Datagrams don't guarentee the order that packets were sent is the order they will be received.
    I would put a check sum at the end of your data to ensure the data is sound before attempting to decode it.
    If your packets are large, one option may be to compress the data with DeflatorOutputStream and InflatorInputStream. This can compress large object streams very well.

  • JMS and object serialization

    My Code is mentioned below
    public class PMLCommandDTO  implements Serializable {
        ConfigureTagFilter cfgTagFltrObj;
        WriteTagData writeTagDataObj;
        ExtensionCommand  extnCmdObj;
       // all getter setter method.
    }Now I set ConfigureTagFilter object (which is not serialized) to the
    PMLCommandDTO class.
    PMLCommandDTO serializedObj;
    serializedObj = new PMLCommandDTO();
    serializedObj.setCfgTagFltrObj(cfgTagFltrObj);Now Can I my "serializedObj" is serialized and can I use it to
    javax.jms.ObjectMessage ---- > setObject(Serializable) method.

    Cross post, already being responded in
    http://forum.java.sun.com/thread.jspa?threadID=5214314&tstart=0
    db

  • Servlets and Object Serialization

    Say, you have a Servlet which sends Objects across an ObjectOutputStream which is obtained from its corresponding HttpServletResponse.
    res.getOutputStream().writeObject(myObject);
    From what I observe it is impossible to obtain an ObjectInputStream from the URLConnection of the calling servlet until it is finished processing.
    Does anyone know if there is a way to do this?
    URLConnection conn = _myUrl.openConnection();
    conn.setDoOutput(false);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    ObjectInputStream in = new ObjectInputStream(conn.getInputStream());
    System.out.println("This won't get called until the calling Servlet has finished processing, is it possible to retrieve before???");
    String s = in.readObject().toString();

    hi , I made a similar query some time ago and came up with the following solution.
    serverUrl_ = new URL(url_);
                   HttpURLConnection con_ = (HttpURLConnection)serverUrl_.openConnection();
                   con_.setRequestMethod("POST");
                   con_.setDoOutput(true);
                   con_.setDoInput(true);
                   con_.setUseCaches(false);
                   ObjectOutputStream out_ = new ObjectOutputStream(con_.getOutputStream());
                        out_.writeObject(new String("a test example to string"));
    The servlet would read this in as follows:
         protected void doPost(HttpServletRequest request_, HttpServletResponse response_){
              try{
                   //get required io streams
                   ObjectInputStream ois_ = new ObjectInputStream(request_.getInputStream());
                   ObjectOutputStream object_ = new ObjectOutputStream(response_.getOutputStream());
                   String test_ = (String)ois_.readObject();
                   if(test_ instanceof String){
                        System.out.println("String value is: "+test_);
                   } else {
                             System.out.println("error reading string")
              } catch(Exception ioe){
                   ioe.printStackTrace();
    this should give you the basic idea how to pass objects through http.
    Hope it helps
    rob

  • Error publishing plsql webservice (xml schema mapping and/or serializer)

    Hi guys,
    I'm with a problem when publishing plsql webservices from JDeveloper 11.
    The scenario is something like this:
    1) I have a connection with a database 9i, and the objects (packages, object types, etc) are all in there.
    2) In this case, i can publish the package spec using the option "Publish as JAX-RPC Web Service" normally.
    3) A database 11g was created, and i compiled the objects in this environment.
    4) Then i've created a new connection with a database 11g.
    5) In this case, when i'll publish the webservice, the error occurs: "The following types used by the program unit do not have an XML Schema mapping and/or serializer specified: REC_DMP_REMESSA"
    I have no idea in how to solve this case. Someone can help?
    Thank in advance.
    Best Regards,
    Gustavo

    Duplicate of https://forums.oracle.com/thread/2610823
    Timo

  • 2D objects Serialization problem

    Welcome!
    I'm making a net game using RMI and I have this problem.
    When I'm trying to join my client with the server an error occures:
    Error: error marshalling arguments; nested exception is:
         java.io.NotSerializableException: java.awt.geom.Ellipse2D$Double
    My client contains an Object extending a JPanel class. There are 2D object used to make the map, and that's why this error occures.
    It's a funny thing, cause I'm not sending a whole Object of my client, but only it's refference (using "this" in the join() method) so I dont know why does the 2D object need to be serialized and sent :|?
    Any way, my question is how to make 2D objects serializable!? I have jdk1.5.0_06 and as far as I remember they should be srializable in this version. Mabey I'm dooing something wrong!? Mabey it's nessesary to ad an appropreate code-line or import sth... i don't know
    please help me... I have little time to finish my project, and this thing is blocking my work.
    Big thanks to anybodey who will help.
    regards floW

    I'll tel u the whole story then, my problem is as follows:
    public class BounceThread{
       public static void main(String[] args)   {
          JFrame ramka = new BounceFrame();
             ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             ramka.setVisible(true);
    class BounceFrame extends JFrame{
    public BounceFrame()
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
          setTitle("MiniGolf v 1.0");
          panel = new BallPanel(); // this contains maps made with 2D objects
          panel.setBackground(Color.green);
          panel.setVisible(panel.czy_widać_panel());
          add(panel, BorderLayout.CENTER);
    // I add a menu bar, that starts a net game:
    JMenuBar pasekMenu = new JMenuBar();
              setJMenuBar(pasekMenu);
              JMenu menuGra = new JMenu("Game");
           // and so on... and finaly I add an option:
              menuGame_Nowa.add(new
                        AbstractAction("Net game")
                             public void actionPerformed(ActionEvent event)
                                  net_game(panel);
    // here i write my net_game method:
    public void net_game(BallPanel aPanel)
         //here, i make an Client object, and connect him with my server
         client = new mgClient(panel);
         client.join();
         // I give panel as a paramete, cause I cant think of another way of leting my server to uce it's (panels) methods
         // If I join only a name of my client, then how can I change the panel in my BounceFrame from the Clients method
         // "shouted" by the server!? It has to be a field in the client's object.
         // Is there any other way out!?
    // Class BouceFrame holds the panel as a field:
    private mgClient client;
    private BallPanel panel;
    //and so on...
    }and that's the real problem I'm facing here. Is there any solution!? I think, that making a Client's field out of my panel is the only way ot. And that means I need those 2D objects serialized... :(
    Please help if u can.
    Regards floW

  • Byte [] to Object and Object to byte[]

    Hi,
    I am quite new to java and need some help. My question is how can I convert an Object to byte [] and convert back from byte [] to Object.
    I was thinking of something like:
    From object to byte []
    byte [] object_byte=object.toString().getBytes();
    When I try to do:
    String obj_string=object_byte.toString();
    But obj_string is not even equal to object.toString().
    Any suggestions?
    Thanks

    well nnneil, if you try to convert and Object into a byte[] in that way you only convert the string representation of the object in bytes.
    If you remenber an object is more than a simple bytes stream, an object have Class, Methods, Attributes and other things, if you wanna, you can use serializable to convert your object in a bytes stream.
    Or if your problem if pass something like {0x01,0x02,0x0f,...} in an object you can use a simple casting over your variable.
    try with this:
    public class Main
    public static void main(String[] args)
    try
    byte[] bs = {0x00,0x00,0x00};
    Object o = (Object)bs;
    System.out.print("Object:[" + o.toString() + "]");
    System.out.print("<- That does not equals to ->");
    int i = 0;
    while(i < bs.length)
    System.out.print("[" + bs[i++] + "]");
    catch(Exception e){
    e.printStackTrace();
    output is: Object:[[B@df6ccd]<- That does not equals to ->[0][0][0]
    if you see [B@df6ccd is the internal represent of bs object.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Customizing Forte object serialization

    Forte supports serialization of arbitrary object graphs into streams.
    However, there do not seem to be any well documented ways to customize
    this serialization, e.g. by using a different encoding scheme. It would
    seem there must be some support in there somewhere. I suppose at the
    very least, one could parse a serialized object (once one decoded the
    Forte encoding scheme) and do the conversion from that. That seems
    suboptimal, though.
    Has anyone done this? Any thoughts on how it might be done?
    Regards,
    Coty
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/forte>

    JavaFunda wrote:
    Object serialization is the process of saving an object's state to a sequence of bytes. Does it saves only the instance variable or also the object methods(like getter and setter methods) ? Only the state--the instance variables. It doesn't save the class definition. That has to be available separately (via classloader) at deserilaization time. In other words, you cannot deserialize an instance of a class that is not on your classpath.
    Once we we write the object to outputstream or some text file, how does it get transmitted over network?The same way any other bytes get transmitted. You have a Socket. You get its OutputStream. You wrap that in an ObjectOutputStream. When you write to the ObjectOutputStream, that writes through to the Socket's OutputStream, which is responsible for putting the bytes on the wire.
    Does we write the java object to text file only duuring serialization?We write the objects to wherever the other end of the ObjectOutputStream is connected to. Just like any other I/O.

  • Runtime Object serialization

    Hi,
    Could someone explain the concept of Runtime Object Serialization with a simple example?
    Thanks

    import java.io.*;
    /* you NEED to make the class implement Serializable */
    class Client implements Serializable {
        private String name;
        private String address;
        public String getName() { return name; }
        public String getAddress() { return address; }
        public void setName(String name) { this.name = name; }
        public void setAddress(String address) { this.address = address; }
        public String toString() { return "name='" + name + "' and address= " + address + "'"; }
    public class Test17 {
        public static void main(String[] args)  throws Exception {
            ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("test.bin"));
            Client myClient = new Client();
            myClient.setName("Steve Jobs");
            myClient.setAddress("1 Infinite Loop; Cupertino, CA 95014");
            System.out.println (myClient);
            oos.writeObject (myClient);
            oos.close();
            ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("test.bin"));
            Client yourClient = (Client) ois.readObject();
            System.out.println (yourClient);
    }Run the program above. It creates an object of the class "Client", serializes it into a file named "test.bin" and recreates the object reading it from the same file.
    Dumping the binary file you get this:
    0000    AC ED 00 05 73 72 00 06  43 6C 69 65 6E 74 F1 D7   ....sr..Client..
    0010    74 76 C4 64 FD 43 02 00  02 4C 00 07 61 64 64 72   tv.d.C...L..addr
    0020    65 73 73 74 00 12 4C 6A  61 76 61 2F 6C 61 6E 67   esst..Ljava/lang
    0030    2F 53 74 72 69 6E 67 3B  4C 00 04 6E 61 6D 65 71   /String;L..nameq
    0040    00 7E 00 01 78 70 74 00  24 31 20 49 6E 66 69 6E   .~..xpt.$1 Infin
    0050    69 74 65 20 4C 6F 6F 70  3B 20 43 75 70 65 72 74   ite Loop; Cupert
    0060    69 6E 6F 2C 20 43 41 20  39 35 30 31 34 74 00 0A   ino, CA 95014t..
    0070    53 74 65 76 65 20 4A 6F  62 73                     Steve JobsYou can see a lot of things in the serialization of the object Client - the name of the class is written, the names of the fields, the type (java/lang/String), and the values of the fields as UTF-8 encoded strings.

  • Object serializable?

    Hi,
    When writing a vector of my own objects out to a file, do the objects need to be serializable even though it is actually the vector I am outputting?
    Also, each of my objects in this vector have a field that is a vector of other objects...do I need to declare those objects serializable also?

    I think you still need to implement serializable on objects contained in the vector. I tried serializing a hashmap and my hashmap contained objects which needed to be serialized before the hashmap could be stored in a file.

  • Object serialization failure during OutOfMemory error (EOFException)

    Hello all,
    We are seeing a very strange situation when writing a serializable object to a flat file, specifically during an OutOfMemory condition. Our application saves the state of an object if an error occurs, and retries at a later point by reviving the object from its serialized form. We recently encountered a series of EOFExcetions when trying to reload the serialized object. Looking at the serialized data, we see that the file is indeed incomplete, and that it appears to be the serialized representation of the data contained within the object that is missing (the structure of the object appears to be stored in the serialized file, but not the runtime data).
    The code that produces and consumes these serialized objects is used in a variety of locations, and even in the case where these EOF errors occurred usually works as expected. The difference appears to be that the error condition which lead to the object serialization was in-fact an OutOfMemory error. That is, we had an OOM error elsewhere in our application, which caused our objects to be serialized to disk. During this serialization process we end up with corrupt (incomplete) serialization data.
    So.. the question is: Is it possible that the OutOfMemory situation causes the JVM to incorrectly serialize an object (without an error), and specifically to omit runtime data (variables) from the serialized form of the object?
    Thanks/

    jasonpolites wrote:
    So.. the question is: Is it possible that the OutOfMemory situation causes the JVM to incorrectly serialize an object (without an error), and specifically to omit runtime data (variables) from the serialized form of the object?you're sure that the serialization process completed without an error? how do you know the the OOME did not cause the serialization to fail (because the serialization process itself will require more memory, hence if it is happening while the system is near the memory peak, it is likely to fail as well)? generally, when a jvm starts throwing OOME's all bets are off. failures in random places can easily cause the whole internal state of a system to become invalid.

  • Object serialization EOFException

    Essentially what I want to do is write to an object to a file. The program can terminate and then when I start the program again, it will read the object from the file and restore the program's original state before it was terminated.
    I get an EOFException with this code
    //insert code that gets input which will be stored in a hashtable
    //save Hashtable in "data.dat" using ObjectOutputStream
    //program terminates
    //program is re-ran again and checks for existing file
    File f = new File("data.dat");
    if(f.exists()){
           ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
           Object obj = ois.readObject(); //EOF exception occurs here
    }I know the above code works if I write the Hashtable and then read it back immediately without terminating in between. Am I missing something? Can object serialization be used in such a way that I can restore a program's original state before it was terminated?

    Sorry, I led you to believe that the actual class itself was going to be written to a file. I meant to say that the Hashtable in the class should be written to a file and then later on when I start the program again, it will restore the Hashtable to it's original state.
    My writing coding is something like this:
    Hashtable accounts = new Hashtable();
    //do stuff to the hashtable
    FileOutputStream fos = new FileOutputStream("data.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(accounts);
    //Program can be terminated from this point
    //there is no further oos.writeObject() if it wasn't terminated
    //immediately after the above writeObject() call
    //Program is ran again and at startup it checks for existing file
    File f = new File("data.dat");
    if(f.exists()){
    ObjectInputStream ois = new ObjectInputStream(new FileInpuStream(f));
    Object obj = obj.readObject(); //EOFException occurs here
    }Again those lines work perfectly fine if I do not terminate the program and I force it to check for an existing file. If I terminate, it's almost as if the program thinks there's nothing in "data.dat" eventhough it's obvious by my code that I did write something to "data.dat".

  • Communication between javascript and Objective-c in iOS.

    We wanted to have a communication between javascript and objective c code. We have already tried the below approach.
    To load fake URLs in JS and append a string which will be used as parameter to the Objective-C code and parse that URL in this delegate method:
    -(BOOL)webView(UIWebView *)webView shouldStartLoadWithRequest(NSURLRequest *)request navigationType(UIWebViewNavigationType)navigationType
    Then send the return value by calling the native method stringByEvaluatingJavaScriptFromString again with parameter callID.
    But we wanted to access Objective class object in Javascript code so that we can call it's methods from javascript code using this object.Android supports this behaviour using addJavaScriptInterface method in webview. Is it possible to have the similar approach in IOS? If not what is the best approach possible to acheive this? If we could achieve similar behaviour then we don't need to change the Jacascript code and will be reused. Please suggest the best possible solution.
    Regards,
    Karthik M.

    https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptu al/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html

  • System and Object privileges question

    hello everyone.
    I was really making it a priority to really understand both system and object privileges for users. I have setup a couple of 'sandboxes' at home and have done lots of testing. So far, it has gone very well in helping me understand all the security involved with Oralce (which, IMHO, is flat out awesome!).
    Anyway, a couple of quick questions.
    As a normal user, what view can I use to see what permissions I have in general? what about permissions on other schemas?
    I know I can do a:
    select * from session_privs
    which lists my session privileges.
    What other views (are they views/data dictionary?) that I can use to see what I have? Since this is a normal user, they don't have access to any of the DBA_ views.
    I'll start here for now, but being able to see everything this user has, would be fantastic.
    Cheers,
    TCG

    Sorry. should have elaborated more.
    In SQLPLUS, (logged in while logged into my Linux OS), I am working to try and get sqlplus to display the results of my query so it is easy to read. Right now, it just displays using the first 1/4 or 1/3 of the monitor screen to the left. Make sense? So it does not stretch the results out to utilize the full screen. it is hard to break down and read the results because they are "stacked" on top of each other.
    Would be nice if I could adjust sqlplus so the results are easier to read.
    HTH.
    Jason

Maybe you are looking for

  • My click wheel and select button are unresponsive

    hi I've had my iPod mini for just over a year now and I've had one or two problems in the past. However, I've been able to reset it by holding the select button and menu button. However, today my iPod's click wheel will not respond (and doesn't make

  • REP-1212: Object 'Body' is not fully enclosed by its

    I get this error when I run a report. Where can I get explaination for these error id like (REP-1212). Thanks null

  • Error 1310. Unable to update / repair / install

    For over a week, on start up of my computer Adobe Acrobat tries to do an update - and fails due to " error 1310. Error writing to file: C:\Program Files\Adobe\Acrobat 7.0\ActivX\AcroPDF.dll. Verify that you have access to that directory " But on canc

  • TS3988 mail password not valid

    I can get mail on my iPhone and iPad, but prefer to get it on my computer because it "manages" for me.  When I try to get mail, it says my password is not valid. Have changed it on all my devices and on iTunes.  any ideas about what's going on?  than

  • IBook won't start up, none of the website's advice is working

    This iBook has 10.2 installed. I have previously tried reinstalling from those discs but it never worked. I found the original install discs that came with the computer so I have been trying yet again to fix it. I just can't give up. It gets stuck on