I have read this page over several times, and am just not seeing some of the inherent differences between GWT's Timer and Scheduler classes. I'm looking for the use cases and applicability of each of the following:
Timer, Timer::schedule and Timer::scheduleRepeating
Scheduler::scheduleDeferred
Scheduler::scheduleIncremental
IncrementalCommand
DeferredCommand
These all appear to be doing the same thing, more or less, and it feels like you can accomplish the same objectives with all of them. Is this just GWT's way a providing multiple ways of doing the same thing? If not, please help me understand when and where each is appropriately used.
Use Scheduler when you need a browser to complete whatever it is currently doing before you tell it to do something else. For example:
myDialogBox.show();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
myTextBox.setFocus();
}
});
In this example, focus will not be set until the browser completes rendering of the dialog, so you tell the program to wait until the browser is ready.
Use Timer if you want some action to happen after a specified period of time. For example:
notificationPanel.show();
Timer timer = new Timer() {
#Override
public void run() {
notificationPanel.hide();
}
};
timer.schedule(10000);
This code will show notificationPanel, and then it will hide it after 10 seconds.
As the JavaDoc says, DeferredCommand is deprecated in favor of Scheduler.
The problem with DeferredCommand and IncrementalCommand is that they have a static state (which makes it hard to use reliably in tests). Moreover, their (static) methods make JSNI calls which forces you to use a GWTTestCase to test your code (static methods aren't –easily– mockable). Static methods also make it impossible to wrap them (to, e.g. add some logging or whatever).
On the other hand, you work with an instance of a Scheduler (if you want testable code, you'll use dependency-injection to get a instance of a scheduler and will never call Scheduler.get() except in your DI "factory"). In a test, you can then use a StubScheduler for instance.
Then there's Timer, which is similar to the others but the scheduled task can be cancelled. Note that Timer makes use of JSNI too, just like DeferredCommand; any kind of code that uses a Timer will need a GWTTestCase to be unit-tested.
Related
My background is mainly in JavaScript, where functions are first-class objects and I can pass them around easily as callbacks. That is very much the way of JavaScript.
Now I am attempting to build a simple Java app. The problem at hand is to (1) use Swing to let the user browse to a file to open, and then (2) do some stuff with it. Let's say I have a method like this
void doStuff(File file) {
//stuff
}
that needs to run on the file chosen by the user. In JavaScript, the doStuff function would simply be passed as a callback. How would one do this in Java?
I'm aware that it is possible to do callbacks in Java by, say, making a Callback interface with a void run() method. But is that idiomatic? How should this kind of thing be done? How would an experienced Java programmer choose to do it?
Also, when I use callbacks, it looks like nearly everything happens on the Event Dispatch Thread. I suppose I could, from the EDT, create a new third thread, but it seems like my doStuff function should be executing on the main thread. And I can't figure out any way to make that happen. Nor do I know if it's necessary or desirable to make it happen.
Put simply, "do stuff" will parse and import data from the file.
Since this involves file or resource input, then it should not be done on the EDT. The best solution IMO would be to
do the importing and parsing within the doInBackground() method of a SwingWorker
add a PropertyChangeListener to the SwingWorker
have this listener listen to the worker's state property, specifically for a new value of SwingWorker.StateValue.DONE
in this listener, you'll then be notified when the worker has completed its task. You'll want to be sure to call get() on the SwingWorker when its done, so you can get any end value that you want it to produce, and so you can capture and respond to any and all exceptions that might have occurred during its run.
For more on this, please check out the tutorial -- Lesson: Concurrency in Swing
Do you suggest using SwingWorker mainly so that this process doesn't take place on the EDT, thereby locking up the user interface?
Yes. Any thread would serve that purpose though, but the main advantage of using the SwingWorker is because while it will run the process in a background thread, it also has great mechanisms for providing end and interim results on the EDT, as well as built-in functionality to monitor progress.
I'm student and I'm working on project with few of my friends. My task is to make something like class library. Classes in this library should provide API for my friend who must make GUI part of application. GUI could be made by any toolkit (Swing, JavaFX, SWT, AWT, all should work, in fact, it should work even if there is no GUI). I need to make class that waits for data to arrive from network. I don't know when data will arrive, and UI must be responsive during waiting, so I put that in different thread. Now problem is how to make GUI respond when data arrive. Well, I tought that this is asynchronous event and GUI should register event handlers, and I should call that methods when event happens. I proposed this solution:
interface DataArrivedListener{
void dataArrived(String data);
}
class Waiter{
private DataArrivedListener dal;
public void setDataArrivedListener(DataArrivedListener dal){
this.dal = dal;
}
void someMethodThatWaitsForData(){
// some code goes here
data = bufRdr.readLine();
//now goes important line:
dal.dataArrived(data);
// other code goes here
}
}
My question is:
Should I replace "important" line with something like this:
java.awt.EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
dal.dataArrived(data);
}
});
Or something like:
javafx.Platform.runLater(new Runnable(){
#Override
public void run(){
dal.dataArrived(data);
}
});
Or maybe I should do something completely different?
Problem is that I'm not sure which of this will work for any type of UI. If it's GUI, dataArrived() could potentialy make changes to GUI and no matter what type of GUI it is, this changes should be drawn on screen properly. I also think that it is better if I do "invoke this code later" so that my someMethodThatWaitsForData() method could trigger event and continue on with it's on work.
I appreciate your help.
Here's an Event Listener article I wrote a while back. The article explains how you write your own event listeners.
You're correct in that you want to write your own event listeners if you want your library to work with any GUI.
I'm most familiar with Swing, so yes, you'll have GUI code that looks like this:
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
dal.buttonPressed(data);
}
});
If you want it to be completely agnostic to what GUI is being used the only real solution is to let the receiver handle it in dataArrived. Since every toolkit has its own implementation all you can really do to make it work with any toolkit is to disregard it. Otherwise what you will actually end up with is a list of "supported toolkits" and a case for each one.
If you just want dataArrived to be executed away from someMethodThatWaitsForData then you could make your own dispatch thread or make a new thread each time.
If you want to be truly independent of any front-end system, I would recommend creating two threads. The first is your Waiter, which will just listen for events and put them into a Queue of some sort (see the "All Known Implementing Classes" section). The second will invoke the data listener or listeners whenever the queue is not empty.
The concept of invoking a Runnable in the background is kind of deprecated since the invention of the concurrent package. The main reason that this was done in earlier days, is that the GUI code needs to be executed in a different thread, to guarantee that it stays responsive, even if the main thread is busy doing some calculations, but actual multi-threading was still in its very early days. The resulting invokeLater concept works, but comes with a strong creation overhead. This is especially annoying if you frequently have to do minor things, but each time you need to create an entire new Runnable, just to get that event into the Swing thread.
A more modern approach should use a thread-safe list, like a LinkedBlockingQueue. In this case any thread can just throw the event into the queue, and other listener/GUI-Event-handlers can take them out asynchronously, without the need of synchronization or background Runnables.
Example:
You initialize a new Button that does some heavy calculation once it is pressed.
In the GUI thread the following method is called once the button is clicked:
void onClick() {
executor.submit(this.onClickAction);
}
Where executor is an ExecutorService and the onClickAction a Runnable. As the onClickAction is a Runnable that was submitted once during Button creation, no new memory is accessed here. Let's see what this Runnable actually does:
void run() {
final MyData data = doSomeHeavyCalculation();
dispatcher.dispatch(myListeners, data);
}
The dispatcher is internally using the LinkedBlockingQueue as mentioned above (the Executor uses one internally as well btw), where myListeners is a fixed (concurrent) List of listeners and data the Object to dispatch. On the LinkedBlockingQueue several threads are waiting using the take() method. Now one is woken up as of the new event and does the following:
while (true) {
nextEvent = eventQueue.take();
for (EventTarget target : nextEvent.listeners) {
target.update(nextEvent.data);
}
}
The general idea behind all this, is that for once you utilize all cores for your code, and in addition you keep the amount of objects generated as low as possible (some more optimizations are possible, this is just demo code). Especially you do not need to instantiate new Runnables from scratch for frequent events, which comes with a certain overhead. The drawback is that the code using this kind of GUI model needs to deal with the fact that multi-threading is happening all the time. This is not difficult using the tools Java gives to you, but it is an entire different way of designing your code in the first place.
I have a static, periodic, java Timer/TimerTask that I would like to shutdown when the app does. I don't want the app hanging because some thread is still running (like what happens in debug mode in eclipse, some environments may kill the thing anyway). The reason I have it static is I plan to have some (very simple, probably just a counter) shared memory in all of the containing class's instances with the Timer so I feel class scope is appropriate.
My question is how best to do the shutdown of the Timer? Is this an appropriate time to use finalize? This timer seems benign enough that having a non-deterministic call to finalize may work? Would probably need to do some kind of instance counting to verify that there are no longer any instances of the class out there? Suggestions on ways to manage the shutdown of the static Timer are welcome.
pseudo code:
class foo {
private static Timer someTimer = null;
public foo() {
if(someTimer == null) {
someTimer = new Timer(new TimerTask(...));
}
}
//how should I shut this thing down?
protected void finalize() throws Throwable {
}
//or is better to have shutdown() called explicitly?
}
It all depends on what your app actually does, but in general there will be some kind of event to signal that the app is being shutdown. For example if it's a GUI app, then maybe this will be the "user clicked on the Quit button" event. Or it's a webapp based on the servlet API, it will be an event fired by a ServletContextListener.
You should add a listener for this event, which calls some kind of shutdown method on your foo object. Inside this shutdown method the foo should take care of cleaning up its resources, including stopping the timer.
As a last resort, you might want to investigate JVM shutdown hooks
I have a class that takes in a number of SwingWorkers and runs them one at a time in a certain order. I use a ReentrantLock to make sure that only one worker runs at a time. Normally I would always unlock in a finally clause, but I need it to stay locked until the worker completes.
nextWorker.getPropertyChangeSupport().addPropertyChangeListener("state",
new PropertyChangeListener()
{
#Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getNewValue().equals(SwingWorker.StateValue.DONE))
{
executionLock.unlock();
}
}
});
If this is not the case, is done() guaranteed to be called? I would prefer not to call unlock this way, as it would violate encapsulation to some degree.
Due to the nature of the project it is likely that this will come up in a code review. In that case it would be helpful to have a verifiable source. So far I have been unable to find one.
personally I tried everything possible with SwingWorker, but always ends me with done(), but I think that there no guarantee that implemented methods from Future ends correctly, still there this Bug
no idea about your code about lock/unlock another thread or process, but I suggest to use Executor for multithreading,
how to get exceptions from SwingWorker Task
personally I never ever had bad experiences with SwingWorker or some un-expected lack, but all MultiThreading Gurus told about SwingWorker for Production code never, there is still required use of Runnable#Thread instead of SwingWorker
currently i am developing a set of simple games for Java (with JavaFX2 as GUI). Just now i ran into the need of "pausable timers". Does anybody know a library for game timing that enables me to pause timers without implementing it myself? For implementing countdowns and fixed rate things.
I need to:
- schedule TimerTasks at a specific rate (thats already in the JDK)
- schedule TimerTasks with a fixed delay
- pause the timer
- resume the timers so that everything starts of where i paused it.
It would be really cool if somebody knew something like that.
Thanks.
I'm pretty certain there's nothing in the JDK that does this, and I don't know of any libraries to do it.
However, I think instead of trying to pause and resume some sort of timer, you should simply wrap anything that relies on executing periodically in a condition so that it only executes when not paused. If the rate at which tasks are scheduled is sufficiently fast, the difference should not be noticeable for the user. For example:
public abstract class PausableTask extends TimerTask {
private final AtomicBoolean isPaused;
public PausableTask(AtomicBoolean flag) {
isPaused = flag;
}
#Override public final void run() {
if (!isPaused.get()) go();
}
public abstract void go();
}
Then you could have one global paused flag, and any time you are using TimerTasks, use this class instead, passing the global flag. You could even make the flag a public static variable of the PausableTask class.
Maybe this approach isn't even applicable to your game and you have some reason to need more accurate pausing, but if not, hopefully this helps!
You may want to take a a look at Quartz Standby method -
http://www.quartz-scheduler.org/docs/api/1.8.1/org/quartz/Scheduler.html#standby()
From the API -
Temporarily halts the Scheduler's firing of Triggers.
When start() is called (to bring the scheduler out of stand-by mode), trigger misfire instructions will NOT be applied during the execution of the start() method - any misfires will be detected immediately afterward (by the JobStore's normal process).
The scheduler is not destroyed, and can be re-started at any time.
Quartz is a very good framework which you can plugin to your application. It is also highly customizable so you can utilize it.