PageRenderTime 26ms CodeModel.GetById 19ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/hudson-remoting/src/main/java/hudson/remoting/PingThread.java

http://github.com/hudson/hudson
Java | 125 lines | 61 code | 15 blank | 49 comment | 1 complexity | 2fe20d3b549889d6b5e617bead9a297a MD5 | raw file
  1/*
  2 * The MIT License
  3 * 
  4 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi
  5 * 
  6 * Permission is hereby granted, free of charge, to any person obtaining a copy
  7 * of this software and associated documentation files (the "Software"), to deal
  8 * in the Software without restriction, including without limitation the rights
  9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 10 * copies of the Software, and to permit persons to whom the Software is
 11 * furnished to do so, subject to the following conditions:
 12 * 
 13 * The above copyright notice and this permission notice shall be included in
 14 * all copies or substantial portions of the Software.
 15 * 
 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 22 * THE SOFTWARE.
 23 */
 24package hudson.remoting;
 25
 26import java.io.IOException;
 27import java.util.concurrent.ExecutionException;
 28import static java.util.concurrent.TimeUnit.MILLISECONDS;
 29import java.util.concurrent.TimeoutException;
 30import java.util.logging.Logger;
 31
 32/**
 33 * Periodically perform a ping.
 34 *
 35 * <p>
 36 * Useful when a connection needs to be kept alive by sending data,
 37 * or when the disconnection is not properly detected.
 38 *
 39 * <p>
 40 * {@link #onDead()} method needs to be overrided to define
 41 * what to do when a connection appears to be dead.
 42 *
 43 * @author Kohsuke Kawaguchi
 44 * @since 1.170
 45 */
 46public abstract class PingThread extends Thread {
 47    private final Channel channel;
 48
 49    /**
 50     * Time out in milliseconds.
 51     * If the response doesn't come back by then, the channel is considered dead.
 52     */
 53    private final long timeout;
 54
 55    /**
 56     * Performs a check every this milliseconds.
 57     */
 58    private final long interval;
 59
 60    public PingThread(Channel channel, long timeout, long interval) {
 61        super("Ping thread for channel "+channel);
 62        this.channel = channel;
 63        this.timeout = timeout;
 64        this.interval = interval;
 65        setDaemon(true);
 66    }
 67
 68    public PingThread(Channel channel, long interval) {
 69        this(channel, 4*60*1000/*4 mins*/, interval);
 70    }
 71
 72    public PingThread(Channel channel) {
 73        this(channel,10*60*1000/*10 mins*/);
 74    }
 75
 76    public void run() {
 77        try {
 78            while(true) {
 79                long nextCheck = System.currentTimeMillis()+interval;
 80
 81                ping();
 82
 83                // wait until the next check
 84                long diff;
 85                while((diff=nextCheck-System.currentTimeMillis())>0)
 86                    Thread.sleep(diff);
 87            }
 88        } catch (ChannelClosedException e) {
 89            LOGGER.fine(getName()+" is closed. Terminating");
 90        } catch (IOException e) {
 91            onDead();
 92        } catch (InterruptedException e) {
 93            // use interruption as a way to terminate the ping thread.
 94            LOGGER.fine(getName()+" is interrupted. Terminating");
 95        }
 96    }
 97
 98    private void ping() throws IOException, InterruptedException {
 99        Future<?> f = channel.callAsync(new Ping());
100        try {
101            f.get(timeout,MILLISECONDS);
102        } catch (ExecutionException e) {
103            if (e.getCause() instanceof RequestAbortedException)
104                return; // connection has shut down orderly.
105            onDead();
106        } catch (TimeoutException e) {
107            onDead();
108        }
109    }
110
111    /**
112     * Called when ping failed.
113     */
114    protected abstract void onDead();
115
116    private static final class Ping implements Callable<Void, IOException> {
117        private static final long serialVersionUID = 1L;
118
119        public Void call() throws IOException {
120            return null;
121        }
122    }
123
124    private static final Logger LOGGER = Logger.getLogger(PingThread.class.getName());
125}