user882196
user882196

Reputation: 1721

How I can put a lock around InputStream and release when reading is done

I want to put a Lock around java.io.InputStream Object and lock this stream. And when I am done finished reading I want to release the lock. How can I achieve this?

Upvotes: 0

Views: 1333

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533870

Do you mean?

InputStream is =
synchronized(is) { // obtains lock
    // read is
} // release lock

Its usually a good idea to use one thread to read or write to a stream, otherwise you are likely to get some confusing and random bugs. ;)

If you want to use a Lock as well

InputStream is =
Lock lockForIs = 
lockForIs.lock();
try {
    // read is
} finally {
    lockForIs.unlock();
}

Upvotes: 1

Viruzzo
Viruzzo

Reputation: 3025

You can't just lock on the InputStream, as it wouldn't prevent write access from a relevant OutputStream; you have to check the lock any time you want to write from the OutputStream.

Upvotes: 0

Related Questions