0

I have two threads created from the same process that are servers in two different server/client chats. What i want is this : When a specific event happens in one server (like a button press) that thread has to notify somehow the other thread. Is there a way to use java events for this purpose ? Is there an alternative?

EDIT: Is there another way to do it other than checking a variable inside method run all the time ? I was thinking something like signals in C for example where you can handle signals asynchronously with the use of signal handlers.

mark4rd
  • 255
  • 5
  • 12
  • 4
    Take a look at http://stackoverflow.com/questions/6916398/communicating-between-two-threads – Radiodef May 17 '15 at 19:11
  • 1
    Please if you want to downvote my question then it's fine , but it would be helpful to write in the comments the reason you do that so I can understand and perhaps make better questions in the future. – mark4rd May 17 '15 at 22:07

1 Answers1

1

Event bus / Message Bus

An event bus (aka message bus) is a simple way to let objects indirectly invoke code on one another without explicitly referencing one another.

Some objects register their interest in certain types of events/messages by signing up with a message bus object. Objects generating such events/messages publish them by calling the message bus. The message then iterates through all the registrants to invoke a certain method tagged with a certain annotation.

Google Guava provides such an event bus. But I don't recommend it because they inexplicably use strong references. That means you must be rigorous in always de-registering any subscribing objects that should otherwise qualify for garbage collection.

I do recommend using the MBassador project. Be default it uses weak references. And you can easily call it asynchronously.

Message Queue

A message queue is another way to let objects anonymously communicate with one another. But a message queue is different from an event bus in a few ways.

  • A message queue usually has a payload of a short piece of text, not an object.
  • A message queue is passive, queueing up messages and waiting for other objects/systems to inquire for fresh messages. An event bus is active in that it invokes a method on each of the registered subscriber methods.
  • A message queue is usually external to an app, a separate process, meant for separate systems to communicate. However, you can have a message queue within your app if you wish.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154