In fact your factory isn't thread safe, because in race condition you can have more than one ClientFactory living in application. Lets assume two threads:
- ThreadA is evaluating condition 'if (instance == null)' and instance is null, so it enters statement
- ThreadB is evaluating condition 'if (instance == null)' and instance is null (because A didn't make to instantiate it), so it enters statement
- ThreadA creates new ClientFactory() and returns it
- ThreadB creates new ClientFactory() and returns it
- Now we have more than one ClientFactory in application. Of course other threads trying to retrieve instance some time later will always return single instance.
In my opinion the easiest way to write singleton in Java is to use enum. In your case it will looks:
public enum ClientFactory {
INSTANCE;
public Company getClient() {
return new Company();
}
}
And usage:
ClientFactory.INSTANCE.getClient()