package org.maachang.comet.net ;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.maachang.comet.httpd.HttpSocket;

/**
 * Accept用監視情報.
 * 
 * @version 2007/11/17
 * @author  masahito suzuki
 * @since   MaachangComet 1.00
 */
public class HttpAcceptThread extends Thread {
    
    private static final Log LOG = LogFactory.getLog( HttpAcceptThread.class ) ;
    private HttpServer server = null ;
    private HttpSocketManager manager = null ;
    private volatile boolean stopFlag = true ;
    
    private HttpAcceptThread() {
        
    }
    
    public HttpAcceptThread( HttpServer server,HttpSocketManager manager )
        throws Exception {
        this.server = server ;
        this.manager = manager ;
        this.stopFlag = false ;
        this.setDaemon( true ) ;
        this.start() ;
    }
    
    public void destroy() {
        setStop( true ) ;
    }
    
    public HttpSocketManager getVtSocketManager() {
        return this.manager ;
    }
    
    public synchronized boolean isStop() {
        return stopFlag ;
    }
    
    private synchronized void setStop( boolean mode ) {
        this.stopFlag = mode ;
    }
    
    public void run() {
        boolean endFlag = false ;
        ThreadDeath threadDeach = null ;
        for( ;; ) {
            if( endFlag == true || isStop() == true ) {
                break ;
            }
            HttpSocket s = null ;
            try {
                if( ( s = server.accept() ) != null ) {
                    this.manager.append( s ) ;
                }
            } catch( InterruptedException ite ) {
                endFlag = true ;
            } catch ( NullPointerException ne ) {
            } catch( OutOfMemoryError mem ) {
                LOG.error( "## out-of-memory-error",mem ) ;
            } catch( Exception e ) {
                LOG.error( "## error",e ) ;
            } catch( ThreadDeath td ) {
                endFlag = true ;
                threadDeach = td ;
            }
        }
        this.server = null ;
        this.manager = null ;
        setStop( true ) ;
        if( threadDeach != null ) {
            throw threadDeach ;
        }
    }
    
}

