2017-01-15 16:00:44 -08:00
|
|
|
// concurrent/SynchronizedConstructor.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 MindView LLC: see Copyright.txt
|
2017-01-15 16:00:44 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://OnJava8.com for more book information.
|
|
|
|
import java.util.concurrent.atomic.*;
|
|
|
|
|
|
|
|
class SyncConstructor implements HasID {
|
|
|
|
private final int id;
|
2017-01-18 16:10:15 -08:00
|
|
|
private static Object
|
|
|
|
constructorLock = new Object();
|
2017-05-01 14:33:10 -06:00
|
|
|
SyncConstructor(SharedArg sa) {
|
2017-01-15 16:00:44 -08:00
|
|
|
synchronized(constructorLock) {
|
|
|
|
id = sa.get();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public int getID() { return id; }
|
|
|
|
}
|
|
|
|
|
|
|
|
public class SynchronizedConstructor {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Unsafe unsafe = new Unsafe();
|
2017-01-18 16:10:15 -08:00
|
|
|
IDChecker.test(() ->
|
|
|
|
new SyncConstructor(unsafe));
|
2017-01-15 16:00:44 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
0
|
|
|
|
*/
|