Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do multiple threads Using the same object in java make a copy of it?

How do multiple threads in Java handle working with a single object reference passed to them?

Do they make a copy of the object and then use it, or do they use the same one?

Any technical explanation is welcome.

I am unable to comprehend this in the context that if the threads pass some data to the object and go to sleep, while one is asleep another thread uses the same object passes data to it and goes to sleep.

Will the last data overwrite the previous one in the object?


1 Answers

You can look at java memory model. You see all objects are stored in Heap memory, which is shared across whole application. Every thread shares the same heap space, but also they have own stack memory where they store their reference to the objects. So if one threads works on object, it have his own reference to this object, but this reference is pointing to the object in heap space, which every thread will see. So to answer to your question, if second thread will do something on the object, and then go to sleep or even die, the previous thread while wake up will see those changes, because its reference is pointing to same object.

I've found interesting image which can help you understand:

http://tutorials.jenkov.com/java-concurrency/java-memory-model.html

image from: http://tutorials.jenkov.com/java-concurrency/java-memory-model.html

like image 187
Kamil Banaszczyk Avatar answered Jun 16 '26 03:06

Kamil Banaszczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!