DefaultMessageQueue.java
1.25 KB
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
package com.dianping.cat.message.io;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.dianping.cat.message.spi.MessageQueue;
import com.dianping.cat.message.spi.MessageTree;
public class DefaultMessageQueue implements MessageQueue {
private BlockingQueue<MessageTree> m_queue;
private AtomicInteger m_count = new AtomicInteger();
public DefaultMessageQueue(int size) {
m_queue = new LinkedBlockingQueue<MessageTree>(size);
}
@Override
public boolean offer(MessageTree tree) {
return m_queue.offer(tree);
}
@Override
public boolean offer(MessageTree tree, double sampleRatio) {
if (tree.isSample() && sampleRatio < 1.0) {
if (sampleRatio > 0) {
int count = m_count.incrementAndGet();
if (count % (1 / sampleRatio) == 0) {
return offer(tree);
}
}
return false;
} else {
return offer(tree);
}
}
@Override
public MessageTree peek() {
return m_queue.peek();
}
@Override
public MessageTree poll() {
try {
return m_queue.poll(5, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
return null;
}
}
@Override
public int size() {
return m_queue.size();
}
}