spring+jaxws: is there a better way than static variables to keep global status?

146 views Asked by At

I have a webservice (cxf) which creates a new Thread each time a time-consuming method is invoked, returning an ID to the client, passed as a token to another web method to check that specific thread's execution state:

public String doWork(){
    String id = /***randomnly generates an ID****/
    executor.execute(**some runnable**);

   // need to save the guy above
   return id;
}

public String checkStatus(String id){
    /* Here I would basically access to an hashmap
       of tasks, pick the one identified by that ID
       and check its state */
}

My problem, as you can see above, is to keep a reference to the task(s) so that I can track its execution. Idea I came up with is the following:

@Webservice
public class MyService{
    private static HashMap<String, Future> futures = new HashMap<String,Future>();

But is there some better way?Moreover what could be the possible drawbacks of this choice?

2

There are 2 answers

1
mmaynar1 On

Another alternative for storing global state is using a database. Not knowing all the details of your application, the only thing that comes to mind is that depending on how they're used static variables can have issues with thread safety.

0
David J. Liszewski On

It helps to know a few things about the underlying programming model of Java EE servlets, upon which JAX-WS and such are built. This answer explains things well.

To retain information associated with a client for the duration of a session, you can obtain the session in the body of your method and store information in it:

Message message = PhaseInterceptorChain.getCurrentMessage();
HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
HttpSession  session = request.getSession(true);
session.setAttribute("id", id);

Upon subsequent method invocations you can retrieve session data in the same manner.

A really basic (ancient) tutorial: Maintaining Client State.