JavaFX working with threads and GUI - multithreading

I have a problem while working with JavaFX and Threads. Basically I have two options: working with Tasks or Platform.runLater. As I understand Platform.runLater should be used for simple/short tasks, and Task for the longer ones. However, I cannot use any of them.
When I call Thread, it has to pop up a captcha dialog in a middle of task. While using Task, it ignores my request to show new dialog... It does not let me to create a new stage.
On the other hand, when I use Platform.runLater, it lets me show a dialog, however, the program's main window freezes until the pop up dialog is showed.
I need any kind of solution for this. If anyone knows how to deal with this or had some similar experience and found a solution I am looking forward to hearing from you!

As puce says, you have to use Task or Service for the things that you need to do in background. And Platform.runLater to do things in the JavaFX Application thread from the background thread.
You have to synchronize them, and one of the ways to do that is using the class CountDownLatch.
Here is an example:
Service<Void> service = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
#Override
public void run() {
try{
//FX Stuff done here
}finally{
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();

Use a Worker (Task, Service) from the JavaFX Application thread if you want to do something in the background.
http://docs.oracle.com/javafx/2/api/javafx/concurrent/package-summary.html
Use Platform.runLater from a background thread if you want to do something on the JavaFX Application thread.
http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html#runLater%28java.lang.Runnable%29

It's too late to answer but for those who have the error, here is the solution XD
You can use one Thread.
Use the lambda expression for the runnable in the thread and the runlater.
Thread t = new Thread(() -> {
//Here write all actions that you want execute on background
Platform.runLater(() -> {
//Here the actions that use the gui where is finished the actions on background.
});
});
t.start();

You can user directly this code
Don't forget you can't send non-final variable in thread .
you can send final variable in thread
//final String me="ddddd";
new Thread(new Runnable() {
#Override
public void run() {
// me = me + "eee";
//...Your code....
}
}).start();
Use in
your code
try/catch

Related

What is the purpose of await() in CountDownLatch?

I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

Timers and javafx

I am trying to write a code that will make things appear on the screen at predetermined but irregular intervals using javafx. I tried to use a timer (java.util, not javax.swing) but it turns out you can't change anything in the application if you are working from a separate thread.(Like a Timer) Can anyone tell me how I could get a Timer to interact with the application if they are both separate threads?
You don't need java.util.Timer or java.util.concurrent.ScheduledExecutorService to schedule future actions on the JavaFX application thread. You can use JavaFX Timeline as a timer:
new Timeline(new KeyFrame(
Duration.millis(2500),
ae -> doSomething()))
.play();
Alternatively, you can use a convenience method from ReactFX:
FxTimer.runLater(
Duration.ofMillis(2500),
() -> doSomething());
Note that you don't need to wrap the action in Platform.runLater, because it is already executed on the JavaFX application thread.
berry120 answer works with java.util.Timer too so you can do
Timer timer = new java.util.Timer();
timer.schedule(new TimerTask() {
public void run() {
Platform.runLater(new Runnable() {
public void run() {
label.update();
javafxcomponent.doSomething();
}
});
}
}, delay, period);
I used this and it works perfectly
If you touch any JavaFX component you must do so from the Platform thread (which is essentially the event dispatch thread for JavaFX.) You do this easily by calling Platform.runLater(). So, for instance, it's perfectly safe to do this:
new Thread() {
public void run() {
//Do some stuff in another thread
Platform.runLater(new Runnable() {
public void run() {
label.update();
javafxcomponent.doSomething();
}
});
}
}.start();

Understanding simple ProgressDialogue , how can another thread update UI?

This example is copied from a book on Android. As you can see from my question, I am new to Android and trying to understand. This application should crash but it does not (I am updating UI from another thread. Which is not allowed.It should cause a crash. It does not. Why?). My code is:
final ProgressDialog dialogue = ProgressDialog.show(this, "title", "message");
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(7000);
dialogue.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
This is done in OnCreate function. I am confused with line - dialogue.dismiss(); Isn't that updating UI (dismissing dialogue) from another thread? Why does this app not cause segmentation fault?
Thanks.
You cant dismiss() it in run method because it is non UI thread.and if you want to dismiss then use Handler.And its better to use AsyncTask
The Code is correct only man.You are starting a thread using the .start function and after that the run function called and then after 7 seconds the the dialogue will dismiss.The dialogue.dismiss() is used to dismiss the dialogue.If you will not call dismiss(),the progress bar never dismissed.You can check by commenting the line Thread.sleep(7000).

Problem in calling thread inside Eclipse view run method, after using asyncExec. Invalid Thread Exception

I am having an eclipse View. Inside the view I added a Table. Now I am calling a thread from run method of the view using asyncExec.
My View class is like -
public class SampleViewAction implements IWorkbenchWindowActionDelegate{
Thread t;
int Count;
#Override
public void run(IAction arg0) {
}
}
Now I added a thread like this -
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
#Override
public void run() {
new UDPReadThread();
}
});
Where UDPReadThread is a class extends a thread where in UDPReadThread 's constructor I started the thread.
But I am getting invalid Thread exception.
How to resolve the issue.
Similar to AWT and the EventDispatchThread, SWT must process everything in the UI thread.
Your SampleViewAction is run on the UI thread already, in response to a menu or tool item selection.
It looks like your problem comes from then using an asyncExec(*) which will post the runnable to be run on the UI thread (which delays it), and starting a new thread from that asyncExec Runnable. You may as well simply start your thread, and get rid of that asyncExec.
Your UDPReadThread is not the UI thread. If you need to update UI widgets from UDPReadThread, that's the code that needs the asyncExec:
display.asyncExec(
new Runnable() {
public void run(){
label.setText(text);
}
});
Just as an aside, you should not subclass Thread unless you really are extending threads capabilities. The normal pattern when you just want to start another thread:
UDPReadRunnable udpRunnable = ....;
Thread thread = new Thread(udpRunnable);
thread.start();
You can get more information on the display thread from http://www.eclipse.org/swt/faq.php#uithread

Thread Invalid Access Error in SWT

Could you let me know the reason for this error in SWT
"org.eclipse.swt.SWTException" Invalid Thread access ?
And How to fix such errors.
It happens when you try to act upon an interface item from a thread that's not the UI thread.
To run a code on the UI thread you have to use a Runnable and ask the display thread to run it. This way:
Display.getDefault().syncExec( new Runnable() {
#Override
public void run() {
// Do your job here
}
} );
As stated by the syncExec method javadoc,
the thread which calls this method is suspended until the runnable completes.
Also, you might check the asyncExec method.
In SWT you can access GUI resources only from the display thread. For example when setting the text in a org.eclipse.swt.widgets.Text control you must already be in the display thread or call
final Text text = ...;
Display.getCurrent().syncExec(new Runnable() {
#Override
public void run() {
text.setText("test");
}
});

Resources