Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:33:39+00:00 2026-06-13T11:33:39+00:00

I’m implementing a cache server with MongoDB and ConcurrentHashMap java class. When there are

  • 0

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…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:33:40+00:00Added an answer on June 13, 2026 at 11:33 am

    You can solve the problem of limiting the size of serialized objects using a custom FilterOutputStream that:

    1. counts the bytes that are written by the write method calls, and
    2. throws a custom IOException subclass when the count exceeds your limit.

    Then put this filter between the ByteArrayOutputStream and the ObjectOutputStream.

    This is what the code would look like (not tested!):

        public LimitExceededException extends IOException { ... }
    
        public class LimitingOutputStream extends FilterOutputStream {
            private int limit;
            private int count;
    
            public LimitingOutputStream(OutputStream out, int limit) {
                super(out);
                this.limit = limit;
            }
    
            @Override
            public void write(byte b) throws IOException {
                if (count++ > limit) {
                    throw LimitExceededException(...);
                }
                super.write(b);
            }
    
            @Override
            // (This override is not strictly necessary, but it makes it faster)
            public void write(byte[] bytes, int from, int size) throws IOException {
                if (count += size > limit) {
                    throw LimitExceededException(...);
                }
                super.write(bytes, from, size);
            }
        }
    
        /**
         * Return the serialization of `o` in a byte array, provided that it is
         * less than `limit` bytes.  If it is too big, return `null`.
         */
        public byte[] serializeWithLimit(Object o, int limit) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                LimitingOutputStream los = new LimitingOutputStream(bos, limit);
                ObjectOutputStream oos = new ObjectOutputStream(los);
                oos.writeObject(o);
                oos.close();
                return bos.toByteArray(); 
            } catch (LimitExceededException e) {
                return null;
            }
        }
    

    Yes, this uses exceptions to “get out” when the limit is exceeded, but this is IMO a good use of exceptions. And I challenge anyone who disagrees with that to come up with a better solution. Put it in another Answer.


    By the way, this is REALLY BAD code:

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

    In addition to the IOExceptions that you might expect to be thrown, you are also catching all manner of unchecked exceptions, most of which would be caused by bugs … that you need to know about:

    1. It is bad practice to catch Exception except when you are trying to do a last-ditch diagnosis.

    2. Whenever you catch unexpected exceptions, be sure to log them so that the stack trace can be recorded (depending on the logger configurations). Or if your application doesn’t use a logging framework, then have it call e.printStackTrace().

    (And if you wouldn’t do this in production code, don’t do it into a StackOverflow Question either … ‘cos some copy-and-paste coder might just copy it.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
i got an object with contents of html markup in it, for example: string
I need a function that will clean a strings' special characters. I do NOT
I have thousands of HTML files to process using Groovy/Java and I need to
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
I am trying to loop through a bunch of documents I have to put

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.