Question

I have built a class (call it RecordManager) which manages data on a file system. I would like to make SOAP or REST calls that change the state of this class. However I only want to have one instance of this class running for every call to the server.

How do I create one instance of this class and be able to use it given all JAX-WS or JAX-RS calls? Ideally I would like to just call:

 @GET 
 public ... (...){
      rec_man.update( <parameters passed by call> )
 }

where rec_man is the instance of RecordManager

I'm fairly certain that I have ensured thread safety with this class.

No correct solution

OTHER TIPS

public class RecordManager {
   public static final RecordManager INSTANCE = new RecordManager();
   private RecordManager() {
         // private constructor prevents instantiation
   }
}

Your JAX-WS service or JAX-RS resource would reference RecordManager like this:

 @GET 
 public ... (...){
      ...
      rec_man = RecordManager.INSTANCE;
      rec_man.update( <parameters passed by call> )
 }

Or, if you don't like that style (singleton as a public static instance) you could hide the static instance and expose a static method to obtain it.

public class RecordManager {
   private static RecordManager instance;
   private RecordManager() {
         // private constructor prevents instantiation
   }

   public static RecordManager getInstance() {
       if (instance == null) {
           instance = new RecordManager();
           ... init
       }
       return instance;
   }
}

Your usage becomes:

 @GET 
 public ... (...){
      ...
      rec_man = RecordManager.getInstance();
      rec_man.update( <parameters passed by call> )
 }

Note that if your instantiation logic needs to be threadsafe (e.g. only ever initialize once) then you could make the getInstance method synchronized or one of the techniques described in this article.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top