0

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?

1
  • 1
    Can we see more of the code? Is a local variable, or a field? What does setAttribute and getAttribute look like? (Both method signature, content and how it is stored (the declaration of the field). Commented Jun 5, 2009 at 12:24

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

1 Comment

its a not a static or singleton object.
1

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

Comments

0

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

some of it explained in Java multi-threading & Safe Publication

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.