classBadListHelper <E> {
publicList<E> list = Collections.synchronizedList(new ArrayList<E>());
public synchronized boolean putIfAbsent(E x) {
boolean absent = !list.contains(x);
if (absent)
list.add(x);
return absent;
}
}
隐藏迭代器(不要这么做,不要写如下代码)
public class HiddenIterator {
@GuardedBy("this") privatefinal Set<Integer> set = new HashSet<Integer>();
publicsynchronizedvoidadd(Integer i) {
set.add(i);
}
publicsynchronizedvoid remove(Integer i) {
set.remove(i);
}
publicvoid addTenThings() {
Random r = new Random();
for (int i = 0; i < 10; i++)
add(r.nextInt());
System.out.println("DEBUG: added ten elements to " + set);
}
}
并发容器
ConcurrentHashMap
Executor框架
基于Executor框架的web服务器
定长线程池,可以容纳100个线程
publicclassTaskExecutionWebServer{
privatestaticfinalint NTHREADS = 100;
privatestaticfinal Executor exec
= Executors.newFixedThreadPool(NTHREADS);
publicstaticvoidmain(String[] args)throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable task = new Runnable() {
publicvoidrun(){
handleRequest(connection);
}
};
exec.execute(task);
}
}
privatestaticvoidhandleRequest(Socket connection){
// request-handling logic here
}
}