0

I created a really simple application for requesting items, tools and what not. I used a database to keep all this information stored. My requisition manager class uses a getter which return a new instance of the requisition using information from the database. Will this new object in on the stack forever? How can I force it to get collected? How can I make this better, as in how can I write the function without creating a new object?

public static Requisition getRequisition(int id) {
  //logic for getting the correct id and so forth
  return new Requisition(id, /*logic for name*/, /*logic for price and other fields*/);
}
NChitty
  • 13
  • 3

1 Answers1

1

Unless this has been identified as a performance issue, I wouldn't worry about it. The java garbage collector is very effective at cleaning up after you.

Objects in java are never stored on the stack, only ever in the heap. references may be placed on the stack, and they'll be gone the moment they go out of scope. The object created will be garbage collected in the first collection pass after the last reference to it is lost.

Without seeing the function, and how it's implemented currently it's very hard to advise how to improve this. As a first thought however it may be possible to use a singleton object and have the getter update its values. Though this could cause issues elsewhere, if the object is assumed to not change after fetching.

Leliel
  • 156
  • 6
  • -how to improve this:- Better don't to think about it. The singleton idea could be a big problem, better forget it. Allocation objects without caring about them is the normal Java way. No optimization are needed except in very rare cases (and then I'd suggest caching by `id`). – maaartinus Oct 30 '13 at 10:47