我正在尝试用Java创建TCP服务器,但是我使用ExecutorService来为名为ServerService
的类中的客户端连接请求提供服务。
像这样:
public class ServerService extends Thread
{
final Settings settings = SystemSettings.getInstance();
private final ThreadPoolExecutor client_pool =
(ThreadPoolExecutor)Executors.newFixedThreadPool(
settings.getNo_of_client_connections(), new ClientThreadFactory());
ServerSocket server ;
Socket client_socket ;
public void run()
{
try {
server = new ServerSocket(4000);
while(!client_pool.isShutDown()) {
client = server.accept();
// call client connection runnable to continue processing from here
ClientConnection client_connection = new ClientConnection(client);
client_pool.execute(client_connection);
}
} catch(Exception ex) {
LoggerService.log(ex);
}
finally {
client.close();
}
}
// shutdown service
public synchronized void shutdown() throws IOException, InterruptedException
{
if(client_pool != null) {
client_pool.shutdown();
client_pool.awaitTermination(20, TimeUnit.SECONDS);
client_pool.shutdownNow();
System.out.println("Service has been shutdown ........");
}
}
}
然后我有ClientConnection
类,一旦建立连接就处理来自客户端的请求。
public class ClientConnection implements Runnable
{
Socket socket ;
private ObjectInputStream ois = null;
private ObjectOutputStream oos = null;
private static boolean isInterrupted = false ;
public ClientConnection(Socket socket)
{
this.socket = socket ;
}
public void run()
{
oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream(), 10240));
// write a session client id to client for
write(new Response(ResponseCommand.CLIENT_ID_SESSION_ID, CLIENT_ID)); // chicken egg problem
System.out.println(getClient_id() +" connected....");
// create a buffer size of 10kb for reading data from client
ois = new ObjectInputStream( new BufferedInputStream(socket.getInputStream(), 10240));
try {
// as far as the thread running this runnable in my pool is not interrupted
while(!Thread.currentThread().isInterrupted()) {
Object request = ois.readObject();
if(request != null) {
// get request object
Request rq = (Request)request;
if(rq.getComand().equlasIgnoreCase("EXIT")) {
isInterrupted = true ;
// interrupt thread running in my pool
Thread.currentThread().interrupt();
}
}
}
} catch(IOException ex) {
LoggerService.log(ex);
} catch(InterruptedException ex) {
LoggerService.log(ex);
Thread.currentThread.interrupt();
} finally {
if(isInterupted) {
socket.close();
}
}
}
}
现在这些是我的问题:
ClientConnection
(Runnable
)与我的线程池同步,因为我
用固定数量的线程启动我的线程池,例如10
其中一个线程被中断它关闭套接字连接和
应该准备好处理另一个客户。RejectedExecutionHandler
进行建模以显示错误
何时超过池中固定数量的连接?感谢。