switching between threads in Intellij Idea - multithreading

How to switch between threads of a suspended program?
or Any tutorial on multi-threaded debugging with Intellij Idea describing basic features - suspend, resume, switch between threads.
very good tutorials/step-by-step guide available for Netbeans:
e.g. https://netbeans.org/kb/docs/java/debug-multithreaded.html

Trick is to set breakpoint suspend policy to - Thread.
View breakpoint properties (right-click on breakpoint)
Once done threads will hit breakpoint and block, now active thread can be switched to check race conditions/deadlocks.
Following code snippet for creating deadlock:
public static void main(String args[]) {
Thread thread1 = new Thread(null, new MyThread(obj1, obj2), "Thread-1");
Thread thread2 = new Thread(null, new MyThread(obj2, obj1), "Thread-2");
thread1.start();
thread2.start();
}
class MyThread implements Runnable {
private Object obj1;
private Object obj2;
MyThread(Object obj1, Object obj2) {
this.obj1 = obj1;
this.obj2 = obj2;
}
#Override
public void run() {
System.out.println("Acquiring locks");
synchronized (obj1){
System.out.println("Acquired 1st lock");
synchronized (obj2){
System.out.println("Acquired 2nd lock");
}
System.out.println("Released 2nd lock");
}
System.out.println("Released 1st lock");
}
}

Amit,
You may be interested in an alternative threads view of the call stack, enabled by clicking the 'Restore threads view' button:
A bit of documentation around that : Debug Tool Window - Threads
Also, these questions might be useful :
IntelliJ Thread Debug
IntelliJ - pause a thread while debugging

Related

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();

JavaFX working with threads and GUI

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

System.exit is not thread-safe on Linux?

I've just switched from Oracle JDK 1.6, to Open JDK 1.7.0_03, and I've hit a rather remarkable deadlock on exit:
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Thread.join(Thread.java:1258)
- locked <0x8608dda0> (a sun.awt.X11.XToolkit$1$1)
at java.lang.Thread.join(Thread.java:1332)
at java.lang.ApplicationShutdownHooks.runHooks(ApplicationShutdownHooks.java:106)
at java.lang.ApplicationShutdownHooks$1.run(ApplicationShutdownHooks.java:46)
at java.lang.Shutdown.runHooks(Shutdown.java:123)
at java.lang.Shutdown.sequence(Shutdown.java:167)
at java.lang.Shutdown.exit(Shutdown.java:212)
- locked <0x8603df28> (a java.lang.Class for java.lang.Shutdown)
at java.lang.Runtime.exit(Runtime.java:107)
at java.lang.System.exit(System.java:960)
It appears that you must call System.exit from the AWT event queue. Is this for real? There is no documentation of a thread requirement in the Sun docs Runtime.exit
I've hit other surprising cases where getting the AWT tree lock is required only on Linux, but this one takes the cake. Is this a bug, or have I just missed something in the documentation?
It depends, the runHooks method will start any hook threads registered through Runtime.addShutdownHook and wait for them to be finished. If any of your hook threads is locking some resources that the AWT event thread is requiring too, they may cause dead lock.
If you have to call System.exit in your AWT event thread,I suggest you call it in another thread like:
new Thread(){
public void run() {
System.exit(0);
}
}.start();
It is impossible to say whether this is a bug in the runtime without knowing more about what the application is doing (ideally, this would take the form of an SSCCE).
For example, the following demonstrates a similar deadlock involving System.exit(). However, it is clearly a bug in the application, not in System.exit():
public class OhNo {
final static Object lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
synchronized (lock) {
for (;;) {
}
}
}
}).start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
synchronized (lock) {
System.out.println("in shutdown hook");
}
}
}));
System.out.println("about to call System.exit()");
System.exit(0);
}
}

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