Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Does SourceDataLine.write(...) mask Interrupts?

I have a Thread that loops calling SourceDataLine.write(...) until all audio data is written (played). I want to be able to stop playback prematurely (before the loop would normally be terminated by an EOF-type condition) and am (attempting) using an interrupt. When I call playbackThread.interrupt() it results in an interupt and termination of the Thread only sporatically. Minor changes in the code, or consecutive invocations, have different (seemingly random) results. I've debugged and tried using Thread.currentThread.isInterrupted() instead of Thread.interrupted(). I have noted that if I replace the SourceDataLine.write(...) call with something else (e.g. a long counting loop) the Thread does terminate predictably and consistently.

Does SourceDataLine.write(...) "consume" an interupt but not throw an InterruptedException? Meaning, does it clear the interrupt flag (possibly with Thread.interrupted()), ignore it, and simply continue? This would explain why the interrupt works intermittently: if it occurs when in the SDL.write(...) method, it is discarded; otherwise, it remains "intact" until I test with the Thread.interrupted() call. This would be terrible, but is the only explanation I can come up with after spending all day on it. I can't find any source for SourceDataLine.write(...) as it's an interface and (I suppose) the implementation is machine-dependent.

Since I'm not using try/catch and expecting to catch an InterruptedExeption in my loop, but am calling Thread.interrupted() (or Thread.currentThread.isInterrupted()) at the bottom of the loop each pass, I can easily create my own interruptFlag and test that. This is precisely what I did elsewhere when interrupting the TargetDataLine.read(...) method several months ago when rushing to meet a schedule. I've spent most of my weekend investigating once-and-for all what is at the root of this long-standing mystery with no success.

It seems more consistent/elegant to use the actual Java interrupt mechanism - but not if it doesn't work. Is this explanation plausible?

Code for playbackThread:

public void run() {
    int offset = 0;
    int remaining = cRawAudioBuffer.length;
    int length = WRITE_LENGTH;
    int bytesWritten = 0;
    cOutputLine.start();
    while (remaining>0) {
        length = Math.min(length,remaining);
        bytesWritten = cOutputLine.write(cRawAudioBuffer,offset,length);
        offset += bytesWritten;
        remaining -= bytesWritten;
        if (Thread.currentThread().isInterrupted()) {
            System.out.println("I Was interrupted");
            break;
        }
    }
    cOutputLine.close();
}

UPDATE:

Still investigating for a more complete understanding of what is going on here. I forced an interupt of the playbackThread by a call to Thread.interrupt() from within the write loop itself, and inserted calls to Thread.currentThread().isInterrupted() - thus not clearing the interrupt flag with the test itself - before and after the write() call. What I found is that for the first few loops, the interrupt is preserved after return from the write() method. After the first 3 loops, the interrupt is cleared after returning from write(). Thereafter, it is almost always, but not always, cleared after returning from write(). My guess is that if write() is blocked waiting for its buffer to clear, it will detect, ignore, and clear the interrupt flag. Still just a guess, I would prefer to be sure (to avoid propagating something I'm doing wrong and having it bite me later). Any ideas on how to verify this hypothesis without access to source?

public void run() {
    ....
    while (remaining>0) {
        length = Math.min(length,remaining);
        Thread.currentThread().interrupt();
        System.out.println("Player interrupt flag is " + (Thread.currentThread().isInterrupted()?"":"not ") + "set before write()");
        bytesWritten = cOutputLine.write(cRawAudioBuffer,offset,length);
        System.out.println("Player interrupt flag is " + (Thread.currentThread().isInterrupted()?"":"not ") + "set after write()");
        offset += bytesWritten;
        remaining -= bytesWritten;
        if (Thread.interrupted()) {
            System.out.println("I Was interrupted");
            //break;
        }
    }
    cOutputLine.close();
}
like image 423
ags Avatar asked Jun 10 '26 04:06

ags


2 Answers

As it turns out, SourceDataLine.write() blocks during the write and if an iterrupt occurs during that write it is ignored and the interrupt flag is reset. There is no way to directly detect the interrupt. I suppose this is common knowledge for folks using Java Audio, there's no way to create a reliably interruptable audio playback without understanding this. I will (sadly) have to resort to a syncrhonized flag that is read after each write() to detect the interrupt.

like image 187
ags Avatar answered Jun 11 '26 21:06

ags


The problem you have is that most of the time is spent in cOutputLine.write which doesn't stop due to interrupts. This means you loop needs to write some data before it can check for the interrupt. If this blocks (due to a full buffer) it will never check the interrupt.

One way around this is to close the stream which will trigegr an IOException in the write. Or you might be able to use blocking NIO (it doesn't have to be non-blocking) which does stop when the thread is interrupted.

like image 27
Peter Lawrey Avatar answered Jun 11 '26 21:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!