Skip to content

Commit 1700ca5

Browse files
committed
Queuing logic
1 parent 9b96321 commit 1700ca5

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package benblack86.collection.queue;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.ArrayBlockingQueue;
5+
import java.util.concurrent.BlockingQueue;
6+
import java.util.concurrent.TimeUnit;
7+
8+
public class RetryManager extends Thread {
9+
10+
public static void main(String[] args) {
11+
Random random = new Random();
12+
RetryManager manager = new RetryManager();
13+
manager.start();
14+
for(int i = 0; i < 1000; i++) {
15+
manager.addToQueue(new Item("task_"+i, new Object()));
16+
try {
17+
int wait = random.nextInt(10);
18+
System.out.printf("Wait:%s\n", wait);
19+
Thread.sleep(wait);
20+
} catch (InterruptedException e) {
21+
e.printStackTrace();
22+
}
23+
}
24+
25+
}
26+
27+
private final static int QUEUE_MAX_CAPACITY = 100;
28+
private final static int WARN_LEVEL = 10;
29+
private final BlockingQueue<Item> queue = new ArrayBlockingQueue<Item>(QUEUE_MAX_CAPACITY);
30+
31+
32+
33+
public void addToQueue(Item item) {
34+
// waits until there is space
35+
try {
36+
queue.offer(item, 1, TimeUnit.SECONDS);
37+
} catch (InterruptedException e) {
38+
e.printStackTrace();
39+
}
40+
41+
if (queue.size() > WARN_LEVEL) {
42+
System.out.printf("Queue warning|Size:%s|Capacity:%s|Filled:%s%%\n", queue.size(), QUEUE_MAX_CAPACITY, ((double)queue.size()/QUEUE_MAX_CAPACITY)*100);
43+
}
44+
}
45+
46+
@Override
47+
public void run() {
48+
while (true) {
49+
try {
50+
// take waits if necessary until an element becomes available
51+
Item item = queue.take();
52+
53+
System.out.printf("Doing something with item|Name:%s\n", item.name);
54+
55+
Thread.sleep(5);
56+
57+
} catch(Throwable t) {
58+
t.printStackTrace();
59+
}
60+
}
61+
}
62+
63+
}
64+
65+
class Item {
66+
String name;
67+
Object object;
68+
69+
public Item(String name, Object object) {
70+
this.name = name;
71+
this.object = object;
72+
}
73+
}

0 commit comments

Comments
 (0)