Java 中的构造函数同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12611366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Constructor synchronization in Java
提问by Brian
Someone somewhere told me that Java constructors are synchronized so that it can't be accessed concurrently during construction, and I was wondering: if I have a constructor that stores the object in a map, and another thread retrieves it from that map before its construction is finished, will that thread block until the constructor completes?
某处有人告诉我 Java 构造函数是同步的,因此在构造过程中不能同时访问它,我想知道:如果我有一个构造函数将对象存储在映射中,并且另一个线程在构造之前从该映射中检索它完成后,该线程会阻塞直到构造函数完成吗?
Let me demonstrate with some code:
让我用一些代码来演示:
public class Test {
private static final Map<Integer, Test> testsById =
Collections.synchronizedMap(new HashMap<>());
private static final AtomicInteger atomicIdGenerator = new AtomicInteger();
private final int id;
public Test() {
this.id = atomicIdGenerator.getAndIncrement();
testsById.put(this.id, this);
// Some lengthy operation to fully initialize this object
}
public static Test getTestById(int id) {
return testsById.get(id);
}
}
Assume that put/get are the only operations on the map, so I won't get CME's via something like iteration, and try to ignore other obvious flaws here.
假设 put/get 是地图上唯一的操作,所以我不会通过类似迭代的方式获取 CME,并尝试忽略这里的其他明显缺陷。
What I want to know is if another thread (that's not the one constructing the object, obviously) tries to access the object using getTestById
and calling something on it, will it block? In other words:
我想知道的是,如果另一个线程(显然不是构造对象的线程)尝试使用getTestById
并调用对象来访问对象,它会阻塞吗?换句话说:
Test test = getTestById(someId);
test.doSomething(); // Does this line block until the constructor is done?
I'm just trying to clarify how far the constructor synchronization goes in Java and if code like this would be problematic. I've seen code like this recently that did this instead of using a static factory method, and I was wondering just how dangerous (or safe) this is in a multi-threaded system.
我只是想澄清构造函数同步在 Java 中的进展程度,以及这样的代码是否会出现问题。我最近看到过这样的代码,而不是使用静态工厂方法,我想知道这在多线程系统中有多危险(或安全)。
回答by Gray
Someone somewhere told me that Java constructors are synchronized so that it can't be accessed concurrently during construction
某处有人告诉我Java构造函数是同步的,因此在构造过程中不能同时访问
This is certainly not the case. There is no implied synchronization with constructors. Not only can multiple constructors happen at the same time but you can get concurrency issues by, for example, forking a thread inside of a constructor with a reference to the this
being constructed.
事实并非如此。没有隐含的与构造函数的同步。不仅多个构造函数可以同时发生,而且您可能会遇到并发问题,例如,通过对this
正在构造的引用在构造函数中分叉一个线程。
if I have a constructor that stores the object in a map, and another thread retrieves it from that map before its construction is finished, will that thread block until the constructor completes?
如果我有一个将对象存储在映射中的构造函数,并且另一个线程在构造完成之前从该映射中检索它,那么该线程会阻塞直到构造函数完成吗?
No it won't.
不,不会。
The big problem with constructors in threaded applications is that the compiler has the permission, under the Java memory model, to reorder the operations inside of the constructor so they take place after(of all things) the object reference is created and the constructor finishes. final
fields will be guaranteed to be fully initialized by the time the constructor finishes but not other "normal" fields.
线程应用程序中构造函数的一个大问题是,在 Java 内存模型下,编译器有权对构造函数内部的操作重新排序,以便它们在(所有事情)创建对象引用和构造函数完成之后发生。 final
字段将保证在构造函数完成时完全初始化,而不是其他“正常”字段。
In your case, since you are putting your Test
into the synchronized-map and thencontinuing to do initialization, as @Tim mentioned, this will allow other threads to get ahold of the object in a possibly semi-initialized state. One solution would be to use a static
method to create your object:
在您的情况下,由于您将您的内容Test
放入同步映射中,然后继续进行初始化,正如@Tim 所提到的,这将允许其他线程以可能的半初始化状态获取对象。一种解决方案是使用一种static
方法来创建您的对象:
private Test() {
this.id = atomicIdGenerator.getAndIncrement();
// Some lengthy operation to fully initialize this object
}
public static Test createTest() {
Test test = new Test();
// this put to a synchronized map forces a happens-before of Test constructor
testsById.put(test.id, test);
return test;
}
My example code works since you are dealing with a synchronized-map, which makes a call to synchronized
which ensures that the Test
constructor has completed and has been memory synchronized.
我的示例代码有效,因为您正在处理一个同步映射,它进行调用以synchronized
确保Test
构造函数已完成并已进行内存同步。
The big problems in your example is both the "happens before" guarantee (the constructor may not finish before Test
is put into the map) and memory synchronization (the constructing thread and the get-ing thread may see different memory for the Test
instance). If you move the put
outside of the constructor then both are handled by the synchronized-map. It doesn't matter what object it is synchronized
on to guarantee that the constructor has finished before it was put into the map and the memory has been synchronized.
您的示例中的大问题是“发生在之前”保证(构造函数在Test
放入映射之前可能无法完成)和内存同步(构造线程和获取线程可能会看到Test
实例的不同内存)。如果移动put
构造函数的外部,则两者都由同步映射处理。它在哪个对象上并不重要synchronized
,以保证构造函数在它被放入映射之前已经完成并且内存已经同步。
I believe that if you called testsById.put(this.id, this);
at the veryend of your constructor, you may in practice be okay however this is not good form and at the least would need careful commenting/documentation. This would not solve the problem if the class was subclassed and initialization was done in the subclass after the super()
. The static
solution I showed is a better pattern.
我相信,如果你叫testsById.put(this.id, this);
的非常构造函数结束时,你可以在实践中是好的但是这不是好的形式,并在至少需要小心注释/文档。如果类被子类化并且初始化是在super()
. static
我展示的解决方案是一个更好的模式。
回答by user207421
Someone somewhere told me that Java constructors are synchronized
某处有人告诉我 Java 构造函数是同步的
'Somebody somewhere' is seriously misinformed. Constructors are not synchronized. Proof:
“某处的某个人”被严重误导了。构造函数不同步。证明:
public class A
{
public A() throws InterruptedException
{
wait();
}
public static void main(String[] args) throws Exception
{
A a = new A();
}
}
This code throws java.lang.IllegalMonitorStateException
at the wait()
call. If there was synchronization in effect, it wouldn't.
此代码抛出java.lang.IllegalMonitorStateException
的wait()
电话。如果同步有效,则不会。
It doesn't even make sense. There is no need for them to be synchronized. A constructor can only be invoked after a new(),
and by definition each invocation of new()
returns a different value. So there is zero possibility of a constructor being invoked by two threads simultaneously with the same value of this
. So there is no need for synchronization of constructors.
它甚至没有意义。它们不需要同步。构造函数只能在 a 之后调用,new(),
并且根据定义,每次调用都会new()
返回不同的值。因此,构造函数被两个线程以相同的值同时调用的可能性为零this
。所以不需要同步构造函数。
if I have a constructor that stores the object in a map, and another thread retrieves it from that map before its construction is finished, will that thread block until the constructor completes?
如果我有一个将对象存储在映射中的构造函数,并且另一个线程在构造完成之前从该映射中检索它,那么该线程会阻塞直到构造函数完成吗?
No. Why would it do that? Who's going to block it? Letting 'this' escape from a constructor like that is poor practice: it allows other threads to access an object that is still under construction.
不,它为什么要那样做?谁会阻止它?让“this”从构造函数中逃脱是一种糟糕的做法:它允许其他线程访问仍在构造中的对象。
回答by Tim Bender
You've been misinformed. What you describe is actually referred to as improper publication and discussed at length in the Java Concurrency In Practice book.
你被误导了。您所描述的内容实际上被称为不正确的发布,并在 Java Concurrency In Practice 一书中进行了详细讨论。
So yes, it will be possible for another thread to obtain a reference to your object and begin trying to use it before it is finished initializing. But wait, it gets worse consider this answer: https://stackoverflow.com/a/2624784/122207... basically there can be a reordering of reference assignment and constructor completion. In the example referenced, one thread can assign h = new Holder(i)
and another thread call h.assertSanity()
on the new instance with timing just right to get two different values for the n
member that is assigned in Holder
's constructor.
所以是的,另一个线程有可能获得对您的对象的引用并在它完成初始化之前开始尝试使用它。但是等等,考虑这个答案会变得更糟:https: //stackoverflow.com/a/2624784/122207...基本上可以重新排序引用分配和构造函数完成。在引用的示例中,一个线程可以在新实例上分配h = new Holder(i)
和另一个线程调用h.assertSanity()
,时机恰到好处,n
以便为在Holder
的构造函数中分配的成员获取两个不同的值。
回答by irreputable
constructors are just like other methods, there's no additional synchronization (except for handling final
fields).
构造函数就像其他方法一样,没有额外的同步(处理final
字段除外)。
the code would work if this
is published later
如果this
稍后发布,代码将起作用
public Test()
{
// Some lengthy operation to fully initialize this object
this.id = atomicIdGenerator.getAndIncrement();
testsById.put(this.id, this);
}
回答by Vipin
Although this question is answered but the code pasted in question doesn't follow safe construction techniques as it allows this reference to escape from constructor, I would like to share a beautiful explanation presented by Brian Goetz in the article: "Java theory and practice: Safe construction techniques" at the IBM developerWorks website.
虽然这个问题得到了回答,但粘贴有问题的代码不遵循安全构造技术,因为它允许这个引用从构造函数中逃脱,我想分享一个由 Brian Goetz 在文章中提出的漂亮解释:“Java 理论和实践:安全构建技术”,位于 IBM developerWorks 网站。
回答by Dmitry Komanov
It's unsafe. There are no additional synchronization in JVM. You can do something like this:
这是不安全的。JVM 中没有额外的同步。你可以这样做:
public class Test {
private final Object lock = new Object();
public Test() {
synchronized (lock) {
// your improper object reference publication
// long initialization
}
}
public void doSomething() {
synchronized (lock) {
// do something
}
}
}