Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have native support for events, similar to that of C#?

Tags:

java

events

I'm a bit confused from what I've heard Java doesn't do events.

But I know that it does GUI events.

Am I missing something? Does java have an event handling mechanism?

I'm aware that I can implement a publisher subscriber pattern, but I'm looking for native support within Java.

I seem to remember something about Java Adding events in either Java 5 or 6 but I can't remember where I heard this and I may be making it up.

Basically I'm wrapping a device in a java class the device throws events, and I'm looking for the most logical way of exposing this. I come mostly from a .Net Background and I'm looking for something like the events in .Net (C#)

Any help would be appreciated.

like image 451
Omar Kooheji Avatar asked Jan 12 '09 16:01

Omar Kooheji


3 Answers

As you already stated, you can do the exact same thing with the publisher-subscriber/Observer pattern. It just requires a bit more legwork.

And no, Java does not have native support for events, like C# does with delegates.

like image 68
Simon B. Jensen Avatar answered Oct 18 '22 13:10

Simon B. Jensen


The Subscribe/Publish mechanism proposed by others here will let you implement synchronous events. For asynchronous event loops (fire and forget) You may want to look at "actors". An Actor<A> consists of a handler for messages (events) of type A, as well as a threading strategy for executing the handler. This lets you do concurrent, asynchronous event handling like the following:

public class EventExample {
  public static void main(String[] args) {
    while ((char c = System.in.read()) >= 0) {
      eventHandler.act(c);
    }
  }

  public static Actor<Character> eventHandler =
    Actor.actor(Strategy.simpleThreadStrategy(), new Effect<Character>() {
      public void e(Character c) {
        // Do something with c here.
      }
    });
}

Get the actors library here. See the Javadoc here.

like image 25
Apocalisp Avatar answered Oct 18 '22 14:10

Apocalisp


From what I remember of Java (haven't worked with it in > 6 months), I don't think there are events ala .NET. Your best bet will probably be to make use of the publisher/subscriber pattern. It's pretty easy to implement and pretty reliable.

like image 30
Matthew Brubaker Avatar answered Oct 18 '22 13:10

Matthew Brubaker