1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
| package one;
import java.text.NumberFormat;
import java.util.concurrent.CountDownLatch;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TransactionContentionTest extends ConnectionBuilder {
private static final int CONTENTION_LEVEL = 5;
private static final int TOTAL = 20000;
private static final NumberFormat nf = NumberFormat.getPercentInstance();
public static void main(String[] args) throws Exception {
nf.setMinimumFractionDigits(2);
buildPool();
CountDownLatch latch = new CountDownLatch(CONTENTION_LEVEL);
Thread[] threads = new Thread[CONTENTION_LEVEL];
ContentionClient[] clients = new ContentionClient[CONTENTION_LEVEL];
Jedis jedis = pool.getResource();
jedis.set("TestCounter", "0");
jedis.close();
for (int i = 0; i < CONTENTION_LEVEL; i++) {
ContentionClient client = new ContentionClient();
client.setTotal(TOTAL);
client.setCounterName("TestCounter");
client.setJedis(pool.getResource());
client.setLatch(latch);
clients = client;
threads = new Thread(client);
}
long start = System.currentTimeMillis();
for (int i = 0; i < CONTENTION_LEVEL; i++) {
threads.start();
}
latch.await();
long end = System.currentTimeMillis();
System.out.println("Elapse:" + (end - start) + " ms");
for (int i = 0; i < CONTENTION_LEVEL; i++) {
Double failRate = (double) clients.getFailCount() / TOTAL;
System.out.println(i + " Fail Rate:" + nf.format(failRate));
clients.getJedis().close();
}
close();
}
static class ContentionClient implements Runnable {
private Jedis jedis;
private String counterName;
private int total;
private long failCount = 0;
public CountDownLatch getLatch() {
return latch;
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
private CountDownLatch latch;
public Jedis getJedis() {
return jedis;
}
public void setJedis(Jedis jedis) {
this.jedis = jedis;
}
public String getCounterName() {
return counterName;
}
public void setCounterName(String counterName) {
this.counterName = counterName;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public long getFailCount() {
return failCount;
}
public void setFailCount(long failCount) {
this.failCount = failCount;
}
@Override
public void run() {
while (total > 0) {
jedis.watch(counterName);
Integer counter = Integer.parseInt(jedis.get(counterName));
Transaction tx = jedis.multi();
counter++;
tx.set(counterName, counter.toString());
if (tx.exec() == null) {
jedis.unwatch();
failCount++;
} else {
total--;
}
}
latch.countDown();
}
}
}
|