英文:
how multiple thread share same object in java
问题
目前我正在学习Java中的并发编程。
以下是我要解释的疑问 -
这里我正在使用它们的ID从数据库中获取两个对象。(使用Spring Boot + Hibernate)
object object1 = getObjectFromDataBaseUsingId(id1);
object object2 = getObjectFromDataBaseUsingId(id2);
1. 如果两个ID相同,这两个对象是否引用堆中的同一对象?
2. 在哪种情况下,它们将始终引用堆中的同一对象。
当我使用下面解释的一些getter和setter方法进行检查时,我发现对一个对象所做的更改会反映到另一个对象。
//打印object2的任何属性
print(object2.getSomething());
//更改object1的该属性
object1.setSomething(某个值);
//再次打印object2的该属性
print(object2.getSomething());
3. 如果我们在不同的线程中获取这些对象怎么办?更改是否会像在一个线程中对这个对象所做的更改一样总是反映到不同线程中的其他对象上。
(请详细解释第4个疑问,并建议一些相关文章。)
英文:
Currently i am learning concurrency in java.
below is my doubt which i trying to explain here--
here i am fetching two object from datatase using their id.(using spring boot +hibernate)
object object1=getObjectFromDataBaseUsingId(id1);
object object2=getObjectFromDataBaseUsingId(id2);
- are both objects referencing the same object in heap if both id are same??
- in which case they will be always referencing the same object in heap.
when i checked it using some getter and setter method as explained below,i got that changes made in one object reflecting to other object.
//print any property of object2
print(object2.getSomething());
//change that property of object1
object1.setSomething(some value);
//again print that property of object2
print(object2.getSomething());
- what if we are fetching these objects in different-different thread ??. will same things apply here that changes made in one thread to this object will always reflect to other objects in different threads.
(please explain 4th doubt in more details and suggest some article about it)
答案1
得分: 1
Hibernate执行一种称为“唯一化”的操作。在一个Hibernate会话中,当您要求Hibernate检索对象时,与实体类对应的每个数据库记录将由同一个实例表示。这就是Hibernate的一级缓存。
只要会话仍然活动,直到您明确从会话中移除该对象,例如调用session.detach(object)
或session.clear()
,这一点就成立。
对于第3点,您还需要考虑通常的Java内存模型注意事项。您应该阅读有关内存屏障的信息,即Java的“happens-before”条件。
英文:
Hibernate performs a kind of "uniquing". In one Hibernate session, each database record corresponding to an entity class will be represented by the same instance when you ask Hibernate to retrieve that object for you. This is the Hibernate first level cache.
This is true as long as the session is alive until you explicitly remove the object from the session, for example calling session.detach(object)
or session.clear()
.
For point 3., you additionally need to take the usual Java memory model considerations into account. You should read about memory barriers there, namely Java's happens-before
conditions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论