简体   繁体   English

java中多个线程如何共享同一个对象

[英]how multiple thread share same object in java

Currently i am learning concurrency in java.目前我正在学习 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)在这里,我使用它们的 id 从 datatase 中获取两个对象。(使用 spring boot +hibernate)

object object1=getObjectFromDataBaseUsingId(id1);
object object2=getObjectFromDataBaseUsingId(id2);
  1. are both objects referencing the same object in heap if both id are same??如果两个 id 相同,两个对象是否都引用了堆中的同一个对象?
  2. 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.当我使用下面解释的一些 getter 和 setter 方法检查它时,我得到了在一个对象中所做的更改反映到另一个对象。

//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());
  1. 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) (请更详细地解释第四个疑问并建议一些关于它的文章)

Hibernate performs a kind of "uniquing". Hibernate 执行一种“独特”。 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.在一个 Hibernate 会话中,当您要求 Hibernate 为您检索该对象时,对应于实体类的每个数据库记录都将由同一个实例表示。 This is the Hibernate first level cache.这是 Hibernate 的一级缓存。 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() .只要会话是活动的,直到您从会话中明确删除对象,例如调用session.detach(object)session.clear()这就是真的。

For point 3., you additionally need to take the usual Java memory model considerations into account.对于第 3 点,您还需要考虑通常的 Java 内存模型注意事项。 You should read about memory barriers there, namely Java's happens-before conditions.您应该阅读那里的内存屏障,即 Java 的happens-before条件happens-before

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM