I have a service class that adds elements to a set and there is a scheduled job method that executes after every 2 seconds which reads all the elements added to the set (the one in which service adds elements) and at the end, it clears the whole set.
I am confused if some element gets added to the list between I am reading the data from the set or between the time after I am done reading data from the set and before clearing the set then that element will be lost.
How can I make sure no element gets added to the set while the scheduled job is not finished?
EventService.java
public void foo(){
eventSet.add(new Event("event description"));
}
EventJob.java
@Autowired
EventService eventService;
@Scheduled(cron = "${cron.expression.for.every.2.second}")
private void job(){
for(Event event : eventService.getEventSet()){
//process event
System.out.println(event);
}
eventService.getEventSet().clear();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…