Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Sep 14, 1999

Inactivity Timeout

I'd like incorporate an inactivity timeout for an application. When there is no mouse or keyboard activity in the application for a certain period of time, I want to close all the windows and dialogs of the application.

The easiest way to implement an inactivity timeout is to keep track of the last time a MouseEvent or KeyEvent was sent to an application. In a separate thread, set a timer that checks periodically if the difference between the current time and the timestamp is greater than the timeout interval.

The following program demonstrates this technique. TimeoutListener keeps track of the last InputEvent sent to the application by implementing MouseListener, MouseMotionListener, and KeyListener. Each time any one of those interface methods is called, TimeoutListener records the current time. TimeoutListener also implements the ActionListener interface so that it may be used with the Swing Timer class.

Every time the Timer expires, it invokes the actionPerformed method in its registered ActionListener. TimeoutListener calculates the difference between the the last recorded time and the current time when this happens. If it is greater than the timeout value, it exits. The Timer class may be active in a separate thread, so it is necessary to avoid race conditions by protecting the time recording and testing with a synchronized block.

The problem with this approach is that it is slightly inaccurate due to the polling. The actual inactivity timeout will be a value between the specified timeout and the timeout plus the polling period. To obtain a more accurate timeout, you can forego polling, set the Timer delay to the timeout value, and restart the Timer every time an event is delivered. When the timer expires, have its ActionListener exit the application. This approach may have a higher overhead because restarting the Swing Timer involves removing the timer from a queue and adding it again in addition to cancelling pending firings.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class TimeoutListener implements MouseListener,
				 KeyListener, ActionListener
  Object _lock;
  long _timeout, _lastTime;

  public TimeoutListener(long timeout) {
    _lock     = new int[1];
    _timeout  = timeout;
    _lastTime = System.currentTimeMillis();

  private void __recordLastEvent(InputEvent event) {
    synchronized(_lock) {
      _lastTime = System.currentTimeMillis();
      System.out.println("Last Event: " + _lastTime + " " + event);

  public void actionPerformed(ActionEvent e) {
    synchronized(_lock) {
We really shouldn't exit, but cleanup gracefully instead
      if(System.currentTimeMillis() - _lastTime >= _timeout) {
	System.out.println("Timed out! " + System.currentTimeMillis());
      } else
	System.out.println("Still active.");

  public void mouseDragged(MouseEvent e) { __recordLastEvent(e); }
  public void mouseMoved(MouseEvent e)   { __recordLastEvent(e); }
  public void mouseClicked(MouseEvent e) { __recordLastEvent(e); }
  public void mouseEntered(MouseEvent e) { __recordLastEvent(e); }
  public void mouseExited(MouseEvent e)  { __recordLastEvent(e); }
  public void mousePressed(MouseEvent e) { __recordLastEvent(e); }
  public void mouseReleased(MouseEvent e){ __recordLastEvent(e); }
  public void keyPressed(KeyEvent e)     { __recordLastEvent(e); }
  public void keyReleased(KeyEvent e)    { __recordLastEvent(e); }
  public void keyTyped(KeyEvent e)       { __recordLastEvent(e); }

public class Timeout {

  public static final int TIMEOUT = 10000;  // milliseconds
  public static void main(String[] args) {
    Frame frame = new Frame("Progress Demo");
    WindowListener exitListener;
    TimeoutListener timeoutListener;
    Timer timer;

    exitListener = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        Window window = e.getWindow();

    timeoutListener = new TimeoutListener(TIMEOUT);
    frame.setSize(400, 400);
We poll at half the timeout interval to reduce the fudge factor introduced by events delivered at just under the timeout value.
    timer = new Timer(TIMEOUT / 2, timeoutListener);
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date