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
Future
s for scheduled tasks around to be able to cancel them on demand later
A simplified example service for the Future
s 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?