Alex Dowining
Alex Dowining

Reputation: 970

global vs local (variables and lists) by byte consumption JAVA

I' trying to create a web site and some times I got the PermGen exception.
So I started searching for ways to reduce the amount of created objects and also to reduce the memory consumption.

I read some articles. But I'm not sure about some things.
For example, is it better to declare lists outside of a method (global), or to create them inside a method? What's the difference in terms of memory consumption in this case? If I declare them as local that means that after they are used the garbage collector will collect them and thus will release space at the heap?

Can anyone propose ways to reduce more memory consumption and to reduce the amount of created objects (is @Autowired a better way to declare on object)?

Upvotes: 2

Views: 1492

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533620

There is no difference between static or non-static data in terms of usage. They use the same amount on the heap.

If you are running out of PermGen, you either need to

  1. load less classes
  2. increase the Maximum PermGen Size e.g. -XX:MaxPermSize=256m

Upvotes: 1

matt freake
matt freake

Reputation: 5090

If you are getting an Out-of-memory exception regarding PermGen, then reducing the number and size of your objects most likely won't help (because they will be taking up space in the Heap, not your PermGen)

This answer PermGen Out of Memory reasons should help with the causes of PermGen problems

Upvotes: 5

Simulant
Simulant

Reputation: 20112

All local variables can be collected from Garbage collector as soon as the block of declaration is finished. So this is the better way for memory recycling.

Upvotes: 0

Brainbot
Brainbot

Reputation: 365

Global and local variables both take up the same amount of memory, the difference is when they go out of scope and thus get eligible for gargabe collection. A global variable will not go out of scope, whereas a local one will go out of scope as soon as it's "block" (a method or a loop for example) is finished. If there is no reference to this variable now, it will get deleted by the garbage collector.

As a rule of thumb always try to put variables in the lowest possible scope, this will free up variables when they are not in use anymore. You should try to reuse variables too if you can.

Here is a small article about scope, one about how the java garbage collector works and another which kind of collector to use.

Upvotes: 3

Related Questions