参考storm中的RotatingMap实现key超时处理
storm0.8.1以后的RotatingMap完全可以独立于storm用来实现hashmap的key超时删除,并调用回调函数
RotatingMap.java:
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry; /**
* Expires keys that have not been updated in the configured number of seconds.
* The algorithm used will take between expirationSecs and
* expirationSecs * (1 + 1 / (numBuckets-1)) to actually expire the message.
*
* get, put, remove, containsKey, and size take O(numBuckets) time to run.
*
* The advantage of this design is that the expiration thread only locks the object
* for O(1) time, meaning the object is essentially always available for gets/puts.
*/
public class RotatingMap<K, V> {
//this default ensures things expire at most 50% past the expiration time
private static final int DEFAULT_NUM_BUCKETS = 3; public static interface ExpiredCallback<K, V> {
public void expire(K key, V val);
} private LinkedList<HashMap<K, V>> _buckets; private ExpiredCallback _callback; public RotatingMap(int numBuckets, ExpiredCallback<K, V> callback) {
if(numBuckets<2) {
throw new IllegalArgumentException("numBuckets must be >= 2");
}
_buckets = new LinkedList<HashMap<K, V>>();
for(int i=0; i<numBuckets; i++) {
_buckets.add(new HashMap<K, V>());
} _callback = callback;
} public RotatingMap(ExpiredCallback<K, V> callback) {
this(DEFAULT_NUM_BUCKETS, callback);
} public RotatingMap(int numBuckets) {
this(numBuckets, null);
} public Map<K, V> rotate() {
Map<K, V> dead = _buckets.removeLast();
_buckets.addFirst(new HashMap<K, V>());
if(_callback!=null) {
for(Entry<K, V> entry: dead.entrySet()) {
_callback.expire(entry.getKey(), entry.getValue());
}
}
return dead;
} public boolean containsKey(K key) {
for(HashMap<K, V> bucket: _buckets) {
if(bucket.containsKey(key)) {
return true;
}
}
return false;
} public V get(K key) {
for(HashMap<K, V> bucket: _buckets) {
if(bucket.containsKey(key)) {
return bucket.get(key);
}
}
return null;
} public void put(K key, V value) {
Iterator<HashMap<K, V>> it = _buckets.iterator();
HashMap<K, V> bucket = it.next();
bucket.put(key, value);
while(it.hasNext()) {
bucket = it.next();
bucket.remove(key);
}
} public Object remove(K key) {
for(HashMap<K, V> bucket: _buckets) {
if(bucket.containsKey(key)) {
return bucket.remove(key);
}
}
return null;
} public int size() {
int size = 0;
for(HashMap<K, V> bucket: _buckets) {
size+=bucket.size();
}
return size;
}
}
EventHandler.java
public class EventHandler<k, v> implements RotatingMap.ExpiredCallback<k, v>
{ @Override
public void expire(Object key, Object val)
{
System.out.println("key=" + key + ",val=" + val);
} }
RotatingMapStarter.java:
import java.sql.Date;
import java.text.SimpleDateFormat; public class RotatingMapStarter
{
RotatingMap<String, String> m_rotatingMap = null;
RotatingMap.ExpiredCallback<String, String> m_eventHandler = null;
long m_lastRotate = System.currentTimeMillis();
long m_rotateTime; @SuppressWarnings(
{ "unchecked", "rawtypes" })
public RotatingMapStarter(int n, int rotateTime) // rotateTime :rotate for
// second
{
m_eventHandler = new EventHandler<String, String>();
m_rotatingMap = new RotatingMap<String, String>(4, m_eventHandler);
m_lastRotate = System.currentTimeMillis();
m_rotateTime = 1000L * rotateTime; // millisecond
} public RotatingMap<String, String> getM_rotatingMap()
{
return m_rotatingMap;
} public void setM_rotatingMap(RotatingMap<String, String> m_rotatingMap)
{
this.m_rotatingMap = m_rotatingMap;
} public void StartConnMonitor()
{
Thread thread = new Thread("Server Monitor")
{
@SuppressWarnings("static-access")
public void run()
{
while (true)
{
try
{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
} long now = System.currentTimeMillis();
if (now - m_lastRotate > m_rotateTime)
{
m_rotatingMap.rotate();
m_lastRotate = now; }
else
{
//System.out.println(now - m_lastRotate);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println(df.format(new Date(now)));// new Date()为获取当前系统时间
}
}
}
}; thread.start();
} /**
* @param args
*/
public static void main(String[] args)
{
RotatingMapStarter rotatingMapStarter = new RotatingMapStarter(4, 10);
String value = "001";
String key = "value";
rotatingMapStarter.getM_rotatingMap().put(key, value);
rotatingMapStarter.StartConnMonitor();
} }
参考storm中的RotatingMap实现key超时处理的更多相关文章
- 关于MapReduce中自定义带比较key类、比较器类(二)——初学者从源码查看其原理
Job类 /** * Define the comparator that controls * how the keys are sorted before they * are pa ...
- storm源码之理解Storm中Worker、Executor、Task关系 + 并发度详解
本文导读: 1 Worker.Executor.task详解 2 配置拓扑的并发度 3 拓扑示例 4 动态配置拓扑并发度 Worker.Executor.Task详解: Storm在集群上运行一个To ...
- C++ STL中Map的按Key排序和按Value排序
map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据key查到相应的value.假如存储学生和其成绩(假定不存在重名,当然可以对重名加以区 分),我们用map来进 ...
- Storm中并发程度的理解
Storm中涉及到了很多组件,例如nimbus,supervisor等等,在参考了这两篇文章之后,对这个有了更好的理解. Understanding the parallelism of a Stor ...
- redis 在 php 中的应用(key篇)
本文为我阅读了 redis参考手册 之后结合 博友的博客 编写,注意 php_redis 和 redis-cli 的区别(主要是返回值类型和参数用法) 目录: KEY(键) DEL ...
- storm中的一些概念
1.topology 一个topolgy是spouts和bolts组成的图,通过stream groupings将图中的spout和bolts连接起来:如图所示: 一个topology会一直运行知道你 ...
- Mysql中INSERT ... ON DUPLICATE KEY UPDATE的实践
转: Mysql中INSERT ... ON DUPLICATE KEY UPDATE的实践 阿里加多 0.1 2018.03.23 17:19* 字数 492 阅读 2613评论 2喜欢 1 一.前 ...
- storm中worker、executor、task之间的关系
这里做一些补充: worker是一个进程,由supervisor启动,并只负责处理一个topology,所以不会同时处理多个topology. executor是一个线程,由worker启动,是运行t ...
- C++ STL中Map的按Key排序跟按Value排序
C++ STL中Map的按Key排序和按Value排序 map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据key查到相应的value.假如存储学生和其成绩(假定 ...
随机推荐
- Android EditText 无法换行
问题 关于控制是否换行的属性android:singleLine 当值为true的时候,只能一行,不换行 当值为false的时候,可以换行 但是现在遇到一个问题: <EditText andro ...
- Android dp和sp的用法汇总
1 > dp 是跟像素密度无关的单位,也就是说在相同尺寸.但不同的分辨率的手机上,用dp标识的东西,显示的大小是一样的. sp是用于标识字体的,它不仅跟屏幕尺寸有关,还跟设置的系统字体大小有关. ...
- 关于jdbc的一些疑问
1.为什么强调在使用jdbc时,须要在使用的时候才打开连接(Connection),用完后立刻关闭.假设我的连接(Connection)一開始就打开.在整个程序结束时才关闭,会带来什么后果呢? 2.为 ...
- SEOR要懂得如何建立完善的seo运营团队
网站运营要想能做大做全面,完善的seo运营团队是不可缺少的,跟企业管理一样的道理,seo运营的成功也在于对团队的合理利用,发挥团队中每个成员的优势才能运营好网站.网站的运营CEO要懂得如何建立完善的s ...
- windows简单杀死进程的批处理程序
新建一个txt文档,命令为taskkill.bat,复制下面的命令保存 @echo offtaskkill /F /IM vm* /Ttaskkill /F /IM apple* /Ttaskkill ...
- emacs打开乱码解决办法
前言:有时候我们使用emacs打开文件的时候,因为emacs默认编码跟文档编码不同而出现了乱码如图: 对于新手的我们应该通过以下两种途径来解决: 方法一: 只需C-x <RET> r ( ...
- BZOJ 3275: Number( 最小割 )
S->每个奇数,每个偶数->T各连一条边, 容量为这个数字.然后不能同时选的两个数连容量为+oo的边. 总数-最大流即是答案. 因为满足a2+b2=c2的a,b一定是一奇一偶或者两个偶数, ...
- eclipse+tomcat+maven debug的时候总是出现source not found /Edit lookup path...的问题解决方案
eclipse+tomcat+maven debug的时候总是出现source not found /Edit lookup path...的问题解决方案 这个问题纠结好久好久.... 问题出现的环 ...
- Net Core在Linux环境
Net Core在Linux环境 基础环境和相关软件准备 1.CentOS7.1 64位系统(或者其他CentOS版本的64位系统) 2.WinSCP软件(主要是方便管理和编辑Linux系统的文件) ...
- spring mvc 和ajax异步交互完整实例
Spring MVC 异步交互demo: 1.jsp页面: <%@ page language="java" contentType="text/html; cha ...