Philipp
Philipp

Reputation: 4799

Properly stopping a thread which is blocked in read() of InputStream

My thread reads from an InputStream, builds objects and puts them in a queue.

How should I stop this thread when it is blocked in read()?

public class InputEventReader extends Thread {

  private final BlockingQueue<ButtonEvent> eventQueue;
  private File name = new File("/dev/input/event0");
  private DataInputStream in;

  private volatile boolean run = true;

  public InputEventReader(BlockingQueue<ButtonEvent> mainButtonQueue) {
    this.eventQueue = mainButtonQueue;
  }

  public void run() {
    in = new DataInputStream(
           new FileInputStream(name));
    byte[] buffer = new byte[16];

    while (run) {
      in.readFully(buffer); // blocks here
      ButtonEvent event = new ButtonEvent(buffer);
      eventQueue.offer(event);
    }
    in.close();
  }

  public void shutdown(){
    run = false; 
    try {
      this.join(500); // Thread is blocked in read() while no data arrives, so "run" is not checked  
      in.close(); // has no effect on blocked read()
      this.join(500); 
      this.interrupt(); // has no effect on blocked read()
      this.join(500);
      if(this.isAlive()){
        // Yes, the thread is still alive here...
        // How to shut it down?
      }
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

The platform is linux 3.12 on ARM v7 hardfloat.

The JVM is

java version "1.7.0_51" 
Java(TM) SE Embedded Runtime Environment (build 1.7.0_51-b13, headless) 
Java HotSpot(TM) Embedded Client VM (build 24.51-b03, mixed mode)

Upvotes: 0

Views: 805

Answers (2)

Pat
Pat

Reputation: 2258

Exercise caution while using readFully() method of DIS, as it waits until it has read the specified amount of data. In contrast, read() method will attempt to read the specified amount of data, but it will return if it has read even less bytes. If possible, try using read() instead of readFully(). If you must use a blocking read, then take a look at this: http://hypirion.com/musings/how-to-cancel-a-blocking-read

Upvotes: 0

Brett Okken
Brett Okken

Reputation: 6306

Consider using FileChannel to read your data, as it is Interruptible.

Upvotes: 1

Related Questions