Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object Reuse

Tags:

Should Java Objects be reused as often as it can be reused ? Or should we reuse it only when they are "heavyweight", ie have OS resources associated with it ?

All old articles on the internet talk about object reuse and object pooling as much as possible, but I have read recent articles that say new Object() is highly optimized now ( 10 instructions ) and Object reuse is not as big a deal as it used to be.

What is the current best practice and how are you people doing it ?

like image 507
Sid Datta Avatar asked Dec 30 '08 20:12

Sid Datta


People also ask

Can you reuse an object in Java?

A feature of Java that makes it an extremely useful language is the ability to reuse objects.

What is reusable object in Java?

An object can always be reused if it is immutable (Item 15). As an extreme example of what not to do, consider this statement: String s = new String("stringette"); // DON'T DO THIS! The statement creates a new String instance each time it is executed, and none of those object creations is necessary.

Can objects be reused?

An object that is immutable can always be reused and handed between threads, this is because its fields are final and set by the constructor which ensures complete visibility.


1 Answers

I let the garbage collector do that kind of deciding for me, the only time I've hit heap limit with freshly allocated objects was after running a buggy recursive algorithm for a couple of seconds which generated 3 * 27 * 27... new objects as fast as it could.

Do what's best for readability and encapsulation. Sometimes reusing objects may be useful, but generally you shouldn't worry about it.

like image 185
Esko Avatar answered Sep 29 '22 16:09

Esko