If you cannot store all the data in memory, you can use something like this: (Uses the classic observer pattern, where one thread controls the source and the rest are notified of new data)
class Broadcaster { private final ConcurrentSkipListSet<Listener> listeners = new ConcurrentSkipListSet<Listener>(); private final BufferedReader source =
and
class Listener implements Runnable { private final Queue<String> queue = new LinkedBlockingQueue<String>(); public void send(String read){ queue.add(read); } public void run(){ while(!Thread.currentThread().isInterrupted()){ String got = queue.get(); System.out.println(got); } } }
I have not tested this thing or anything else, so have mercy if it doesn't work!
EDIT . If you have a memory limit, you can also do this:
Queue<String> queue = new LinkedBlockingQueue<String>(2000);
This will lead to an upper limit on how many items can queue in the queue, and when this limit is reached, threads that want to put items on it will have to wait (if add used, that is), so Broadcaster will block (wait) when the listeners cannot quickly use the data (while in this simple scheme, another listener might starve).
EDIT2:. When you do this, you should most likely only queue unchanging things. If you put, for example, byte[] , an impolite listener may modify the data, and other threads may be surprised. If this is somehow impossible, you should put another copy in each queue, for example. byteArray.clone() . This may result in some performance degradation.
source share