High Java memory usage even for small programs

I see similar questions to this asked frequently and I have yet to see a satisfactory answer.

The answers I see most frequently are angry “why do you care?” answers. Some people put a lot of thought and effort into making the question and whoever asks it seem stupid.

Some people will answer this question with a long diatribe about the different kinds of memory Java allocates, why it does so, and what command line parameters you should look into. (rarely does anyone get very specific)

The fact is that for small utilities Java is a memory hog on most operating systems. The smaller the utility, the more obvious it really is. Java developers have long been conditioned to deal with or ignore this fact.

The reasons for the seemingly abnormal memory usage are plentiful. Each thread gets a certain amount of memory for it’s stack. There are several threads that will get started regardless of how simple a program is for things like garbage cleanup, RMI, etc. On Windows/64-bit that’s 1MB per thread. A bunch of classes get loaded by default and all of your classes. I’m sure a lot of other things are happening behind the scenes.

Java has made tradeoff choices that other languages haven’t. The load time is slower than most other languages. The initial memory requirement is higher. Strings as they are most commonly used eat up a lot more memory than most people realize. There are countless others. The benefit for many situations really does pay off. Something like Hello World shows off the cost of those choices more than anything else. Benefits like easy multi-threading and near-native performance really don’t do you any good with Hello World.

Unfortunately, there’s not a lot that you can do to really minimize the memory used by a simple application. There are the aforementioned command line switches and trial and error could shrink your reported usage down to the ~10-15mb level I’m sure, but those choices and time you spend figuring them out aren’t going to be applicable to a wide variety of future applications. You’ll have to go through the same process again for the next application. Throw in a GUI interface and some logging and another common library or two and your base number will shoot up to 60mb pretty darn quick.

You aren’t doing anything wrong. It’s just the way things work in Java. You’ll get used to it. You’ll choose another language on occasion because of it, and that’s OK too.

Leave a Comment