问题
My application wants to communicate with a REST server. At first, we need to authenticate and in response to that, we will receive a client token. This token is valid for 30 minutes and for the rest of the communication this client token needs to be present as a header.
I am planning to implement a Singleton Class that handles the REST communication. Reson for not following an ENUM approach (as mentioned in many other threads) is because of the requirement to make a rest call and populate the client token in runtime.
public class RESRService {
private static RESRService RESTSERVICEINSTANCE;
private String clientToken;
private RESRService(){
clientToken = //make a rest call to authenticate and get the client
//token from reponse
}
public static RESRService getInstance(){
if(RESTSERVICEINSTANCE == null){
RESTSERVICEINSTANCE = new RESRService();
}
return RESTSERVICEINSTANCE;
}
public void makeRestCall(String requestSpecificInfo){
//set client token to header
//create JSON body using requestSpecificInfo
//make rest call
}
}
The main challenge here is that this class will be used by multiple threads at the same time (client token is the same for all threads). My doubt is about the initialization part where we make a REST call to populate client token. Is there any possible chances of ambiguity here between threads if the REST call takes a couple of seconds to set the client token. If yes, what do you think is the best way to implement this?
回答1:
If you have a multithread application and use singleton pattern, you can use synchronized keyword.
public static synchronized RESRService getInstance(){}
But getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously and all operation is synchronized. So you can use Double checked locking solution.
private static volatile RESTSERVICE RESTSERVICEINSTANCE;
public static RESTSERVICE getInstance(){
RESTSERVICE restservice = RESTSERVICEINSTANCE;
if(restservice == null){
synchronized (RESTSERVICE.class){
restservice = RESTSERVICEINSTANCE;
if(restservice == null){
restservice = new RESTSERVICE();
}
}
}
return restservice;
}
来源:https://stackoverflow.com/questions/56232753/using-java-singleton-instance-in-a-multi-threaded-environment