• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reusing an object  RSS feed

 
Omar Nassar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all,
I have red alot that says you have to reuse an object when ever you can.

I have applied this



running this code will produce this output??

Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]
Employee [id=10, name=j]

if we moved the object creation into the for loop, it will work as expected.
how can we get benefit from reusing an object in such a case?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omar Nassar wrote:
I have red alot that says you have to reuse an object when ever you can.


how can we get benefit from reusing an object in such a case?



In order to reuse an object, you have to be finished using it (with the previous data) first. In your case, you still need the object (it is referenced by the list), so reusing it doesn't make sense.

Henry
 
Omar Nassar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so reusing an object applied in case there is no another reference to the object?
 
Praful Thakare
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

Object reuse is generally done using object pool.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain more about the object pool; that may be a level too advanced for the current thread.

What is happening is that you are creating one object, then changing its state repeated. You add the same object to the List ten times, so you have ten references to the same object. Since they all point to the same object they all have the same state. You are printing the state after the loop runs ten times, so you get the tenth update.
Suggest: go back to your original code and print the sate of the List inside your loop. Then you can see the List enlarge and the values increase from 1 to 10.
By the way: you can do this in the loop: System.out.println(empList);
 
Praful Thakare
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:object pool; that may be a level too advanced for the current thread


I agree, the author of the question seems to be at initial level of learning java.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omar Nassar wrote:hello all,
I have red alot that says you have to reuse an object when ever you can. . . .
Please show us where you saw that. We like to know sources; in this case for the reason shown after the third •
Alexander Pope wrote:A little learning is a dangerous thing;
  Drink deep, or taste not the Pierian spring.
I suspect that advice may have been given by people with a “little learning”. With a bit more learning, you find that it is dangerous to have two references to the same mutable object. That problem does not apply to immutable types like java.lang.String. Nor does it occur with primitives, e.g. an int. As you see, you only have one object and every reference to that reflects the changes.

Two ways you can solve the problem. One is to copy the object. Let us start by doing what you uoght to have done with the Employee class. Give it a constructor.Now, I am going to enhance it with a copy constructor. That takes an object of the same class and sets up the current object to be identical, but a different object. I am using this(id, name); to mean, “Call the constructor in the same object which can take id and name as its parameters.”Now, you can change your loop to read like this:-
empList.add(new Employee(emp)); // change line 34 only.
Now see what happens.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote: . . .
Two ways you can solve the problem.
. . .
And here is a second way to do it.

Make the Employee class immutable. Any changes are reflected by making a new object.It is very bad to call the methods setXXX, but I have left it so you can see how little needs to be changed:-
  • 1: Class now final.
  • 2: Both fields now final.
  • 3: No need to copy the fields because they are immutable or primitives.
  • 4: Every field is initialised in the constructor.
  • 5: No fields can be changed.
  • 6: Methods which appear to change state actually create a new object.
  • Now change your line 34 to this:-
    empList.add(emp.setID(...).setName(...));
    You are now adding ten different objects to the List and you can see that when you print the List.

    General Warning: If you have two references to the same mutable object, it is only a matter of time before something goes seriously wrong.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Not sure I understand the last post, but I was trying to say that reusing mutable objects is not necessarily as good an idea as OP has been told. I called object reuse dangerous, if the object is mutable. We have seen strange behaviour in thsi thread with reused mutable objects. You can find the converse of that in books like Joshua Bloch's Effective Java. When Tim Cooke noticed the recommendation about defensive copies, it was exactly the same warning against reusing objects, only from the other direction.

    I would be very interested to know where the original idea came from.
    Of course, see what it says about String
    API Documentation, first page wrote: Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.
     
    Bear Bibeault
    Author and ninkuma
    Marshal
    Posts: 66306
    152
    IntelliJ IDE Java jQuery Mac Mac OS X
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Not sure I understand the last post, but I was trying to say that reusing mutable objects is not necessarily as good an idea as OP has been told.

    This. This. This.

    Unless there is really really really good reason to do this, just don't.

    The phrases "A friend told me ..." or "I read somewhere ..." always raise a red flag. Not everything someone tells you, or that you read (especially in one place -- where is the "a lot" that you cited?), is true.
     
    Chris Barrett
    Bartender
    Posts: 321
    24
    Eclipse IDE Firefox Browser
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi Omar,

    To back pedal a little, in case this point was missed, before you can jump into a conversation about Object Pools and the immutable vs mutable object, it's important to understand the differences between primitives in an ArrayList and object references in a ArrayList. If you are not sure why your output happened like it did in the first place, this Campfire Story should help.

    I think it's important to know the reason why something happens like it does before you can start looking for the solution. I apologize if you already understand this concept.

    Cheers!
    Chris
     
    Ulf Dittmer
    Rancher
    Posts: 42972
    73
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Object pools have fallen largely out use for simple objects that have no associated other resources (like threads or network connections). The main reason is that object creation has become much less expensive over time due to improvements in the JVM - to the point where avoiding object creation for performance reasons generally no longer makes sense.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Chris R Barrett wrote: . . . the differences between primitives in an ArrayList and object references in a ArrayList. . . .
    Can you put primitives into an ArrayList? Surely they are boxed to the corresponding wrapper objects. But those wrappers are all immutable.
     
    Chris Barrett
    Bartender
    Posts: 321
    24
    Eclipse IDE Firefox Browser
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Can you put primitives into an ArrayList?

    Valid point. I should have been more specific in my response.

    Primitives in an ArrayList == bad/not possible. Objects references of primitive wrapper classes in an ArrayList == good.

    Cheers!
    Chris
     
    Omar Nassar
    Greenhorn
    Posts: 26
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you all, i am very glad to see all these discussions.
    this is one source.
    Object Reuse section, says
    objects are expensive to create. Where it is reasonable to reuse the same object, you should do so.

    and there is alot of sources that says the same thing. :P

    I understand the reason why this happens, and I know how to solve it, but as I told you How to get benefit of object reusing.
    Another points are welcome also, even if I know these points, it is good to refresh them.
     
    Matthew Brown
    Bartender
    Posts: 4568
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It's worth noting that book dates from 2000. Java has changed a lot in that time - as Ulf says, object allocation is not as expensive as it used to be.

    I would also add - that book is about performance tuning. Tuning is what you do when you have a working solution and you know - because you've measured it - that you need to speed things up. Until you can demonstrate that your application is too slow it's much more important to have a clear solution. And the example this thread started with, and the confusion it caused you, is a good example of how trying to minimise the number of objects you create might lead to a less clear solution. Sounds like premature optimisation to me.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The bit about objects being expensive to create is simply wrong. It might have been correct 15 years ago but it isn't now. Especially for very short-lived objects only referred to as local variables, which may never need garbage collection when they go out of scope (Java6+ only).
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!