I think there's probably a name for what I'm describing here, but I don't know it. So my first question would be to know the name of this technique.
Here's an example: suppose you're implementing live search on a web page. Everytime the user types in the search box, you fire a new search query, and the results are updated as often as possible.
This is a stupid thing to do because you'll send much more queries than you actually need. Sending a request once per 2-3 letters or at most once per 100 ms is probably sufficient.
A technique is thus to schedule the queries to be executed soon after a key is typed, and if there are still queries that were planned but not executed, cancel them since they're obsolete now.
Now more specifically, are there specific patterns or librairies for solving this problem in Java ?
I had to solve the problem in a Swing app, and I used an ExecutorService, which returned ScheduledFutures that I could cancel. The problem is that I had to manually create a Runnable for each method call I wanted to "buffer", and keep track of each Future to cancel it.
I'm sure I'm not the first person to implement something like this, so there must be a reusable solution somewhere ? Possibly something in Spring with annotations and proxies ?
Given the other answers, and after some searching, it seems there's indeed no library that does what I wanted.
I created one and put it on GitHub. Future readers of this question may find it interesting.
https://github.com/ThomasGirard/JDebounce
I don't think it's very good yet but at least it works and can be used declaratively:
#Debounce(delayMilliseconds = 100)
public void debouncedMethod(int callID, DebounceTest callback) { }
This is not solvable in Java without using some extra infrastructure like you did with executor and futures. It is not possible to solve this in syntactically concise manner in Java.
You will always need some sort of method result wrapper, because the mechanism returns immediately but the actual result is retrieved later. In your case this was accomplished via Future.
You will always need to be able to specify code to be executed in a manner that will allow delayed execution. In most languages this is accomplished using function pointers or function values or closures. In Java, lacking these language features, this is usually accomplished by passing an object that implements some sort of interface such as Runnable, Callable, that allows delayed execution of a block of code. There are other options but none of them are simple, such as using a dynamic proxy.
tl;dr
Can't do this in concise manner in Java.
What you need is called debouncing. You should check the jQuery Throttle/Debounce plugin (which is btw totally independent of jQuery except for using the same namespace). What you need is covered by the debounce part:
Using jQuery throttle / debounce, you can pass a delay and function to
$.debounce to get a new function, that when called repetitively,
executes the original function just once per “bunch” of calls,
effectively coalescing multiple sequential calls into a single
execution at either the beginning or end.
Underscore.js has the same method:
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
// example: debounce layout calculation on window resize
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
[Edit]
I mistakenly read "Javascript" instead of Java. Actual Java solution was written by OP afterwards.
Related
I have read through the Javadocs for the reactor.core.publisher.Mono class From project reactor However I still don't understand what's the point of having the Mono.never() method.
What are some example use cases where one would use Mono.never()?
It is very often used in tests (typically to assert timeout behavior), but can also have production usage: some operators take a control Publisher as parameter in various situations where they need an asynchronous external signal to tell them to trigger some behavior. If in some cases you don't want said behavior to trigger, user never().
For instance, windowWhen takes such parameter both for opening and closing windows (the later generated by a Function). Conditionally returning a Mono.never() you could have a window that never closes.
I apologize if there's already an answer to my question, but I couldn't find a solution. I want to make an application which basically has two text fields and two combo boxes where you choose a increment step, and when you click start you can see the numbers change in different steps in each text box every second. I managed to do it in a single file using two threads, but I want to do it the MVC way. In other words, I have a Controller class which handles the View click, and runs a thread from my Model class, which returns the value on every iteration of the loop, and then I pass that value to the JTextField.setText() method to visualize it. In a single class I can easily do it in the loop itself:
while(!isInterrupted()){
count += step;
textField1.setText(count);
sleep(1000);
}
However, I think there are two ways to do it. Pass a reference of the View to the Model, and manipulate the text field from the Model class, which I feel counters the idea of the MVC to separate the model and the view. Or use a Callable or a Future somehow (I don't really know how they work, and if they will work in my case) to pass the count value on every iteration of the while loop to the Controller, which in turn is going to pass it on to the View.
How do you think I should do it, and is there any other (better) way of doing it?
You should read up on Event Handling in Java and Listeners.
The basic gist is: You want your GUI to be updated. More specific - you want it to be notified, when to update itself.
Solution : Listeners.
What's that? I linked to the oracle lesson in my comment, but basically you "register" your gui to be notified of some sort of event at the model. That is done by providing some Interface, that your gui will implement - for example an interface that declares a method 'onMyValueChanged( int oldVal, int newVal )'. You will then add a reference to the gui at the model. The model would then use that reference to call the Listener interface when appropriate.
Mind that you should manipulate GUI Elements from the GUI-Thread (aka "EDT" = "Event Dispatch Thread"), only. So you will probably have to do some inter-thread communication in the listener implementation.
A convenient means of doing all the above is using SwingPropertyChangeSupport. See How to write a PropertyChangeListener for examples and further explanation.
Another way of meeting your requirement would be to use a SwingWorker and publish changes in the process. A good starting point would be this tutorial from oracle: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
And this section about the EDT is definitely for you: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
As a sidenote, I can really recommend those Oracle Lessons. They are an informative read and they are free. They really helped me a lot when I was a beginner and they still do frequently as look-up for things I do not use frequently.
I am trying to access a global event created by native code in my java client. I am using JNA for this purpose to call OpenEvent method of kernel32.dll. But the method always returns NULL and GetLastError returns 2, which is File not found.
So I was wondering if JVM can see these global events and if so is there any other approach I can use?
--
Vinzy
How do you call your openEvent?
I suppose it's something like this
int result = kernel32.OpenEvent( 10000, false, "Global\\nameOfEvent" ); //request for deletion
with the only difference you may be using objects as arguments, which, I suppose, is a matter of preference.
Maybe if you provide the code for the call we might be able to help you. Another thing to be asked is if you call CreateEvent in your native code somewhere. If you dig into the Windows API, you will notice that:
"The function succeeds only if some
process has already created the event
by using the CreateEvent function."
source : http://msdn.microsoft.com/en-us/library/ms684305(v=vs.85).aspx
Which in your situation mean you will be in a lot trouble if you were not the one creating the event. There is a way of obtaining a handle to an event you did not create but it's a bit more complicated and let's start by you providing a bit more information.
Cheers.
To sum it up:
If you don't call CreateEvent anywhere in your code you will have trouble when calling OpenEvent. To escape this problem you would basically have to find which process/thread holds the lock to the event and make it give it to your thread (the jvm's).
If you do call CreateEvent in your code then you should not have any problems obtaining a reference to your event and the culprit is somewhere else.
In any case, a bit more code would be nice.
I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project
I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html