设为首页 加入收藏

TOP

实战Memcached缓存系统(6)Memcached CAS的多线程程序实例
2014-11-24 07:25:23 来源: 作者: 【 】 浏览:2
Tags:实战 Memcached 系统 CAS 线程 程序 实例
1. 源程序
[java]
package com.sinosuperman.memcached;

import java.io.IOException;
import java.net.InetSocketAddress;

import net.spy.memcached.CASResponse;
import net.spy.memcached.CASValue;
import net.spy.memcached.MemcachedClient;


public class Test {

private static MemcachedClient client = null;

static {
try {
client = new MemcachedClient(new InetSocketAddress("localhost", 11211));
} catch (IOException o) {
}
}

public static void main(String[] args) throws Exception {

client.set("numberss", 1800, 1);

Test testObj = new Test();
for (int i = 0; i < 10; i++) {
testObj.new ThreadTest("Thread-" + (i + 1)).start();
}
}

private class ThreadTest extends Thread {

private MemcachedClient client = null;
ThreadTest(String name) throws IOException {
super(name);
client = new MemcachedClient(new InetSocketAddress("localhost", 11211));
}

public void run() {
int i = 0;
int success = 0;
while (i < 10) {
i++;
CASValue uniqueva lue =client.gets("numberss");
CASResponse response = client.cas("numberss",
uniqueva lue.getCas(), (Integer)uniqueva lue.getValue() + 1);

if (response.toString().equals("OK")) {
success++;
}

if (i == 10)
System.out.println(Thread.currentThread().getName() + " " + i
+ " time " + " update oldValue : " + uniqueva lue.getValue()
+ " , result : " + response);
}

if (success < 10) {
Count.incr(10 - success);
System.out.println("Test counter: " + Count.get());
}
}
}

public static class Count {
private static int counter = 0;
public static void incr(int x) {
counter += x;
}
public static int get() {
return counter;
}
}
}

2. 输出结果:
[plain]
Thread-1 10 time update oldValue : 14 , result : EXISTS
Test counter: 6
Thread-2 10 time update oldValue : 14 , result : EXISTS
Test counter: 15
Thread-3 10 time update oldValue : 17 , result : EXISTS
Test counter: 22
Thread-5 10 time update oldValue : 17 , result : EXISTS
Test counter: 27
Thread-4 10 time update oldValue : 20 , result : OK
Test counter: 33
Thread-8 10 time update oldValue : 27 , result : OK
Test counter: 36
Thread-6 10 time update oldValue : 28 , result : EXISTS
Test counter: 43
Thread-10 10 time update oldValue : 31 , result : EXISTS
Test counter: 52
Thread-9 10 time update oldValue : 31 , result : OK
Test counter: 60
Thread-7 10 time update oldValue : 35 , result : OK
Test counter: 65

3. 分析
我们可以看到,未成功的次数最终为65,数据值最终为35,两者的和刚好是100,正好符合我们的实验结果预期
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇写给MongoDB开发者的50条建议Tip1 下一篇获取当前日期对应是星期几

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)
·SQL 撤销索引、表以 (2025-12-25 22:20:38)
·Linux系统简介 (2025-12-25 21:55:25)
·Linux安装MySQL过程 (2025-12-25 21:55:22)