Is there some way to verify that code is executing on the user’s user interface thread (event loop thread)?
This question is the Vaadin equivalent of this question, Swing verify code on Event Dispatch Thread at runtime.
I know how to call UI::access from a background thread to schedule a Runnable to be run on the user-interface thread. My question is how to double-check that some executing code is indeed running on the user-interface thread.
I filed a feature request for this.
UI.getCurrent()
If UI.getCurrent() returns an instance you are (most probably) either:
On a thread started by UI interaction
On a thread that is already initiated with UI::access
To quote the Vaadin 7.3.9 doc:
… In other cases, (e.g. from background threads), the current UI is not automatically defined.
Example Code
boolean uiOrUiAccessManagedThread = UI.getCurrent() != null;
The framework is already full of asserts in various code paths that should only be run on the thread that has locked the UI state. The most important being whenever shared state is accessed.
To benefit from this checking, just make sure your server is run with assertion checking enabled, i.e. by starting it with the -ea JVM parameter.
Related
I want to coordinate serial requests coming from a Java Swing GUI using the state pattern. When a state method was called, the serial communication shall start and in parrallel the GUI should not be frozen during this time.
I have one GUI Thread. In this thread I'm invkoing methods of a state machine which also lives in the GUI Thread.
In some cases after a state machine method has been invoked, data from a serial port shall be fetched (longer task). This fetching is been done in an otherThread. On some state changes the otherThread can be interrupted and otherThread should stop immediately (I'm using otherThread.interrupt()). To know when otherThread actually has returned, I use otherThread.join() to wait for otherThread in the GUI Thread.
Without using join() I always run into exceptions after a state change where I communicate via serial port in another otherThread.
The inconvinience of this approach is ofc. that the GUI thread is blocked/frozen as long as otherThread needs to finish its task.
I was thinking about calling the state machine method in a third thread. But I don't like this idea bcs.:
I don't have a lot experience with multi threading in Java (I assume labeling the methods of the state machine as synchronized could work to ensure thread safetiness).
Overhead due to thread and runnable creation for each invocation of a state machine method.
So my question is: What is a good way to make the GUI not frozen while waiting for otherThread?
All the stuff about "states", "state machines", and "state pattern" is red herring. (Meaning: it is completely irrelevant.) The question is simply how to avoid block-waiting for Thread.join() from the gui thread.
Your "otherThread" should be aware of the fact that it was interrupted and exit gracefully. (Look for more information on thread interruption in Java to see how to accomplish this correctly.)
Right before exiting, the "otherThread" should post a message back to your "gui thread" to let it know that it is exiting.
Posting a message back to the "gui thread" in Swing is done with SwingUtilities.invokeLater(), and the "message" is not exactly a message, it is a function that you pass to invokeLater() and it gets executed within the "gui thread".
Then, the "gui thread" can then either ignore the thread, or join with it, knowing that this Thread.join() will complete very quickly because thread termination is either imminent, or has already happened.
In java fx controller i have two version of the code that simply sets a text on a label when a button is pressed (this is just a sample, but any other ui modification can be considered)...
first version uses Platform.runLater :
Platform.runLater(() -> {
status.setText("");
statusIndicator.setVisible(false);
});
the other one simply modifies it in ordinary thread :
status.setText("");
statusIndicator.setVisible(false);
Both are working perfectly fine, only difference i know so far is that passing some runnable to Platform.runLater will keep the order of execution.
is there any other significat difference or motive to use Platform.runLater?
JavaFX has just a single UI thread
From Docs
The JavaFX scene graph, which represents the graphical user interface
of a JavaFX application, is not thread-safe and can only be accessed
and modified from the UI thread also known as the JavaFX Application
thread
In case you have long-running tasks, you will want to run them on background threads and after completion of such threads, you would want to update the result back to the UI. Under such scenario's, you use the updation surrounded with Platform.runlater(). Surrounding your code with Platform.runLater enables your code to communicate with the JavaFX Application thread.
Coming to your question :
is there any other significat difference or motive to use Platform.runLater?
I hope most of it is already answered, just to add
1 . You don't have to use Platform.runlater(), if you are already on the JavaFX Application thread
2 . As the Platform.runLater() doc says
Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future
We are not sure when the update will take place, it depends on the number of updates waiting to be processed. If a number of updates are waiting to be processed on the UI thread, it can take some time (such scenario normally doesn't happen)
I am using the thread for login on Server and I want to stop the Thread as the user press back button, I am using stop() and destroy() method and these methods crashing my application, I think these Methods are depreciated that why I am facing this problem. Please Give me the way to stop thread without using stop() and destroy().
Thread.stop() is deprecated since java 1.1 (~17 years ago...). Java of this method explains the reasons in details. This means that you should never call this method. It is still there for backwards compatibility with code written when I was young.
But what to do if you want to "cancel" the operation done in thread? The answer is that you (developer) should care about this yourself. How? It depends on your application. If for example your thread opens i/o stream you can close the stream. If your thread performs series of operations in loop you should check special flag that indicates that thread should exit and update this flag according to needs of your application (in your case when user presses "back" button.
If you still have problem please try to give more details what does your thread do and you will probably get concrete recommendations how to stop it.
For background thread in android try to use service.
I mean you start a service and put a thread in that service.
If you want to stop that service then pressed back button try "Bound" Service. You will get basic idea here.
http://developer.android.com/guide/components/services.html
Only use a thread if you want to do work repeatedly for a long time. I have never needed to start a thread.
You should look at using an AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
It works by using a Thread from the ThreadPool. AsyncTask's are easy to stop, have a method to override for background tasks and one to override for post task work which is suitable for updating the UI (as long as the task was started by the UI thread).
I have a Swing application that handles Ctrl+C using addShutdownHook(), and it works fine until one of the shutdown tasks I have calls a function that under normal circumstances changes a JLabel text, at which point it hangs.
I assume the problem is that the Swing EDT has either terminated or is waiting for something.
Is there a way to either determine that the EDT has terminated or is "done" (so I can avoid calling Swing methods), or to prevent the usual close-all-the-windows-down behavior on Ctrl-C?
Just to clarify:
I have a method in a class called stop(). Under normal circumstances this can get called (along with its complement start()) and it triggers a cascade of things that causes a JLabel to be updated, for visual feedback that a stop() has occurred.
When my shutdown hook runs, I need to call stop() to gracefully shutdown some resources.
What I'm asking is how I can detect that Swing EDT is not there, so I can rewrite stop() so that it detects a lack of Swing and avoids the call to the Swing functions.
The following hack helps to determine whether JVM is in the process of shutting down without passing any flags around:
private static final Thread DUMMY_HOOK = new Thread();
public static boolean isShuttingDown()
{
try {
Runtime.getRuntime().addShutdownHook(DUMMY_HOOK);
Runtime.getRuntime().removeShutdownHook(DUMMY_HOOK);
} catch ( IllegalStateException e ) {
return true;
}
return false;
}
But don't forget about possible concurrency issues.
Shutdown hooks should not expect other services to be in a known state (e.g. the UI event-handling thread, etc.), because the application has been requested to be shut down. Writing a shutdown hook that tries to update something that isn't 100% within the hook's control can result in this, and other behavior, that will be difficult to troubleshoot.
The addShutdownHook method specifically mentions this case, and warns that you shouldn't try these types of actions, since doing so can easily result in unexpected consequences, such as the lockup you've observed.
From the documentation:
Shutdown hooks run at a delicate time in the life cycle of a virtual
machine and should therefore be coded defensively. They should, in
particular, be written to be thread-safe and to avoid deadlocks
insofar as possible. They should also not rely blindly upon services
that may have registered their own shutdown hooks and therefore may
themselves in the process of shutting down.
In this case, since Swing is a multi-threaded UI system which you do not control, I would recommend not trying to alter anything in the UI at the shutdown stage of you're program's life. Doing so will result in strange, unpredictable, and sometimes non-repeatable situations that can vary from one run to the next, or from one machine to the next, depending on how the threads get scheduled to shutdown. How, and when, another thread stops its work is not designed to happen in a linear, predictable way. As such, any code you write in a multi-threaded program that relies upon another thread being in a certain state at a certain time (unless those threads are clearly communicating with each other about their state), will open you up to these kinds of issues.
I suppose my follow up question would be, "Why do you want/need to alter the JLabel during the shutdown process?" If you want to change the state of something before shutdown, the better way to do it would be catch the keyboard input as a regular event (preventing it from causing the application to close), change the JLabel text, and then start a shutdown of the application yourself via a call to System.runFinalization() and/or System.ext(int)
I ended up setting a flag at the beginning of the shutdown hook, and communicating this (via objects set up ahead of time) to the object with my stop() method, so that it can test this flag and decide whether or not to call the Swing methods.
If the shutdown flag is not set, the Swing methods get called. Otherwise they don't.
I am writing an application in java (1.6) using swing. I currently have a JXBusyLabel on a JXLayer over the content area of my program acting as a busy indicator. I want to provide a way to allow others working with me to create a task that pops up the busy label while it's executing. The catch is, the task must be cancel-able. What is the best way to expose the functionality I desire?
Some ideas I've come up with:
Raw access to setBusy()
This is obviously the easiest for me but requires users know and understand swing threading issues.
public <T> Future<T> execute(Callable<T>)
Wraps the callable in a FutureValue that is run() on a separate thread and returns that FutureValue. The question then becomes, how to keep track of all FutureValue's generated and how to ensure that they can be cancelled. (e.g. cancel(true) always cancels)
I have never used the concurrency package in Java before and it didn't exist back when I 'learned' Java. So I am open to completely new and different ways of implementing this functionality.
Edit:
Clarification of my question. I know about SwingWorker. I've just never used it. What I want to know is this:
Given a Callable (Java version of a closure?) How can I:
Return the value of call() to the user w/o blocking (I think I need to use a Future for this)
Tell the JXLayer to lock (starts painter), execute the supplied callable, and then unlock the JXLayer (stops painter)
Ensure that, no matter what thread calls my busyExec() function, the GUI remains responsive and the background task completes. (NOTE: If I return some sort of Future object and they call get() on the event thread, it can/will block and that is ok)
I guess my main stumbling point is how to implement #2. Should I have busyExec() spin off a new thread that blocks until no background tasks are running? Should I try for some sort of queue. Is there an object that will do this all for me already?
The SwingWorker (of Java 6) implements Future so it seems like it has the ability to cancel tasks via the cancel method.
More information on SwingWorker from The Java Tutorials:
Lesson: Concurrency in Swing
Worker Threads and SwingWorker
Canceling Background Tasks
Okay. For anyone interested here is what I am currently using to implement my request.
I have a method that will take a Callable<T>. It then creates a FutureTask<T> this will be returned to the caller as a this as a Future<T>. The JXBusyLabel and JXLayer are told to start painting and to lock the ui. The FutureValue and Thread (see below) is enqueued in a special list. A Runnable is created that: calls run() on the FutureTask, removes the FutureValue (and thread) from the list, and if the list is empty, unlocks the JXLayer and stops the JXBusyLabel. This Runnable is launched in a new Thread with normal priority.
When the user hits the cancel button. The list is iterated over and the FutureTasks are all canceled and removed from the list if they could be cancelled. First try cancel(false), then cancel(true). If both those means fail, the user is prompted with a warning asking them if they want to Thread.stop() the task and explains that this could make the app unstable. If yes, stop() the thread running the task. This might bring the app down. In all cases, the UI is unlocked.
The documentation for other team members states that they must be aware that the task can be killed. They are not to call get() until isDone() is true. They are explicitly told that this will basically force them to block until the task is done or cancelled. So they can't call it from the event dispatch thread.
Other solutions are still welcome