简体   繁体   中英

Concurrent read/write buffer byte[] in java

I'm new to Java and I want to implement a buffer of byte[] which one thread can write into, and another thread can read from.
It sounds like it should have already been implemented in java , but I spent hours trying to find/understand several number of classes, and I didn't understand if it does what I want, and how to use it.
I saw BufferedInputStream , ByteBuffer , ByteChannel , BlockingQueue ...

Can someone please point to a more specific direction? I use SDK 1.6

If you're looking to simply stream bytes from one thread to the other, I suggest you use PipedInputStream and PipedOutputStream . Though note that it's likely you're in this position where you need a solution such as this because of a design fault.

Here is how you would do such thing, for instance:

PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
new YourReadingThread(in).start();
new YourWritingThread(out).start();

Then anything you write to out will be available for reading through in .


If you're looking for a solution to make a thread safe ByteBuffer, I would suggest you use a ReentrantReadWriteLock :

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
ByteBuffer buffer = ByteBuffer.allocate(n);

// Reading thread:
lock.readLock().lock();
buffer.get(i);
lock.readLock().unlock();

// Writing thread:
lock.writeLock().lock();
buffer.put(b,i);
lock.writeLock().unlock();

Sorry, ByteBuffer wasn't good for me cause it involves playing with the position of the buffer.
I realized all I really needed was a simple pipe (I don't know how could I forget about pipes).

I used an example from here :

PipedOutputStream output = new PipedOutputStream();
PipedInputStream input = new PipedInputStream(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM