Menu

[r2]: / socket / SelectorFactory.java  Maximize  Restore  History

Download this file

89 lines (72 with data), 2.0 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
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
/**
* <strong>Selector缓存(线程相关)</strong>
* <p>
* 1. 减少线程切换时间
* 2. 如果在线程的每次run调用时初始化Selector, 会增加生成对象的开销
*
* </p>
*
* @author: 汉娱网络.技术部.yangxf
* @date: 2007-12-27
* @version: 1.1
**/
package com.handjoys.socket;
import java.io.IOException;
import java.nio.channels.Selector;
import java.util.EmptyStackException;
import java.util.Stack;
public class SelectorFactory{
protected static long timeout = 5000;
protected static int maxSelectors = 20;
/**
* Cache of <code>Selector</code>
*/
private final static Stack<Selector> selectors = new Stack<Selector>();
/**
* Creates the <code>Selector</code>
*/
static {
try{
for (int i = 0; i < maxSelectors; i++)
selectors.add(Selector.open());
} catch (IOException ex){
; // do nothing.
}
}
/**
* Get a exclusive <code>Selector</code>
*/
public final static Selector getSelector() {
synchronized(selectors) {
Selector s = null;
try {
if ( selectors.size() != 0 )
s = selectors.pop();
} catch (EmptyStackException ex){}
int attempts = 0;
try{
while (s == null && attempts < 2) {
selectors.wait(timeout);
try {
if ( selectors.size() != 0 )
s = selectors.pop();
} catch (EmptyStackException ex){
break;
}
attempts++;
}
} catch (InterruptedException ex){};
return s;
}
}
/**
* Return the <code>Selector</code> to the cache
*/
public final static void returnSelector(Selector s) {
synchronized(selectors) {
selectors.push(s);
if (selectors.size() == 1)
selectors.notify();
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.