ITeye博客

关于Java钩子的使用

cloud21 · 2010-02-25 10:48 · Java Swing · 企业架构 · Markdown

package test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class Untitled1 {

	public Untitled1(){
		doShutDownWork();
		
	}
	private void doShutDownWork(){
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			public void run(){
				try{
					FileWriter fw=new FileWriter("c:\\t.log");
					System.out.println("Im going to end");
					fw.write("The application ended! "+(new Date()).toString());
					fw.close();
				}catch(IOException ex){
					
				}
				
			}
			
		});
		
	}
	
	public static void main(String[] args){
		Untitled1 untitled11=new Untitled1();
		long s=System.currentTimeMillis();
		for(int i=0;i<1000000000;i++){
			
		}
		long se=System.currentTimeMillis();
		System.out.println(se-s);
		
	}
}

但是我还是不知道,tomcat是如何退出的,请教各位提提意见,一直想知道。

评论(2)

  1. #2 楼 · xiegqooo · 2012-12-21 10:29

    简单的关闭 tomcat

    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class ShutdownService {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		try {
    			Socket socket = new Socket("127.0.0.1", 8005);
    			OutputStream stream = socket.getOutputStream();
    			String shutdown = "SHUTDOWN";
    			for (int i = 0; i < shutdown.length(); i++)
    				stream.write(shutdown.charAt(i));
    			stream.flush();
    			stream.close();
    			socket.close();
    		} catch (UnknownHostException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    
    
    
  2. #1 楼 · xiegqooo · 2012-12-21 10:27

    下面是 tomcat 等待关闭的源代码 。 如何有退出 tomcat 。应该会明白的 。

    
    
    org.apache.catalina.core.StandardServer
    
    int port = 8005;
    ServerSocket awaitSocket;
    
        /**
         * Wait until a proper shutdown command is received, then return.
         * This keeps the main thread alive - the thread pool listening for http 
         * connections is daemon threads.
         */
        public void await() {
            // Negative values - don't wait on port - tomcat is embedded or we just don't like ports
            if( port == -2 ) {
                // undocumented yet - for embedding apps that are around, alive.
                return;
            }
            if( port==-1 ) {
                try {
                    awaitThread = Thread.currentThread();
                    while(!stopAwait) {
                        try {
                            Thread.sleep( 10000 );
                        } catch( InterruptedException ex ) {
                            // continue and check the flag
                        }
                    }
                } finally {
                    awaitThread = null;
                }
                return;
            }
            
            // Set up a server socket to wait on
            try {
                awaitSocket =
                    new ServerSocket(port, 1,
                                     InetAddress.getByName("localhost"));
            } catch (IOException e) {
                log.error("StandardServer.await: create[" + port
                                   + "]: ", e);
                return;
            }
    
            try {
                awaitThread = Thread.currentThread();
    
                // Loop waiting for a connection and a valid command
                while (!stopAwait) {
                    ServerSocket serverSocket = awaitSocket;
                    if (serverSocket == null) {
                        break;
                    }
        
                    // Wait for the next connection
                    Socket socket = null;
                    StringBuilder command = new StringBuilder();
                    try {
                        InputStream stream = null;
                        try {
                            socket = serverSocket.accept();
                            socket.setSoTimeout(10 * 1000);  // Ten seconds
                            stream = socket.getInputStream();
                        } catch (AccessControlException ace) {
                            log.warn("StandardServer.accept security exception: "
                                               + ace.getMessage(), ace);
                            continue;
                        } catch (IOException e) {
                            if (stopAwait) {
                                // Wait was aborted with socket.close()
                                break;
                            }
                            log.error("StandardServer.await: accept: ", e);
                            break;
                        }
    
                        // Read a set of characters from the socket
                        int expected = 1024; // Cut off to avoid DoS attack
                        while (expected < shutdown.length()) {
                            if (random == null)
                                random = new Random();
                            expected += (random.nextInt() % 1024);
                        }
                        while (expected > 0) {
                            int ch = -1;
                            try {
                                ch = stream.read();
                            } catch (IOException e) {
                                log.warn("StandardServer.await: read: ", e);
                                ch = -1;
                            }
                            if (ch < 32)  // Control character or EOF terminates loop
                                break;
                            command.append((char) ch);
                            expected--;
                        }
                    } finally {
                        // Close the socket now that we are done with it
                        try {
                            if (socket != null) {
                                socket.close();
                            }
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
    
                    // Match against our command string
                    boolean match = command.toString().equals(shutdown);
                    if (match) {
                        break;
                    } else
                        log.warn("StandardServer.await: Invalid command '" +
                                           command.toString() + "' received");
                }
            } finally {
                ServerSocket serverSocket = awaitSocket;
                awaitThread = null;
                awaitSocket = null;
    
                // Close the server socket and return
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }
        }
    
    
    

评论功能维护中,当前仅展示历史评论。