I'm developing a clock class for my discrete event simulation. I already have events being held in a PriorityQueue and thus sorted according to which event has the nearest event time. However there's one thing I can't get my head around. In the papers about Discrete Event Simulation that I've read, it's clearly stated that the clock jumps from events to events and therefore it is not necessary to have a clock which "ticks".
But how would this work, I have an EventScheduler class which holds the events in the PriorityQueue. So after it figures out when this next event is, could I just invoke a "setTime" method in the Clock which the EventScheduler invokes with the given time of the next event? But then It would never really run as a clock it would just keep jumping to the next event ?
I was thinking that the clock runs (ticks) and then it knows when an event will occur from the EventScheduler and when the clock reaches that time, it processes the events , updates the system state and perhaps generates an output event.
Sorry for being a bit unclear but I'm just interested in any tips on how the clock works, does it tick and then only "do" stuff when an event occurs or does it just jump from events to events?
Also is there any built in functionality in java that you suggest I could use for this? E.g. Timer class
The idea is that nothing happens without going into your event queue. Think about it: what is you clock doing during a time when it "ticks", but there are no events? Nothing. So why process those times at all?
So yes, you just go from event to event in the queue. Really, the "clock" in a discrete event is pretty much exactly what you've built: a priority queue sorted in "chronological" order and some sense of "now" that is the position in the queue.
If you pop off the head queue, then "now" could just be the head of the queue, and you're done. Often times more sophisticated models may have further features, such as the ability to detect when events are attempted to be scheduled before "now" - this is, for instance, indicative of a model that is responding too slowly: in the real world, it would always be "late" and catching up to what's going on in the simulation as a whole.
If you have e.g. a model that requires updating every second, then you have to put those events in the queue, or they don't happen. Frequently, for problems that fit the discrete event simulation model well (in my career, this has been physics-based modeling), this is not a problem: your models usually "idle" when there are no events, and can have their state calculated at any particular time in the future when no events change their state.
If this is not true of your models, then perhaps discrete event modeling is not really a good fit for your problem domain.
java.util.concurrent package ( available since Java 5) helps in building concurrent applications that can benefit from multicore systems and in DES applications.
here is a list of items designed for such applications.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html
Related
I want to process multiple events in order of their timestamps coming into the system via multiple source systems like MQ, S3 ,KAFKA .
What approach should be taken to solve the problem?
As soon as an event comes in, the program can't know if another source will send events that should be processed before this one but have not arrived yet. Therefore, you need some waiting period, e.g. 5 minutes, in which events won't be processed so that late events have a chance to cut in front.
There is a trade-off here, making the waiting window larger will give late events a higher chance to be processed in the right order, but will also delay event processing.
For implementation, one way is to use a priority-queue that sorts by min-timestamp. All event sources write to this queue and events are consumed only from the top and only if they are at least x seconds old.
One possible optimisation for the processing lag: As long as all data sources provide at least one event that is ready for consumption, you can safely process events until one source is empty again. This only works if sources provide their own events in-order. You could implement this by having a counter for each data source of how many events exist in the priority-queue.
Another aspect is what happens to the priority-queue when a node crashes. Using acknowledgements should help here, so that on crash the queue can be rebuilt from unacknowledged events.
What is both faster and "better practice", using a polling system or a event based timer?
I'm currently having a discussion with a more senior coworker regarding how to implement some mission critical logic. Here is the situation:
A message giving an execution time is received.
When that execution time is reached, some logic must be executed.
Now multiple messages can be received giving different execution times, and the logic must be executed each time.
I think that the best way to implement the logic would be to create a timer that would trigger the logic when the message at the time in the message, but my coworker believes that I would be better off polling a list of the messages to see if the execution time has been reached.
His argument is that the polling system is safer as it is less complicated and thus less likely to be screwed up by the programmer. My argument is that by implementing it my way, we reduce the reduce the computational load and thus are more likely execute the logic when we actually want it to execute. How should I implement it and why?
Requested Information
The only time my logic would ever be utilized would almost certainly be at a time of the highest load.
The requirements do not specify how reliable the connection will be but everyone I've talked to has stated that they have never heard of a message being dropped
The scheduling is based on an absolute system. So, the message will have a execution time specifying when an algorithm should be executed. Since there is time synchronization, I have been instructed to assume that the time will be uniform among all machines.
The algorithm that gets executed uses some inputs which initially are volatile but soon stabilize. By postponing the processing, I hope to use the most stable information available.
The java.util.Timer effectively does what your colleague suggests (truth be told, in the end, there really aren't that many ways to do this).
It maintains a collection of TimerTasks, and it waits for new activity on it, or until the time has come to execute the next task. It doesn't poll the collection, it "knows" that the next task will fire in N seconds, and waits until that happens or anything else (such as a TimerTask added or deleted). This is better overall than polling, since it spends most of its time sleeping.
So, in the end, you're both right -- you should use a Timer for this, because it basically does what your coworker wants to do.
I have been trying to find a solution to this question for a while. What is the best practice for writing a swing event buffer? The idea is when triggering an action from a mouse gesture, such as 'mouseMoved', as the events may be fired many times, I only want to trigger the last call - for example,
if the mouse was clicked five times, while the first click listener is being executed, and four are queued, the next call will be the fifth one - all previous ones will be skipped.
It seems that I should be using the Executor class, as it can remove unsubmitted tasks, but I am still not quite sure. All help is appreciated!
user1291492 is right, this shouldn't happen at all. You should never run any code that could take longer than a couple of milliseconds to complete in an event handler. The SwingWorker documentation contains examples and explanations on how to do it. The most important quotes is
Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
To address the original question, there are two patterns I usually employ:
Use flags to mark actions that should be executed at some point in the future. When there's no other work for some time I check all the flags, reset them and perform the appropriate actions.
When scheduling work for a worker thread, hold a reference to it. Every time before scheduling new work, cancel the previously scheduled work. Most often used with CancellationTokens in C#/Async.
How would one go about implementing a mouselistener (or some other way, doesn't matter) that will handle a mouse click event at ANY part of the program? Preferably returning to the line it left off at when the click event handler method completes.
I am using swing. The 'context' is a GUI that constantly updates, but must respond to a mouse click from the user at any time with no delay. Indeed I do have experience with events, using and overwriting their handlers etc., not too in-depth I suppose but what i do know has been sufficient in anything until now.
I could not understand your first para, so my answer goes for your second para, if I understood that correctly. ;)
Swing follows single thread model. So, you should be updating the UI from Event Dispatch Thread (EDT). This thread is responsible for delivering the events to your code too, hence the name. If you are continuously updating an UI in a loop then that is going to keep the EDT busy and blocked. The end effect will be an UI which does not respond to user events. This because the events are getting queued and EDT can pick them and deliver them to your code when it becomes free.
Games typically encounter this kind of scenario. You might have noticed that games typically have one fixed rate of refresh which they call FPS (Frames Per Second). Typically maintaining 60 FPS is good enough. That is, you need to draw your UI 50 times per second, but right now it seems that your render loop (which updates the UI) is running continuously.
You need to have separate thread continuously running which is responsible for drawing the UI. This should draw into a buffer (Image). And then invoke repaint() on the UI element to be updated. That UI element's paintComponent() needs to overridden, so that it can copy the image in Image buffer and paint that on the graphics context.
Now comes the real trick. The loop which calls repaint() must do some arithmetic to make sure it does not go beyond drawing 60 times, i.e. looping 60 times, per second. If and when it does then it must call Thread.sleep(sleepTime), where sleepTime is the number of milliseconds left in a second after looping 60 times. It might happen sometime that your loop may take more than a second to complete 60 iterations, then don't just go ahead for next iteration, but call Thread.yield(). This will give other threads a chance to use the CPU, e.g. maybe your EDT. To make the matter more complicated, do not keep yielding always, so might want to put some logic to make sure that yield for only x consecutive times. This last scenario should be very rare, if at all. This scenario means the system is under heavy load.
Remember, repaint() is thread safe and allowed to be called from any thread. It schedules a paint() call on EDT. So, calling repaint() does not guarantee a paint. So, you may want to experiment with different values of FPS to find the one which suites you.
By the way, the trick of rendering to an in-memory Image is technically called Double buffer. This gives us the ability to render nice smooth animations.
Further reading:-
LANSim - Wrote this code a long time back. You can use this code as an example.
http://java.sun.com/docs/books/performance/1st_edition/html/JPSwingThreads.fm.html
Killer Game Programming in Java - This book is on this subject.
Have you looked at SwingWorker? It's a simple framework that lets you run computations in the background and periodically publish updates to the GUI thread.
In my Java program, I have a text component that can fire events in rapid succession. Since I'm doing a lot of background processing whenever the text is modified, this can noticeably decrease the responsiveness of the text component. That's why I'd like to introduce a delay: When the text component starts firing, the attached listener should wait for a certain amount of time (e.g. 1 second) until the text component has "calmed down", and then start its own processing.
I know that it's relatively easy to roll my own simple delay mechanism that does what I want, but I'm wondering if the java.util.concurrent package (or some other system package) has a ready-made solution for this. I've been looking into
Executors.newScheduledThreadPool(int)
but this doesn't seem to be what I'm looking for, since this will fire all incoming events - I only want exactly one event to make it through to the listener after the delay.
Thanks in advance.
You're very close to the solution.
What you want is to schedule a firing of the listener to happen one second in the future, but to cancel that when the next event arrives (if it hasn't already happened) and reschedule. Using an executor is reasonable, but the key is that you need to keep around the Future object that scheduling returns, as it is that which you cancel.