The time-out triggering algorithm based on the ring queue only needs a timer to trigger the batch timeout task, which is low CPU consumption and high efficiency. The following is a simple implementation of this algorithm.
1,taskholder.java
package com.zws.timer;/** * * @author wensh.zhu * @date 2018-04-22 */public class taskholder {/** the number of laps to wait for a task, that is, the task needs to walk a few laps **/private int Cycles;private int delays;private runnable task;public taskholder () {}public taskholder (Int cycles, int delays, runnable task) {this.cycles = cycles;this.delays = delays;this.task = task;} Public boolean istimeout () {return cycles <= 0;} Public void cutdown () {cycles --;} Public int getcycles () {return cycles;} Public void setcycles (Int cycles) {this.cycles = cycles;} Public int getdelays () {return delays;} Public void setdelays (Int delays) {this.delays = delays;} Public runnable gettask () {return task;} Public void&nBsp;settask (Runnable task) {this.task = task;} @Overridepublic string tostring () {return "taskholder[cycles=" + cycles + ", delays=" + delays + "]";}}
2,timercontext.java
package com.zws.timer;import java.util.map;import java.util.queue;import java.util.concurrent.concurrenthashmap;import java.util.concurrent.concurrentlinkedqueue;/** * * @author wensh.zhu * @date 2018-04-22 */public class Timercontext {public static final int default_ticks = 60;public static final int DEFAULT_TICK_DURATION = 1;private Map<Integer, Queue< taskholder>> taskholders;private volatile int currenttick = 0;/** Tick lap length **/private int ticks = DEFAULT_TICKS;/** time interval per tick, unit: Seconds **/private int tickduration = default_tick_duration;public timercontext () {init ();} Public timercontext (int ticks, int tickduration) {if (ticks <= 0) Throw new illegalargumentexception ("ticks must be greater than 0 ");if (tickduration <= 0) throw new IllegalArgumentException ("tickduration must be greater than 0"); this.ticks = ticks;this.tickduration = tickduration;init ();} Private void init () {taskholders = new concurrenthashmap<integer, queue <TaskHolder>> (;for ) (int i = 0; i < ticks; i ++) Taskholders.put (i, new concurrentlinkedqueue<taskholder> ());} /** * Add a timed task and calculate the number of laps to walk and index * @param task * @param delays */ Public void addtask (runnable task, int delays) {if (task == null) throw new nullpointerexception ("Task must not be null");if (delays <=0) throw new illegalargumentexception ("delays must be greater than 0 ");int allseconds = ticks * tickduration;int cycles = delays / allseconds;int index = (delays % allseconds) / Tickduration) + currentTick; Taskholder metadata = new taskholder (Cycles, delays, task); TaskHolders.get (index ). Add (MetaData);} Public int tick () {currentTick = (currenttick + 1) % ticks;return currenttick;} Public queue<taskholder> getcurrenttasks () {return taskholders.get (CurrentTick);} Public int getcurrenttick () {return currenttick;} Public int getticks () {return ticks;} Public int gettickduration () {return tickduration;} @Overridepublic string tostring () {return "timercontext [timers=" + taskholders + ", ticks=" + ticks + ", tickduration=" + tickDuration+ ", currenttick= " + currentTick + "] ";}}
3,timerscheduler.java
package com.zws.timer;import java.io.ioexception;import java.util.iterator;import java.util.queue;import java.util.timer;import java.util.timertask;/** * is used to determine if the timer is up, perform a task, Maintain timer status. * @author wensh.zhu * @date 2018-04-22 */public class timerscheduler extends timertask {private timercontext timercontext;public Timerscheduler () {}public timerscheduler (Timercontext timercontext) {this.timerContext = timercontext;} /** * timing Detection, if the timer trigger time to delete from the collection and perform the task, otherwise the number of laps minus one. */@Overridepublic void run () {if (timercontext == null) return; Queue<taskholder> timers = timercontext.getcurrenttasks ();Iterator<TaskHolder> itor = timers.iterator ();while (Itor.hasnext ()) {TaskHolder timer = Itor.next ();if (Timer.istimeout ()) {itor.remove (); New threAD (Timer.gettask ()). Start ();} else {timer.cutdown ();}} Timercontext.tick ();} Public void addtask (runnable task, int delays) {timercontext.addtask (task, delays);} Public timercontext gettimercontext () {return timercontext;} Public void settimercontext (Timercontext timercontext) {this.timerContext = Timercontext;} Public static void main (String[] args) throws ioexception {timercontext context = new timercontext (60, 1); Timerscheduler sheduler = new timerscheduler (context); Sheduler.addtask (New Runnable () {public void run () {system.out.println (Dateutils.now ());}}, 60); System.out.println (Dateutils.now ()); Timer timer = new timer (); Timer.scheduleatfixedrate (sheduler, 0, Context.gettickduration () * 1000l); System.in.read ();}}
4,dateutils.java
Package Com.zws.timer;import java.time.localdatetime;import java.time.format.datetimeformatter;/** * * @author Wensh.zhu * @date 2018-04-22 */public class Dateutils {public static final String Default_pattern = "Yyyy-mm-dd HH:mm:ss"; public static String Now () {LocalDateTime time = Localdatetime.now (); return Time.format (Datetimeformatter.ofpattern ( Default_pattern));} public static String plusseconds (int seconds) {LocalDateTime time = Localdatetime.now (); time.plusseconds (seconds); Return Time.format (Datetimeformatter.ofpattern (Default_pattern));}}
Algorithm implementation of efficient triggering of a large number of timeout tasks in ring queue