views:

584

answers:

6

i am encountering a weird scenario, Is there a possibility of JVM re-using an already created object when we are initializing a new one and the object count is JVm is very high?

abc a = new abc();
a.setAttribute("aaaa");
.........
a...is no longer being used...and has not yet been garbage collected by the JVM. There are multiple threads creating 5000 instances of class abc..
again, abc a = new abc();
       Sysout(a.getAttribute()); // This prints "aaaa" set for an earlier instance!

Is there a possibility of an instance being re-used.? Has anyone come across this scenario before?

+4  A: 

No. I think this is a bug of yours. Maybe also try with a different JVM version or vendor to see whether those behave as you expect or not.

Lucero
could be that's what i am testing right now!
hakish
+4  A: 

This would constitute a bug in the JVM, but I would consider it very unlikely.

I would say with 99% confidence that your code is simply exhibiting a race condition, such as a thread other than the one you are observing setting the attribute.

Michael Borgwardt
+3  A: 

Objects will not be 'reused'. You can check the following -

  • Do you get an OutOfMemoryError? If yes, the program can be in an inconsistent state
  • Are you sure that other threads are not modifying your 'a' object?

Note: Updated answer after gid corrected me.

talonx
instance of a is created each time per thread!
hakish
note quite sure the statement 'the JVM can be in an inconsistent state', your program can be in an inconsistent state but the state of the JVM should be just fine
Gareth Davis
@gid: Thank's for pointing that out - that's what I meant originally.
talonx
+3  A: 

The JVM does not re-une objects AFAIK. But the behaviour you are seeing can be explained.

a.setAttribute("aaaa"); and a.getAttribute might be setting a static field, a singleton or a threadlocal in another class, or another thread is changing state.

Marcelo Morales
its a not a static or singleton object.
hakish
A: 

if you are using multithreading you might be encountering what is know as 'stale data'

some of it explained in http://stackoverflow.com/questions/801993/java-multi-threading-safe-publication

Peter
+1  A: 

Depending on where these assignments take place your program may be exhibiting statement reordering: the JVM may be instruction-reordering the assignment statements so they don't execute in the order you coded them. This is part of the Memory Model specification and could point to your program being under synchronized.

See the JSR133 FAQ: http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#reordering

Or section 2 in: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf

An easier explanation begins at 10:40 in this video: http://www.youtube.com/watch?v=1FX4zco0ziY

andygavin