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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With