• Post Reply Bookmark Topic Watch Topic
  • New Topic

Any concerns with nesting "new" calls  RSS feed

 
Tom Landry
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just wondering if doing something like the following will leave any object dangling out there.

int width3 = new Double(Math.ceil(new Double(0.1 * width))).intValue();

Or is it safe to assume that anytime an object is instantiated but not tied to a variable that the object will be garbage collected sometime afterward.
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java will collect all the unused objects.

You can get a memory leak of sorts if you don't clean up fields that an object isn't going to use anymore. Let's say you have an array in your class, and you fill it with values, and don't need half of the array anymore. If you don't null out those values, or replace the array, then you're going to waste memory.

It's more difficult than in C though. In Java it's not really possible to "lose" memory. Technically every object still knows where all the data they're not using is. In C, when you let a pointer go out of scope, good luck finding out what was in the memory block pointed at.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use javap -c Foo, you find the bytecode differs only slightly from the bytecode when you create those objects and assign them to local variables. somebody had a similar question recently, probably here.
If you use… and compare the bytecode with what you have, you will see the same things, but in a different order. You might do well to try it with Double instead of double throughout, too. As you will see, all those object references appear as local variables, and they will be eligible for garbage collection when they go out of scope.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a rule of thumb you can use (I use it all the time): The Java engineers have been working on garbage collection since the 1990's. If there's something that looks fairly obvious to a beginning Java programmer, you can be certain they already noticed it. And since memory leaks are anathema to garbage collector writers, you can be sure that construct can't be a source of memory leaks.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote: . . . The Java engineers have been working on garbage collection since the 1990's. . . .
And they use principles which were well‑established long before that.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!