Jade - which behaviour for an events loop? - java

I'm implementing a Multi-Agent System in JADE. Events are placed in a queue and will sequentially happen. An EventManager agent should go through the queue and handle them one by one.
So my EventManager should take the first event - send out messages to the other agents, whom will "solve" the event.
After the first event has been completely solved should the second event be taken and solved. (etc. for many more events)
My problem thus is which behaviour to use to implement this?
I thought about a sequential behaviour but that uses multiple behaviours sequentially while this is one behaviour (grabbing the event and solving it) multiple times, but only after the previous one has been done.
I like the idea of the generic behaviour but instead of the switch a for loop. Unfortunately it is absolute necessary that the previous event is completely solved before the next one is opened.
How to implement this ?

One important thing is here, how the communication between agents is orgainzed?
Do you get answers from all agents when they did their work? This can be archived by using communication protocols like ContractNet or something more handy.
If you have received all answers, you can start a new 'job' behaviour (can be an OneShotBehaviour for example), wait for agent answers again and finally, decide if to start a new job or terminate.

Related

Axon Framework: Saga project with compensation events between two or three microservices

I have a question about Axon Saga. I have a project where I have three microservices, each microservice has his own database, but the two "Slave" microservice has to share his data to the "Master" microservice, for that I want to use the Axon Saga. I already asked a question about the compensation, when something goes wrong, and I have to deal with the compensation by myself, it is ok, but not ideal. Currently I am using the DistributedCommandBus to communicate between the microservices, is it good for that? I am using the Choreography Saga model, so here is what it is look like now:
Master -> Send command -> Slave1 -> Handles event
Slave1 -> Send back command -> Master -> Handles event
Master -> Send command -> Slave2 -> Handles event
Slave2 -> Send back command -> Master -> Handles event
If something went wrong then comes the compensating Commands/Events backwards.
My question is has anybody did something like this with Axon, with compensation, what the best practices for that? How can I retry the Saga process? With the RetryScheduler? Add a github repo if you can.
Thanks, Máté
First and foremost, let me answer your main question:
My question is has anybody did something like this with Axon?
Shortly, yes, as this is one of the main use cases of for Sagas.
As a rule of thumb, I'd like to state a Saga can be used to coordinate a complex business transaction between:
Several distinct Aggregate Instances
Several Bounded Contexts
On face value, it seems you've landed in option two of delegating a complex business transaction.
It is important to note that when you are using Sagas, you should very consciously deal with any exceptions and/or command dispatching results.
Thus, if you dispatch a command from the "Master" to "Slave 1" and the latter fails the operation, this result will come back in to the Saga.
This thus gives you the first option to retry an operation, which I would suggest to do with a compensating action.
Lastly, with a compensating action, I am talking about dispatching a command to trigger it.
If you can not rely on the direct response from dispatching the command, retrying/rescheduling a message within the Saga would be a reasonable second option.
To that end, Axon has the EventScheduler and DeadlineManager.
Note that the former of the two publishes an event for everyone to see.
The latter schedules a DeadlineMessage within the context of that single Saga instance, thus limiting the scope of who can see a retry is occurring.
Typically, the DeadlineManager would be my preferred mode of operation for thus, unless you require this 'rescheduling action' to be seen by everybody.
FYI, check this page for EventScheduler information and this page for DeadlineManager info.
Sample Update
Here's a bit of pseudo-code to get a feel what a compensating action in a Saga Event Handler would look like:
class SomeSaga {
private CommandGateway commandGateway;
#SagaEventHandler(assocationValue = "some-key")
public void on(SomeEvent event) {
// perform some checks, validation and state setting, if necessary
commandGateway.send(new MyActionCommand(...))
.exceptionally(throwable -> {
commandGateway.send(new CompensatingAction(...));
});
}
}
I don't know your exact use case, but from this and your previous question I get the impression you want to roll back, or in this case undo, the event if one of the event handlers cannot process it.
In general, there are some things you are able to do. You can see if the aggregate that applied the event in the first place has or can have the information to check whether the 'slave' microservice should be able to handle the event before you apply it. If this isn't practical, the slave microservice can also apply a 'failure' event directly on the eventbus to inform the rest of the system that a failure state has occurred that needs to be handled:
https://docs.axoniq.io/reference-guide/implementing-domain-logic/event-handling/dispatching-events#dispatching-events-from-a-non-aggregate

Reactor Multiplexing: Dispatch event to just exactly one subscriber

I am playing a bit with Reactor right now. While trying to build a small demo game (just to get accustomed to the framework), I need the ability to have multiple "entities" subscribed to a publisher. But I also need each published event to reach exactly one subscriber. For now, they all always get it. I know that I could build some "latch" into this event so that all but one subscriber discard it.
But I think in the sea of features, there might be an operator or something that already does exactly this...
Multiple subscribers to a single publisher. Each subscriber would need to apply a different filter too though.
Each event from the publisher going only to a single subscriber in no particular order... (The filter does not guarantee uniqueness, there could be multiple subscribers using the same filter).
Randomness is cool but not required (since the subscriber will unsubscribe upon receiving this event). You might have guessed that this will be the kill signal for the entity ;).
Thanks!
Looks like UnicastProcessor does the trick.

Java - Swing UI separate socket logic

I become desperate, I develop a simple multi-user chat in Java based on the client-server principle. I already wrote a basic multi-threaded server application and it works great. My problem is the client on the basis of the Swing GUI Toolkit. A basic UI with a runtime loop for receiving messages in the background. My problem is that I want to separate the socket logic from the UI, this means that in the best case I've two different classes one for the socket runtime loop and another to manage the UI. Because of the problem, that the runtime loop must notify/add messages to the UI, they depend on each other.
MessengerView is my main class which contains the swing ui and all depended components. At the moment this class contains also the socket logic, but I want to extract them to an external class.
ClientRuntime the class which should hold the socket logic...
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
addListener(MessageArrivedListener listener);
emitMessageArrivedEvent(String message);
The problem is, that it is very confusing if the count of events raises! As already said my second options is to hold socket logic and ui design in one class, but I think it's a bad idea because it makes it very hard to write unit tests for it or to find bugs...
In my time with C++ I used sometimes friend-classes for this issue, because this makes it possible to access class members of other classes! But this solution is often also very confusing and I found no such option for Java.
So are there any other possibilities to hold the connection between the swing widgets and the socket logic, without storing them in the same class (file)?
how could I separate them and how could I connect them?
Connect them with BlockingQueue - this the first choice when choosing ways to connect threads.
ClientRuntime class must start 2 threads: one takes requests from the blocking queue and sends them to the server, and the second constantly reads the messages from the server through the socket and sends them to the UI thread. The UI thread has already input blocking queue for messages: it is accessed by SwingUtilities.invokeLater(Runnable);. The ClientRuntime class does not access UI queue directly: it calls a method from MessengerView and passes what it received from the socket, a binary array or json string, and that UI method converts it to some Runnable which actually updates the UI.
they depend on each other
Well, they don't really. The "socket" layer only cares about been started, running, posting some messages and stopping.
How all that actually get done/handled it doesn't care about, it just "starts" when told, processes input/output messages, posts notifications and "stops" when asked to.
This is basically an observer pattern, or if you prefer, a producer/consumer pattern.
So the socket layer needs to define a "protocol" of behaviour or contract that it's willing to work with. Part of that contract will be "how" it generates notifications about new messages, either via an observer or perhaps through a blocking/readonly queue - that's up to you to decide.
As for the UI, it's a little more complicated, as Swing is single threaded, so you should not block the UI with long running or blocking operations. This is where something like a SwingWorker would come in handy.
It basically acts a broker between the UI and the mechanism made available by the socket layer to receive messages. Messages come from the socket layer into the SwingWorker, the SwingWorker then publishes them onto the UI's event thread which can then be safely updated onto the UI
Maybe start with Concurrency in Swing and Worker Threads and SwingWorker
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
The problem is, that it is very confusing if the count of events raises!
I don't think so (IMHO). What you want to do is focus on the "class" of events. For example, from the above, you have "life cycle" events and you have "message" events. I'd start by breaking those down into two separate interfaces, as those interested in "message" events probably aren't that interested in "life cycle" events, this way you can compartmentalise the observers.
The important concept you want to try and get your head around is the proper use of `interfaces to define "contracts", this becomes the "public" view of the implementations, allowing you devise different implementations for different purposes as you ideas change and grow. This decouples the code and allows you to change one portion without adversely affecting other parts of the API

Vertx 3.4: Difference between running code immediately and context.runOnContext

I am trying to figure out the basics of Vertx. I was going through standard doc on it here, where I stumbled upon a section on context object. It says that it lets you run your code later by providing a method called runOnContext. The thing I don't understand is, in which case would I choose to invoke a (non-blocking) block of code later? If the code is non-blocking, it will take same amount of time, whether you execute it now or later.
Can anyone please tell me, in which case, context.runOnContext will be helpful?
Most often it will be helpful if you call it from another thread. It will schedule a task for execution by the event loop bound to this context.
If you're already on the event loop, you may also use it when you read items from a queue: instead of processing all items as a single event, you would schedule an event per item in the queue. That would give other kind of events (network, filesystem) a chance to be processed earlier.

Are there any standard techniques and/or examples of collapsing multiple events in Java?

Let me first sketch the concrete situation I find myself in, although my question is actually more general. I'm writing a component containing several sliders and I have listeners listening for events from these sliders. When one of these sliders changes I want my component to send an event to its own listeners to notify them that its state has changed. I would however like to limit the number of events that are sent, i.e. if there are several events waiting when my component notifies its listeners, I would like to collapse all these events into a single event.
My question is whether there are standard techniques for this. If so, any example would be welcome, because I couldn't find any. (Maybe collapsing is not the correct terminology?)
I believe collapsing is the correct term. An example class from the Java Core libraries that implements such behavior is RepaintManager. I would check out it's source code to see how it collapses multiple repaint requests.
Before you do any such thing you should make sure that it is really necessary.
I guess you would need to access the EventQueue from your listener. When an event triggers the callback method, this method should first look in the queue to see if there are more recent events of the relevant type and, if so, process the most recent event only and then remove all events of that type from the queue.
Since the callbacks are always on the Swing (awt) event thread, you don't need to worry about concurrency.

Categories