Search code examples
javamultithreadingweb-servicesjax-wssynchronized-block

Why are WebMethods blocked when threads are synchronized?


Please see my code example of a JAX-WS Webservice:

@WebService
public class ClassA {

@WebMethod
public synchronized void doSomething() {
    new Thread(new Runnable() { // Thread X
        @Override
        public void run() {
            synchronized (ClassA.this) {
                // Do something which should be run in this separate
                // thread, but not twice at the same time
                try {
                    System.out.println("Thread X Start");
                    Thread.sleep(10000);
                    System.out.println("Thread X End");
                } catch (InterruptedException e) {
                }
            }
        }
    }).start();
}

}

If the WebMethod is called twice, the second call is waiting for thread X to complete - why?


Solution

  • The problem is that you have synchronized also doSomething. This should definitely be removed as it prevents multi-threading in your webservice. For the inner synchronized block, I would also remove it and try to use a single-Thread ThreadPool so that the jobs are executed one at a time.

        // Initiate you thread pool and make sure it is unique
        ExecutorService service = Executors.newFixedThreadPool(1);
    
        ...
        // In your web method:
        Future<?> futureResult = service.submit(new Runnable()/or new Callable());
        // Using callable, you will get a Typed Future
    
        Object result = futureResult.get();// If you need to wait for the result of the runnable/callable.
        ...
    

    This is available since Java 1.5