OnJava8-Examples/concurrent/SynchronizedConstructor.java

29 lines
718 B
Java
Raw Normal View History

2017-01-15 16:00:44 -08:00
// concurrent/SynchronizedConstructor.java
// (c)2021 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; }
2017-01-15 16:00:44 -08:00
}
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
*/