动态维护执行时机
来源:互联网 发布:社交网络 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
- 动态维护执行时机
- 关于LINQ执行时机
- finally语句执行时机
- Handler执行时机
- onSaveInstanceState执行时机
- onRestart执行时机。
- jQuery执行时机
- machine start的执行时机
- debug : CoInitialize执行的时机
- oracle后台进程执行时机
- std - locale - global(...) 执行时机
- SpiderMonkey执行JIT的时机
- finally语句的执行时机
- Spring BeanPostProcessor执行时机和Bean的初始化时机总结
- 动态维护凸包
- 动态维护中位数
- 静态构造函数的执行时机
- page类的构造函数执行时机
- error
- Matlab 图像处理 增加图像亮度(曝光度)算法
- HDU 2473——junk mails
- spring在service层和dao层如何获取request和session
- java的动态代理机制详解
- 动态维护执行时机
- Mysql输错命令后如何退出
- 递归算法之斐波那契数列的求项与求和算法
- 制作辉光钟的一些感想
- 挖地雷问题 单向 动态规划
- MFC制作一个可自由添加删除节点的树(CTreeCtrl)类
- poj 2411 Mondriaan's Dream (状态dp)
- VIM快捷(四):修改
- <hr>标签如何设置水平线颜色