0

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?

Eric Wilson
  • 54,930
  • 75
  • 197
  • 265
user882196
  • 1,631
  • 8
  • 23
  • 39
  • possible duplicate http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference – Trevor Arjeski Dec 01 '11 at 14:38

2 Answers2

1

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();
}
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
  • A stream doesn't have an associated lock, unless you associate it. You can lock a Lock, but unless the rest of your code also locks the same lock it won't do anything. Why do you want a `Lock`? – Peter Lawrey Dec 01 '11 at 14:46
0

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.

Viruzzo
  • 3,015
  • 12
  • 13