动态维护执行时机

来源:互联网 发布:社交网络 chris hughes 编辑:程序博客网 时间:2024/06/05 02:33

  看到一段代码,能够动态维护执行时机,使之在大概的时间间隔里面
执行一次。比如一段代码不断运行,我需要在大概800毫秒的时间后执行一次异常操作。如果使用定时任务的方式是实现不了的,因为800毫秒是一个大概的时间,有概率性。废话少说,上代码。

package cn.com.agree.afa.applog.util;/** * This class serves as a gateway for invocations of a "costly" operation on a critical execution path. * */public class InvocationGate {  // experiments indicate that even for the most CPU intensive applications with 200 or more threads MASK  // values in the order of 0xFFFF is appropriate  private static final int MAX_MASK = 0xFFFF;  private volatile long mask = 0xF;  private volatile long lastMaskCheck = System.currentTimeMillis();   // IMPORTANT: This field can be updated by multiple threads. It follows that  // its values may *not* be incremented sequentially. However, we don't care  // about the actual value of the field except that from time to time the  // expression (invocationCounter++ & mask) == mask) should be true.  private long invocationCounter = 0;  // if less than thresholdForMaskIncrease milliseconds elapse between invocations of updateMaskIfNecessary()  // method, then the mask should be increased  private static final long thresholdForMaskIncrease = 100;  // if more than thresholdForMaskDecrease milliseconds elapse between invocations of updateMaskIfNecessary() method,  // then the mask should be decreased  private final long thresholdForMaskDecrease = thresholdForMaskIncrease*8;  public boolean skipFurtherWork() {     //invocation在mask有1的对应的位上也是1,等号成立     return ((invocationCounter++) & mask) != mask;                                                                                                                                                                                                             }  // update the mask so as to execute change detection code about once every 100 to 8000 milliseconds.  public void updateMaskIfNecessary(long now) {      final long timeElapsedSinceLastMaskUpdateCheck =                                                                now - lastMaskCheck;      lastMaskCheck = now;      //执行次数过多了      if (timeElapsedSinceLastMaskUpdateCheck < thresholdForMaskIncrease && (mask < MAX_MASK)) {      mask = (mask << 1) | 1;//mask变大,使得执行的可能性更小,执行次数减少      //执行次数过少了        } else if (timeElapsedSinceLastMaskUpdateCheck > thresholdForMaskDecrease) {      mask = mask >>> 2;//mask变小,使得执行的可能性更大,执行次数增大    }  }}

客戶端的使用

 InvocationGate GATE = new InvocationGate(); if (!GATE.skipFurtherWork()) {                      GATE.updateMaskIfNecessary(System.currentTimeMillis());          if (file.length() >= maxFileSize) {              append = false;          }  }
0 0
原创粉丝点击