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超时处理的更多相关文章

  1. 关于MapReduce中自定义带比较key类、比较器类(二)——初学者从源码查看其原理

    Job类 /**   * Define the comparator that controls    * how the keys are sorted before they   * are pa ...

  2. storm源码之理解Storm中Worker、Executor、Task关系 + 并发度详解

    本文导读: 1 Worker.Executor.task详解 2 配置拓扑的并发度 3 拓扑示例 4 动态配置拓扑并发度 Worker.Executor.Task详解: Storm在集群上运行一个To ...

  3. C++ STL中Map的按Key排序和按Value排序

    map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据key查到相应的value.假如存储学生和其成绩(假定不存在重名,当然可以对重名加以区 分),我们用map来进 ...

  4. Storm中并发程度的理解

    Storm中涉及到了很多组件,例如nimbus,supervisor等等,在参考了这两篇文章之后,对这个有了更好的理解. Understanding the parallelism of a Stor ...

  5. redis 在 php 中的应用(key篇)

    本文为我阅读了 redis参考手册 之后结合 博友的博客 编写,注意 php_redis 和 redis-cli 的区别(主要是返回值类型和参数用法) 目录: KEY(键) DEL           ...

  6. storm中的一些概念

    1.topology 一个topolgy是spouts和bolts组成的图,通过stream groupings将图中的spout和bolts连接起来:如图所示: 一个topology会一直运行知道你 ...

  7. Mysql中INSERT ... ON DUPLICATE KEY UPDATE的实践

    转: Mysql中INSERT ... ON DUPLICATE KEY UPDATE的实践 阿里加多 0.1 2018.03.23 17:19* 字数 492 阅读 2613评论 2喜欢 1 一.前 ...

  8. storm中worker、executor、task之间的关系

    这里做一些补充: worker是一个进程,由supervisor启动,并只负责处理一个topology,所以不会同时处理多个topology. executor是一个线程,由worker启动,是运行t ...

  9. C++ STL中Map的按Key排序跟按Value排序

    C++ STL中Map的按Key排序和按Value排序 map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据key查到相应的value.假如存储学生和其成绩(假定 ...

随机推荐

  1. 梳排序(Comb sort)

    Comb Sort,梳排序或者梳子排序,就像梳子那样有间隔地比较两个数,很形象,O(n*logn)时间复杂度,O(1)空间复杂度,属于不稳定的排序算法.算法的思想是使逆序的元素尽可能快地移动到最终的位 ...

  2. java学习之实现文件的复制

    package com.io; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * 文件 ...

  3. HDU 5045 Contest(状压DP)

    Problem Description In the ACM International Collegiate Programming Contest, each team consist of th ...

  4. 【Eclipse】Failed to load the JNI shared library

    这是因为JDK配置错误所导致的现象. 一般说来,新购笔记本会预装64位的windows系统,而在网上下载软件时,32位会优先出现在页面中(现在来说是这个情况,但我认为未来64位会越来越普及). 如果你 ...

  5. 计算闰年_winform

    新建窗体应用程序(如下),新建控件label1,label2,label3,textBOX1,button1,button2 label1的Text属性改为“计算闰年演示” label2的Text属性 ...

  6. ubuntu15.04安装hexo

    首先吐槽一下npm淘宝源,貌似中国目前唯一一个npm源,现在不好用了,不知道是不是换了地址,在吐槽一下万恶的墙!你懂得. 好了,说点正儿八经的事儿. 之所以安装hexo也是为了创建自己的博客,我只说最 ...

  7. [Swust 549]--变位词(vector水过)

    Time limit(ms): 1000 Memory limit(kb): 65535   Description 输入N和一个要查找的字符串,以下有N个字符串,我们需要找出其中的所有待查找字符串的 ...

  8. Linux如何修改SSH端口号

    SSH是什么? SSH 为 Secure Shell 由 IETF 的网络工作小组(Network Working Group)所制定: SSH 是建立在应用层和传输层基础上的一种安全协议. SSH传 ...

  9. 使用Maven打包项目并上传到Linux服务器

    Maven打包: 项目右键Run as-->Maven build...-->  出来下面的界面,注意红色部分的填写,Goals填写package表示打包,下面的Skip Tests表示打 ...

  10. freemarker报错之八

    1.错误描写叙述 freemarker.core.ParseException: Encountered "string" at line 21, column 21 in typ ...