Http://www.ibm.com/developerworks/cn/java/j-zhanghz/
Level: elementary
Vision Zhang Huang (zhanghuangzhu@gmail.com), software engineer
January 18, 2006
Java 5
Added a new class library concurrency set java. util. Concurrent, which provides a wide range of API multi-thread programming in Java
5 is easier and more flexible. This article uses a network server model to implement Java 5 multi-threaded programming. This model uses the thread pool in Java 5, blocks the queue, and reentrant locks.
Callable, future, and other interfaces, and use another new generic feature of Java 5.
This article will implement a network server model. Once a client connects to the server, a new thread is started to serve the connection, and the service content is to deliver some character information to the client. A typical network server model is as follows:
1. Create a listening port.
2. New connections are found, connections are accepted, threads are started, and service threads are executed.
3. After the service is completed, close the thread.
This
Models run well in most cases, but user requests need to be processed frequently. When the services required for each request are short, the system will spend a lot of time creating and destroying the threads. Java
The thread pool of 5 overcomes these shortcomings. By executing multiple tasks on the reuse thread, the overhead of frequent thread creation and destruction is avoided, which greatly improves the server performance. Therefore, the network server in this article
The model will be as follows:
1. Create a listening port and a thread pool.
2. When a new connection is found, the thread pool is used to execute service tasks.
3. After the service is completed, release the thread to the thread pool.
The following describes how to use the APIS provided by the concurrent package of Java 5 to implement the server.
Chu
Initialization includes creating thread pools and initializing listening ports.
To create a thread pool, call the static method newchahedthreadpool in the Java. util. Concurrent. executors class or
Newfixedthreadpool. You can also create a java. util. Concurrent. threadpoolexecutor instance.
To execute the task. Here we use the newfixedthreadpool method to create a thread pool.
ExecutorService pool = Executors.newFixedThreadPool(10);
Indicates that a new thread pool is created, and 10 threads in the thread pool serve the task queue.
Use the serversocket object to initialize the listening port.
private static final int PORT = 19527;serverListenSocket = new ServerSocket(PORT);serverListenSocket.setReuseAddress(true);serverListenSocket.setReuseAddress(true); |
When a new connection is established and the accept returns, the service task is submitted to the thread pool for execution.
while(true){Socket socket = serverListenSocket.accept();pool.execute(new ServiceThread(socket));} |
Here, the thread pool object is used to execute the thread, reducing the overhead of every thread creation and destruction. After the task is executed, the thread is released to the thread pool.
Server
The service thread servicethread maintains a count to record the number of times the service thread is called. When a service task is called once, the Count value increases by 1. Therefore
Servicethread provides the increasecount and getcount methods to increase the Count value by 1 and obtain the Count value respectively. Because there may be multiple
Threads compete and access count at the same time. Therefore, the lock mechanism is required. Before Java 5, we can only use synchronized to lock. Java
5 introduces reentrantlock with more fine-grained performance. We use reentrantlock to ensure code thread security. The code below is as follows:
private static ReentrantLock lock = new ReentrantLock ();private static int count = 0;private int getCount(){int ret = 0;try{lock.lock();ret = count;}finally{lock.unlock();}return ret;}private void increaseCount(){try{lock.lock();++count;}finally{lock.unlock();}} |
The service thread prints a welcome message to the client at the beginning,
increaseCount();int curCount = getCount();helloString = "hello, id = " + curCount+"/r/n";dos = new DataOutputStream(connectedSocket.getOutputStream());dos.write(helloString.getBytes()); |
Then use the submit method of executorservice to extract
Submit a callable task and return a reference to the future interface. This method is very effective for time-consuming tasks. After the submit task, you can continue to execute the following code and
You can use the get method of future to obtain the result. If the method has been executed, you do not need to wait until the result is obtained.
Executorservice executor = executors. newsinglethreadexecutor (); Future <string> future = executor. submit (New timeconsumingtask (); dos. write ("Let's Do soemthing other ". getbytes (); string result = Future. get (); dos. write (result. getbytes (); timeconsumingtask implements the callable Interface Class timeconsumingtask implements callable <string> {Public String call () throws exception {system. out. println ("it's a time-consuming task, you 'd better retrieve your result in the furture"); Return "OK, here's the result: it takes me lots of time to produce this result ";}} |
Java
Another new feature of 5 is generic. When declaring timeconsumingtask, string is used as the type parameter. The call function of the callable interface must be implemented,
Its function is similar to the run function in runnable. It writes the code to be executed in the call function. Its return value type is equivalent to the type value passed in the class declaration. In this program, we submitted
A callable task, and then the program will not be blocked, but will continue to execute DOS. Write ("Let's Do soemthing
Other ". getbytes (); when the program is executed to string result =
When future. Get () is run, if the call function has been executed, the return value is obtained. If the call function is still being executed, the call function is executed.
The complete server implementation code is as follows:
package com.andrew;import java.io.DataOutputStream;import java.io.IOException;import java.io.Serializable;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;public class Server {private static int produceTaskSleepTime = 100;private static int consumeTaskSleepTime = 1200;private static int produceTaskMaxNumber = 100;private static final int CORE_POOL_SIZE = 2;private static final int MAX_POOL_SIZE = 100;private static final int KEEPALIVE_TIME = 3;private static final int QUEUE_CAPACITY = (CORE_POOL_SIZE + MAX_POOL_SIZE) / 2;private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;private static final String HOST = "127.0.0.1";private static final int PORT = 19527;private BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY);//private ThreadPoolExecutor serverThreadPool = null;private ExecutorService pool = null;private RejectedExecutionHandler rejectedExecutionHandler = newThreadPoolExecutor.DiscardOldestPolicy();private ServerSocket serverListenSocket = null;private int times = 5;public void start() {// You can also init thread pool in this way./*serverThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_POOL_SIZE, KEEPALIVE_TIME, TIME_UNIT, workQueue,rejectedExecutionHandler);*/pool = Executors.newFixedThreadPool(10);try {serverListenSocket = new ServerSocket(PORT);serverListenSocket.setReuseAddress(true);System.out.println("I'm listening");while (times-- > 0) {Socket socket = serverListenSocket.accept();String welcomeString = "hello";//serverThreadPool.execute(new ServiceThread(socket, welcomeString));pool.execute(new ServiceThread(socket));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}cleanup();}public void cleanup() {if (null != serverListenSocket) {try {serverListenSocket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//serverThreadPool.shutdown();pool.shutdown();}public static void main(String args[]) {Server server = new Server();server.start();}}class ServiceThread implements Runnable, Serializable {private static final long serialVersionUID = 0;private Socket connectedSocket = null;private String helloString = null;private static int count = 0;private static ReentrantLock lock = new ReentrantLock();ServiceThread(Socket socket) {connectedSocket = socket;}public void run() {increaseCount();int curCount = getCount();helloString = "hello, id = " + curCount + "/r/n";ExecutorService executor = Executors.newSingleThreadExecutor();Future<String> future = executor.submit(new TimeConsumingTask());DataOutputStream dos = null;try {dos = new DataOutputStream(connectedSocket.getOutputStream());dos.write(helloString.getBytes());try {dos.write("let's do soemthing other./r/n".getBytes());String result = future.get();dos.write(result.getBytes());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (null != connectedSocket) {try {connectedSocket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (null != dos) {try {dos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}executor.shutdown();}}private int getCount() {int ret = 0;try {lock.lock();ret = count;} finally {lock.unlock();}return ret;}private void increaseCount() {try {lock.lock();++count;} finally {lock.unlock();}}}class TimeConsumingTask implements Callable<String> {public String call() throws Exception {System.out.println("It's a time-consuming task, you'd better retrieve your result in the furture");return "ok, here's the result: It takes me lots of time to produce this result";}} |