Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java - How to execute a @Scheduled job in a thread safe manner in SpringBoot?

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want to be added to the set while running the scheduled job means you have to maintain some flags based on some set limits and enable that AtomicBoolean to true when the when you reached the limit "false" once you have cleared the set. Below is the pseudo code,

AtomicBoolean canAddData = new AtomicBoolean(true);

public void foo(){
    if(canAddData){ // here instead of atomicboolean you can use eventSet.size()==10 as well if you want to be added based on some level size.
      eventSet.add(new Event("event description"));
      canAddData.set(eventSet.size() <= 10)
   }
}

// scheduler code 
public void processEvents() {
     Iterator<Event> eventIter = eventSet.iterator()
     while(eventIterator.hasNext()) {
          Event = eventIterator.remove()
          // Process event here and clearing item one by one
     }
     canAddData.set(true)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...