eric eric - 1 year ago 43
Java Question

Java Static Synchronized vs BlockingQueue implementation

I'm trying to implement an appointment queue using Servlets (resteasy + Hibernate).
my appointment controller is as follows (simplified of course).

public class AppoController{

public synchronized static int createAppoinment(AppObj app){
//get last app no
//insert new app with no+1
//return new app no

currently this method works fine. but i've read about BlockingQueue implementations which seems the correct way?

Definition of working Fine:

if i dont use synchronized static and send multiple requests at once multiple appointments have same appointment no

but if i use synchronized static, appointments created with correct order

i dont use any threads here but i assume tomcat uses its own threads to server http requests from users.
so this is a multithreaded app?

i have googled it for past few days but the closest i got is Java/Android: Synchronized vs Queue implementation

what i need to clarify are;

- is this the correct way to do this?

- what are the pros and cons of using synchronized static vs BlockingQueue implementation for my scenario.

Any other inputs you seem relevant are also welcome. Thanks.

Answer Source

Your implementation does work. The synchronized method can only be executed by one thread at any time. Tomcat will use multiple threads (the details depend on the current settings, lets assume one thread per request), so every concurrent request will get its own thread and then ever request waits on this methods until its thread is allowed to enter the method.

I see two options depending on your needs.

  1. If the appointment comes from a database, lets the database or hibernate handle the id generation. That would move the multi thread problem to the database which was designed to handle that kind of problem.
  2. If the appointment does not come from a database and you just need a unique identifier for the appointment objects use a UUID, e.g. java.lang.UUID.randomUUID()

Actually using a Queue will only make sense if you want move the creation of the appointment out of the http request. E.g. if you create the appointment after the request finished like a nightly batch job or a dedicated worker thread pool. But this will only make sense if it is a expensive operation to create an appointment.

On a different topic, you should check if this method needs to be static.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download