1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.plugin.opennap.net.msg;
21
22 import org.xnap.plugin.opennap.net.SendQueue;
23 import org.xnap.plugin.opennap.net.msg.client.ClientMessage;
24
25 public class SendWorker implements Runnable
26 {
27
28
29
30 /***
31 * Spent that much time on a queue per run.
32 */
33 public static long MAX_TIME_PER_SERVER = 2 * 1000;
34
35 public static long STALL_INTERVAL = 200;
36
37
38
39
40
41 private MessageSender parent;
42
43
44
45 public SendWorker(String name, MessageSender parent)
46 {
47 this.parent = parent;
48
49 Thread t = new Thread(this, name);
50 t.start();
51 }
52
53
54
55 public void run()
56 {
57 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
58
59 while(!parent.hasDied()) {
60 SendQueue q = parent.pop();
61 if (q != null) {
62 sendMessages(q);
63
64 parent.enqueue(q);
65 }
66 else {
67 synchronized (parent) {
68 try {
69 parent.wait();
70 }
71 catch (InterruptedException e) {
72 }
73 }
74
75 }
76 }
77 }
78
79 /***
80 * Sends the message from q until timeout is expired.
81 *
82 * @return true, if q has more messages, meaning it should be requed
83 */
84 public boolean sendMessages(SendQueue q)
85 {
86 long start = System.currentTimeMillis();
87
88 int stallCount = 0;
89 while (System.currentTimeMillis() - start < MAX_TIME_PER_SERVER) {
90
91 ClientMessage msg = q.pop();
92 if (msg == null) {
93 if (stallCount == 3) {
94 return false;
95 }
96 else {
97 stallCount++;
98 try {
99 Thread.sleep(STALL_INTERVAL);
100 }
101 catch (InterruptedException e) {
102 }
103 }
104 }
105 else {
106 if (!q.send(msg)) {
107 return false;
108 }
109 else if (msg.getPriority() != ClientMessage.PRIORITY_LOW) {
110 stallCount = 3;
111 }
112 }
113 }
114
115 return true;
116 }
117
118 }