0

My java web service has a number of methods offered, each starting a different thread when called (operations include mysql database calls). I want to make sure the operations are executed in the same order they are called, so no thread rushes to complete before the other, effectively having synchronized access to the web service.

What is the best way to implement this ? Are there any smarter ways to do it ? Any tools/pre made solutions/libraries I can use ?

2
  • Why do you want to implement this? In fact your service won't scale any more... if you really need this feature you could simply synchronize on a 'global' object (semaphore, one request at a time).
    – home
    Apr 2, 2013 at 16:11
  • Some methods report data to other parties, if one of these methods sends data before another method completes (considering this other method should have completed first) it sends incorrect data.
    – Flavian
    Apr 2, 2013 at 16:24

2 Answers 2

1

If you really need to execute the services in the exact order invoked, one at a time, then the simplest way to achieve this is to use a queue. Each web service queues a "command pattern" object on the queue, the queue is handled by a single thread that reads commands and executes them, and then returns the results to the waiting thread that originally queued the request.

Before doing this I would re-examine your design, as this requirement will prevent your application from scaling to large numbers of requests.

1

We have implemented this thing using SingleThreadExecutor. You can submit all your requests to SingleThreadExecutor and it will execute them sequentially in proper order.

So each method of your should spawn a new thread which can be executed using SingleThreadExecutor.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.