Is event listener using CPU time - events

Maybe this is a dumb question, but do event listeners use CPU cycles like a timer, or are they inactive until the event is fired?
Is it language specific, or do all languages handle this basically the same?
I want to write a tiny service that only does anything when a network disconnect event is fired, and I don't want the service to use up resources just listening (other than memory of course).
I plan to do something like this
using NetworkUtilities;
ManagementEventWatcher networkAdapterArrivalWatcher = new ManagementEventWatcher("\\root\\wmi","SELECT * FROM MSNdis_NotifyAdapterArrival ");
networkAdapterArrivalWatcher.Options.Timeout = new TimeSpan(0,0,5);
ManagementEventWatcher networkAdapterRemovalWatcher = new ManagementEventWatcher("\\root\\wmi","SELECT * FROM MSNdis_NotifyAdapterRemoval " );
networkAdapterRemovalWatcher.Options.Timeout = new TimeSpan(0,0,5);
ConnectionNotifierHandler handler = new ConnectionNotifierHandler();
networkAdapterArrivalWatcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
networkAdapterRemovalWatcher.EventArrived += new EventArrivedEventHandler(handler.Removed);
//Start watching for events
networkAdapterArrivalWatcher.Start();
networkAdapterRemovalWatcher.Start();
public void Arrived(object sender, EventArrivedEventArgs e)
{
using (ManagementBaseObject ev = e.NewEvent)
{
//Log the event
}
}
public void Removed(object sender, EventArrivedEventArgs e)
{
using (ManagementBaseObject ev = e.NewEvent)
{
//Log the event
}
}

In C#, events are merely function delegates (pointer to function), which will be called "on demand" and won't use any extra CPU cycle.
BUT, if you are referring to monitoring events like:
OnConnecitonPending for some socket listener.
OnWindowMessage for a window application.
I think those sure use a thread to monitor their events and of course will cost extra CPU.

Event Listeners don't use any CPU time until the event is actually fired (and your Event Handler is called).
There's no background process involved with an Event Listener.

Generally, event listeners conforming to a built in event-listening system don't use CPU time until the event is fired. Rather, they are delegates that are triggered by the event. Their interest in the event is noted by the system. This is most obvious, for example, with Objective-C/Cocoa style delegates, but the principle applies just about everywhere.

Related

Apache Ignite server crashes after incorporating Auditing events

In start, it works fine, but after a certain time (1-2 hours) it crashes with the following exception in server logs.
ERROR 1 --- [-ignite-server%] : JVM will be halted immediately due to the failure: [failureCtx=FailureContext [type=CRITICAL_ERROR, err=class o.a.i.i.IgniteDeploymentCheckedException: Failed to obtain deployment for class: com.event.audit.AuditEventListener$$Lambda$1484/0x0000000800a7ec40]]
public static void remoteListener(Ignite ignite) {
// This optional local callback is called for each event notification
// that passed remote predicate listener.
IgniteBiPredicate<UUID, CacheEvent> locLsnr = new IgniteBiPredicate<UUID, CacheEvent>() {
#Override public boolean apply(UUID nodeId, CacheEvent evt) {
System.out.println("Listener caught an event");
//--- My custom code to persists the event in another cache
};
IgnitePredicate<CacheEvent> remoteListener = cacheEvent -> {
return true;
};
// Register event listeners on all nodes to listen for task events.
UUID lsnrId = ignite.events(ignite.cluster()).remoteListen(locLsnr, remoteListener, EVT_CACHE_OBJECT_PUT, EVT_CACHE_OBJECT_REMOVED);
}
}
As I understand you, you try to perform cache operations in event listener:
//--- My custom code to persists the event in another cache
Event listeners are called under the locks and this is bad idea to make any other cache operations in listeners. I suppose it could be the root cause of your issue.
Try to change you design, for example you can add your caught event in a queue and then read this queue in another thread and save the data in another cache.

Xamarin Forms Map Viewable Area event handler

I have a Xamarin form map on my screen and I'm using PropertyChanged event to retrieve geolocation information from my server and display the proper pins on screen.
While coding the solution I noticed the PropertyChanged event is triggered multiple times (up to 10 times) with a single zoom or drag action on the map. This causes unnecessary calls to server which I want to avoid.
Ideally I want to make only one call to server when the final PropertyChanged event is called but I cant's find an easy solution to implement this.
At this point I've added a refresh button to my page that becomes enabled when a PropertyChanged event happens and I disable it after user uses the button.
Obviously this fixed the too many calls to server but made the solution manual.
I was wondering if there is a more elegant way to make the server call but do it automatically.
Thanks in advance.
I just test the PropertyChanged event on iOS side and it just triggered one time with a single zoom or drag action on the map.
While if it really triggered multiple times, you can use a timer to call the server when the final PropertyChanged event is called, for example:
public partial class MapPage : ContentPage
{
Timer aTimer;
public MapPage()
{
InitializeComponent();
customMap.PropertyChanged += CustomMap_PropertyChanged;
}
private void CustomMap_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (aTimer != null)
{
aTimer.Enabled = false;
aTimer.Stop();
aTimer.Close();
}
aTimer = new Timer();
aTimer.Interval = 1000;
aTimer.Enabled = true;
aTimer.Elapsed += ATimer_Elapsed;
aTimer.Start();
}
private void ATimer_Elapsed(object sender, ElapsedEventArgs e)
{
aTimer.Stop();
//do web request
Console.WriteLine(sender);
Console.WriteLine("CustomMap_PropertyChanged");
}
}
In the above code, I set the Interval = 1 second, that means in 1 second, whatever how many times PropertyChanged triggered, only the last call will trigger the ATimer_Elapsed function.
The Interval can be set to any value depending on your requirement.

disruptor producer too fast for consumer

I am using a disruptor for some business logic which publishes to another disruptor that handles IO. The events published to the IO disruptor can arrive too fast to construct and validate the IO. Well, that's kind of the point...
The IO disruptor is setup like this:
disruptor = new Disruptor<>(factory, RING_SIZE, executor, ProducerType.SINGLE, new BlockingWaitStrategy());
disruptor.handleEventsWith(new Logic(disruptor, io));
Then the Logic event handler is setup like this:
public void onEvent(FixEvent event)
{
quickfix.Message ioMessage = event.message;
quickfix.SessionID receiver = event.session;
Log.debug("message: " + event.message.toString());
SessionID id = new SessionID(receiver.getBeginString(), "MYFX", receiver.getTargetCompID());
Session session = Session.lookupSession(id);
Log.debug("message: " + ioMessage.toString());
session.send (ioMessage);
}
and what's happening is by the time you get to send (ioMessage) there's been a new event which is somehow overwriting the ioMessage, and therefore duplicate messages are being sent out.
What can you suggest?
The answer looked like it was to finalize the event handler variables and use a synchronized final lock on the event as follows:
private final Object lock = new Object();
public void onEvent(final FixEvent event, final long sequence, final boolean endOfBatch)
{
synchronized(lock)
{
...
It didn't work unless the lock was final. It didn't work with a static final lock. It didn't work synchronizing on anything else other than a final lock, ie synchronizing on the final event didn't work.
Then it worked 1 time, at band camp, then stopped working...

How can a JSF/ICEfaces component's parameters be updated immediately?

I have an ICEfaces web app which contains a component with a property linked to a backing bean variable. In theory, variable value is programmatically modified, and the component sees the change and updates its appearance/properties accordingly.
However, it seems that the change in variable isn't "noticed" by the component until the end of the JSF cycle (which, from my basic understanding, is the render response phase).
The problem is, I have a long file-copy operation to perform, and I would like the the inputText component to show a periodic status update. However, since the component is only updated at the render response phase, it doesn't show any output until the Java methods have finished executing, and it shows it all changes accumulated at once.
I have tried using FacesContext.getCurrentInstance().renderResponse() and other functions, such as PushRenderer.render(String ID) to force XmlHttpRequest to initialize early, but no matter what, the appearance of the component does not change until the Java code finishes executing.
One possible solution that comes to mind is to have an invisible button somewhere that is automatically "pressed" by the bean when step 1 of the long operation completes, and by clicking it, it calls step 2, and so on and so forth. It seems like it would work, but I don't want to spend time hacking together such an inelegant solution when I would hope that there is a more elegant solution built into JSF/ICEfaces.
Am I missing something, or is resorting to ugly hacks the only way to achieve the desired behavior?
Multithreading was the missing link, in conjunction with PushRenderer and PortableRenderer (see http://wiki.icesoft.org/display/ICE/Ajax+Push+-+APIs).
I now have three threads in my backing bean- one for executing the long operation, one for polling the status, and one "main" thread for spawning the new threads and returning UI control to the client browser.
Once the main thread kicks off both execution and polling threads, it terminates and it completes the original HTTP request. My PortableRenderer is declared as PortableRender portableRenderer; and in my init() method (called by the class constructor) contains:
PushRenderer.addCurrentSession("fullFormGroup");
portableRenderer = PushRenderer.getPortableRenderer();
For the threading part, I used implements Runnable on my class, and for handling multiple threads in a single class, I followed this StackOverflow post: How to deal with multiple threads in one class?
Here's some source code. I can't reveal the explicit source code I've used, but this is a boiled-down version that doesn't reveal any confidential information. I haven't tested it, and I wrote it in gedit so it might have a syntax error or two, but it should at least get you started in the right direction.
public void init()
{
// This method is called by the constructor.
// It doesn't matter where you define the PortableRenderer, as long as it's before it's used.
PushRenderer.addCurrentSession("fullFormGroup");
portableRenderer = PushRenderer.getPortableRenderer();
}
public void someBeanMethod(ActionEvent evt)
{
// This is a backing bean method called by some UI event (e.g. clicking a button)
// Since it is part of a JSF/HTTP request, you cannot call portableRenderer.render
copyExecuting = true;
// Create a status thread and start it
Thread statusThread = new Thread(new Runnable() {
public void run() {
try {
// message and progress are both linked to components, which change on a portableRenderer.render("fullFormGroup") call
message = "Copying...";
// initiates render. Note that this cannot be called from a thread which is already part of an HTTP request
portableRenderer.render("fullFormGroup");
do {
progress = getProgress();
portableRenderer.render("fullFormGroup"); // render the updated progress
Thread.sleep(5000); // sleep for a while until it's time to poll again
} while (copyExecuting);
progress = getProgress();
message = "Finished!";
portableRenderer.render("fullFormGroup"); // push a render one last time
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
});
statusThread.start();
// create a thread which initiates script and triggers the termination of statusThread
Thread copyThread = new Thread(new Runnable() {
public void run() {
File someBigFile = new File("/tmp/foobar/large_file.tar.gz");
scriptResult = copyFile(someBigFile); // this will take a long time, which is why we spawn a new thread
copyExecuting = false; // this will caue the statusThread's do..while loop to terminate
}
});
copyThread.start();
}
I suggest looking at our Showcase Demo:
http://icefaces-showcase.icesoft.org/showcase.jsf?grp=aceMenu&exp=progressBarBean
Under the list of Progress Bar examples is one called Push. It uses Ajax Push (a feature provided with ICEfaces) to do what I think you want.
There is also a tutorial on this page called Easy Ajax Push that walks you through a simple example of using Ajax Push.
http://www.icesoft.org/community/tutorials-samples.jsf

How to pass window handle to wndproc?

I have written this code in c# application for tracking messages ...
protected override void WndProc(ref Message m)
{
// Listen for operating system messages.
switch (m.Msg)
{
case WM_CHAR:
FileStream fs = new FileStream("d:/Type.txt",FileMode.Append,FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
int no=(int)m.WParam;
sw.Write(Convert.ToChar(no));
sw.Flush();
sw.Close();
break;
}
base.WndProc(ref m);
}
I want to track messages for different window so how can I pass different window handle to wndproc ? please help me...
You'd have to register global keyboard hook instead of passing different handle. This article shows how to do that. Basic idea behind that is that you register your function for polling all keyboard-related system events (for every message) and filter out only those you need.
The functionality is achieved with SetWindowsHookEx winapi function.
You can filter all the messages in the application by calling Application.AddMessageFilter(IMessageFilter filter) at the beginning of your program.
The IMessageFilter interface has just one method:
bool PreFilterMessage(ref Message m);
That is called for every message handled by the application. There you can use m.HWnd to identify the different windows of your program.

Resources