rimsky
rimsky

Reputation: 1193

Is it okay to manage scheduled jobs with Servlet state?

My web app needs to allow users at different locations to possibly schedule one data import job per location. Each job may take a long time to complete. There can be multiple users at a location who may simultaneously schedule the job (using different schedules), in which case, the schedule last submitted wins out. Schedules can be canceled and modified at any time. Also, new locations (and their schedules) may be added at any time. I'm using JDK 1.6 and raw servlets.

My plan below seems full of red flags given thread safety issues and the dependence on servlet state.

Plan:

  1. Use ScheduledExecutorService to schedule jobs in the init() method of a servlet. A ServletContextListener is the generally recommended place to schedule a job, but given that an HttpRequest may arrive to change the schedule of a existing job, it seems like I need to:

  2. Track the scheduled job threads in the servlet using a member variable map<location, ScheduledFuture<?>>. I know that keeping state in a servlet is considered BAD, but in my case, it seems needed so that I can:

  3. Cancel a scheduled job thread and reschedule it when requested by the user by using the known location as a key to the map above. This part seems to require synchronized blocks but the block should execute quickly and simultaneous access should be limited to a handful of users. Does this seem like a valid use case for using synchronization?

Is it okay to manage scheduled jobs with Servlet state? What holes do you see in my plan and what would be better way to do what I want?

Thanks!

Upvotes: 1

Views: 138

Answers (1)

Monica Granbois
Monica Granbois

Reputation: 7212

Instead of doing the work in the servlet, do it in an offline process (program that is not part of the web-app) instead. Have the servlet simply act as the triggering mechanism for the offline process. There are multiple ways to accomplish how the triggering process is done (file transfer, shared database, messaging or remote procedure invocation). See enterprise integration patterns as a starting point.

The benefits of having the processing in an offline program are you don't need to manage state in the servlet and it leads to more modular code.

Edit: edited for clarity.

Upvotes: 1

Related Questions