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:
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:
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: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!