I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance()
. So I have coded it in the following way
public class SomeService implements Provider<String, Claims>{
private SomeService(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
// single instance
private static SomeService instance = null;
private String a;
private static AtomicInteger initialized = new AtomicInteger();
private static CountDownLatch latch = new CountDownLatch(1);
private String b;
private String c;
public static SomeService getInstance(String a, String b, String c) {
if ( initialized.incrementAndGet() == 1) {
instance = new SomeService(a, b, c);
latch.countDown();
} else {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return instance;
}
// Other implementation code
}
My intention (as well as understanding about this) is that:
When a thread calls
getInstance
it will atomically increment and check whehther it's desired value.If not, it will wait for the other thread to open the latch which means initialization is in progress.
It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {}
block but I was wondering if this makes sense at all.