Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - signal/slots mechanism

For someone relatively new to the Java ecosystem, is there a fairly lightweight way to do what frameworks such as Qt and Django do with their signalling/receiver system, where components can say" I'm doing something", and other components can handle that in a fairly loosely-coupled manner?

I apologise in advance if this question fails the" single objective answer" test.

Edit: To add a bit more context, this is related to a database-driven application layer for a web service. Certain resources, when persisted, need to also save an audit record containing extra context information. In Django I'd do this via the signalling mechanism, or use one of several existing libraries that do just that. For a Scala program I've made my own hacky thing using callback functions, but it's easier with first class functions. I've no doubt that frameworks such as Swing provide facilities for this kind of thing, but I'm (perhaps unjustifiably) leary of adding such a dependency to what is at present a fairly vanilla application (not that Django isn't itself a massive dependency on vanilla Python!)

like image 490
Mikesname Avatar asked Sep 21 '12 20:09

Mikesname


3 Answers

In Java, at least on the UI side, this is usually done with the listener approach: you register a listener method which is called when specific events occur. It might be a bit less loosely-coupled than the Qt signal/slot mechanism though ... Another approach you might consider is the java message service, which is especially designed for loosely coupled communication in client/server systems based on the Java EE standard.

like image 132
Andreas Fester Avatar answered Sep 19 '22 10:09

Andreas Fester


If you are looking for a Java library which provides a signal/slot mechanism similar to Qt then you should have a look at sig4j. It is threadsafe, typesafe and supports different types of connections.

Note: I'm the author of this library :)

like image 35
Marcel Avatar answered Sep 20 '22 10:09

Marcel


I agree with the other comments/answers regarding event-driven programming.

You might be interested in http://eventbus.org. This allows you to broadcast/receive events globally without having to explicitly register listeners on every event producer.

like image 39
JimN Avatar answered Sep 22 '22 10:09

JimN