import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This ServerTransport is work in multi thread env
*
* @author daniel
*
*/
public class ServerTransport {
private static final Log _log = LogFactory.getLog(ServerTransport.class);
private final Object _lock = new Object();
private boolean _readyFlag = false;
private boolean _stopFlag;
private final AsynchronousCaller _asyncCaller;
/**
* Initialization AsynchronousCaller
* @param asyncThreadPoolSize
*/
public ServerTransport(int asyncThreadPoolSize) {
if(asyncThreadPoolSize<0){
throw new IllegalArgumentException("illegal Server Transport poolSize: "+asyncThreadPoolSize);
}
_asyncCaller = new AsynchronousCaller(asyncThreadPoolSize);
//Do some other things about each transport!
}
/*
* Operate Handler
*/
//check ready
public boolean isReady(){
synchronized(_lock){
return _readyFlag;
}
}
//start
public void start() throws Exception {
if (isStopped()) {
return;
}
_asyncCaller.start();
setReady(true);
}
//stop
public void stop() {
_asyncCaller.stop();
setReady(false);
setStop(false);
}
//set ready
private void setReady(boolean b) {
synchronized(_lock){
_readyFlag = b;
}
}
//set ready
private void setStop(boolean b) {
synchronized(_lock){
_stopFlag = b;
}
}
//check stop
private boolean isStopped() {
synchronized(_lock){
return _stopFlag;
}
}
}
/*
* Construct an Asynchronous Operate way
*/
class AsynchronousCaller {
private final ThreadPoolExecutor _executor;
/*
* Generate an Thread pool with some thread factory & thread group
*/
public AsynchronousCaller(int poolSize) {
if (poolSize <= 0) {
throw new IllegalArgumentException("illegal pool size: "+poolSize);
}
ThreadGroup threadGroup = new ThreadGroup("Async Caller Group");
ThreadGroupFactory tFactory= new ThreadGroupFactory(threadGroup, "AsyncCaller-");
tFactory.createDaemonThreads(true);
_executor = new ThreadPoolExecutor(poolSize,
poolSize,
Long.MAX_VALUE,
TimeUnit.NANOSECONDS,
new LinkedBlockingQueue(),
tFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public void start() {
_executor.prestartAllCoreThreads();
}
public void stop() {
_executor.shutdown();
}
}
int serverTransNum = 3;
ServerTransport serverTran = new ServerTransport(serverTransNum);
if(!serverTran.isReady()){
try {
serverTran.start();
Thread.sleep(2000);
serverTran.stop();
} catch (Exception e) {
throw new RuntimeException("Unable to start server transport", e);
}
}
}