参考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.假如存储学生和其成绩(假定 ... 
随机推荐
- Qt Creator error: LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
			Qt Creator error: LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 治标又治本的解决方法: 找到在 { C:\Windows\Microsoft.NET\Fra ... 
- Ubuntu上用premake编译GDAL
			GDAL的编译脚本呈现出不同平台不同解决方案的百花齐放现状.我是从windows平台开始编译GDAL的,用的自然是nmake.那就是一种每个目录下都需要写makefile文件的构建方法,写的人麻烦,我 ... 
- 基于visual Studio2013解决C语言竞赛题之0301函数求值
			 题目 解决代码及点评 #include <stdio.h> #include <stdlib.h> #include <math.h> void main() ... 
- IT第十天 - String和StringBuffer的比较、编程设计技巧整理、本周总结 ★★★
			IT第十天 上午 String 1.String在进行多次的+扩展时,会严重的降低处理效率,因为String长度是不可变的,在进行+运算改变字符串时,会自动创建很多临时字符串,并不是在原字符串上追加, ... 
- ORACLE uuid自己主动生成主键
			-- Create table create table TECHNOLOGYCOMPANY ( ID VARCHAR2(32) default SYS_GUID() not null, FLOWID ... 
- iOS7支持九宫格
			Beta4支持九宫格 还没试,等最终版把,现在的有很多bug还比较费电 看网上有人说虽然终于出来了但是还是不如百度搜狗等输入法方便 前几个月在weiphone上还有人问支不支持结果回帖的都说没戏 这算 ... 
- linux脚本:ftp自动传输文件
			使用Shell脚本实现ftp的自动上传下载 http://liwenge.iteye.com/blog/566515 open 192.168.1.171 user guest 123456cd /h ... 
- java.lang.NoClassDefFoundError: org.ksoap2.transport.HttpTransportSE异常处理
			原因就是没有打包进去 因为引用进去 编译时没出出现问题 解决如下 
- Opencv2系列学习笔记2(图像的其它操作)
			本节主要涉及到图像的领域.算术操作以及如何操作图像感兴趣的区域. 一:邻域操作 以下例子主要对图像进行锐化.基于拉普拉斯算子<后面讨论>.这幅图像的边缘部分将得到放大,细节部分将更加的锐利 ... 
- 17.1.1.3 Creating a User for Replication
			17.1.1.3 Creating a User for Replication 创建一个用户用于复制: 每个slave 连接到master 使用一个MySQL 用户名和密码, 因此必须有一个user ... 
