سؤال

I have a class that calls an interface, like the below:

interface MessageReceiver{
  public void messageReceived(Message m);
}

However, because I am receiving messages from multiple sources that I need to synchronise I would instead like to have code that blocks on receiving messages. i.e. I would like to implement the following (blocking) interface, so my calling process can block on a new message coming in:

public Message getNextMessage();

However, my attempts so far end up getting bogged down with Thread synchronisation and locking issues... when really this could be done on the same Thread (concurrency is not required), but I am not sure how, without delving into assembler... and for that, java is probably not the easiest language to do this...

Thanks in advance!

هل كانت مفيدة؟

المحلول

Create intermediate object with a blocking queue inside. Register it as a MessageReceiver.

class Channel implements MessageReceiver {
  BlockingQueue q=new ArrayBlockingQueue();

  public void messageReceived(Message m) {
     q.put(m);
  }

  public Message getNextMessage() {
    return q.take();
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top