i have a java process that reads data from a socket server. Thus i have a BufferedReader and a PrintWriter object corresponding to that socket.
Now in the same java process i have a multithreaded java server that accepts client connections. I want to achieve a functionality where all these clients that i accept can read data from the BufferedReader object that i mentioned above.(so that they can multiplex the data)
How do i make these individual client threads read the data from BuffereReader single object? Sorry for the confusion.
I would strongly suggest that they don’t access the
BufferedReaderdirectly. Assuming you know the format of the data, and that each client is trying to read the same format (if that’s not the case, I can’t see how it could work at all) I would suggest creating one thread to read from theBufferedReaderand put work items in aQueue. There are lots of example of using producer/consumer queues in Java, and this is also likely to make it easier to test the client code.Having only one thread accessing the
BufferedReadermeans you don’t need to worry about defining an atomic operation that all other threads will have to content for – your reading thread effectively defines that operation by deciding to add a work item to the queue.EDIT: If all the clients should see all of the data, that reinforces my suggestion of having a single reader even further – except instead of having a
Queueof data which items are removed from, you’d have a collection which clients can read all the existing data from. You’ll need to use an appropriately thread-safe collection, but there are plenty of those in Java.EDIT: Having just read your comment which says that each client should just see the last item read from the reader, that makes it even easier. Have one thread reading the data, but just keep a single variable with a reference to “the last item read”. You probably either want to synchronize access to it or use an
AtomicReference, but both of those are easy.