How can I get size in bytes of an object sent using RMI?

Posted by Lucas Batistussi on Stack Overflow See other posts from Stack Overflow or by Lucas Batistussi
Published on 2012-10-27T14:10:41Z Indexed on 2012/10/28 5:01 UTC
Read the original article Hit count: 139

Filed under:
|
|
|
|

I'm implementing a cache server with MongoDB and ConcurrentHashMap java class. When there are available space to put object in memory, it will put at. Otherwise, the object will be saved in a mongodb database. Is allowed that user specify a size limit in memory (this should not exceed heap size limit obviously!) for the memory cache. The clients can use the cache service connecting through RMI. I need to know the size of each object to verify if a new incoming object can be put into memory. I searched over internet and i got this solution to get size:

  public long getObjectSize(Object o){
    try {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(o);
        oos.close();

        return bos.size();      
    } catch (Exception e) {
        return Long.MAX_VALUE;
    }
} 

This solution works very well. But, in terms of memory use doesn't solve my problem. :( If many clients are verifying the object size at same time this will cause stack overflow, right? Well... some people can say: Why you don't get the specific object size and store it in memory and when another object is need to put in memory check the object size? This is not possible because the objects are variable in size. :(

Someone can help me? I was thinking in get socket from RMI communication, but I don't know how to do this...

© Stack Overflow or respective owner

Related posts about java

Related posts about stream