3

I want to create proper stateless services, i.e., beans with singleton scope, but sometimes state creeps in. Current candidates in the application I work on are

  • caching data
  • keeping Futures for scheduled tasks around to be able to cancel them on demand later

A simplified example service for the Futures could be

class SchedulingService {
  @Autowired
  TaskScheduler scheduler;

  Map<String, ScheduledFuture> scheduledEvents = new HashMap<>();

  public void scheduleTask(String id, MyTask task) {
    if (scheduledEvents.containsKey(id)) {
      scheduledEvents.remove(id).cancel(false);
    }
    persistTask(task)
    scheduledEvents.put(id, scheduler.schedule(task, task.createTrigger()));
  }

  void persistTask(MyTask task) { /* persist logic here */ }
}

I'm sure requirements like these will pop up all the time. Since the data that should be kept in memory doesn't have to be persisted because it is just derived information from data in the database, is it acceptable to keep state this way? And if not is there a better way of doing this?

musiKk
  • 14,751
  • 4
  • 55
  • 82
  • I'm for the pragmatic approach, and really don't think there's a difference between keeping state in DB or in a cache on the bean. Always be aware of premature optimization though! – Anders R. Bystrup Mar 07 '14 at 10:28
  • 1
    A cache without state would suck. You need to handle synchronization, though. – Dave Newton Mar 07 '14 at 10:29
  • I think there are exceptions to every rule; this seems fine. Be aware that your implementation is not thread safe - this could be somewhat dangerous as you obviously have threads involved. – Boris the Spider Mar 07 '14 at 10:33
  • @Dave: True. I was merely asking in case there was some `SpecialStatefulServiceThingamabob` I don't know about. Spring is effing huge. I guess this implementation would still be bad for clustering but this is currently of no concern. – musiKk Mar 07 '14 at 10:44
  • Now, if someone would put this up as an answer, I'd be happy to accept that. It would be a shame if I had to answer my own question based on your comments. – musiKk Mar 10 '14 at 08:32
  • By "volatile state" you really mean *mutable* and/or *non-persistent* state, not to be confused with `volatile` (keyword) semantics in the Java memory model. I wouldn't *recommend* it, for all of the reasons already given (thread-safety, persistence in the event of failure, behavior in a cluster of N>1 instances). But, on a case-by-case basis it could be considered *acceptable* based on whether those concerns are mitigated for your particular needs. Fundamentally, a cache in memory is just as stateful as a SQL database. The devil is in what you trade off one vs the other. – William Price Apr 18 '14 at 06:08

0 Answers0