lundi 5 mars 2018

Make getInstance method thread safe in java

I am creating an application which acts as a Rest App and a Rest/SOAP client as well. So I get some information from the Rest request and make subsequent calls to Third Party Rest/Soap servers. While doing this, I am creating certain DTOs which can carry my Data from one layer to another. However, in that process I do not want them to be passed as parameters. Hence I created an implementation like this.

public class PersistDTO {
private static DTO1 dto1;
private static DTO2 dto2;
public static DTO1 getDTO1() {
if(null != dto1)
return dto1;
//else create new object and return
}
//Same for DTO2
}

I am doing it in this so that once I set values to DTO, I can use them wherever I wish. Kind of session variable I suppose. Now the issue I have is the method which shall be using this piece is called by multiple threads. Which makes my implementation vulnerable to be changed by Multiple Threads.

public class foo{
//Rest Annotations
public Response getRestReq(String params){
  //do some validations
  //Create a Queue say "que" of some size eg. 30
  while(!que.siEmpty()){
   Thread t = new Thread(()->{
     //populate DTO
     //Does a lot of stuff and use DTO values
    });
    t.start()
    }
  }
}

I am not much acquaint with multi-threaded application implementations. Any help is very much appreciated. Thanks

Aucun commentaire:

Enregistrer un commentaire