I have an archive object which manages various byte arrays and hands out InputStream
s and OutputStream
s for reading and writing them. Each byte array has an associated ReentrantReadWriteLock
.
The constructor of the subclass of InputStream
which the archive produces acquires the lock for the relevant data, while close()
releases the lock. Now, the problem:
Suppose that I have a task which will run on another thread which needs input from the archive, is given the InputStream
as an argument before it starts, and is responsible for closing the stream when it's finished. These requirements appear to be incompatible with the locking mechanism used by my data archive, because
- The
InputStream
is created on a different thread from the one on which it is closed. - A
ReentrantReadWriteLock
must be released by the thread which owns it.
Rewriting the parts of the program which expect an InputStream
as input in order to avoid #1 is inconvenient and makes those parts less flexible. Using a kind of lock which permits change of ownership would let me avoid #2, but I don't see any locks in the Java API which can handle that and I'm not terribly keen on knocking together a custom lock if I don't have to.
What solutions are there to this problem?