I'm trying to make the program wait for the user to click on the GUI.
But Thread.sleep() just sleeps the entire GUI. So all I can see is an empty window.
code:
while (!enteredField) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Swing events need to happen on the Event Dispatch Thread.
Have you tried
SwingUtilities.invokeAndWait(() -> Thread.sleep(20))
https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingUtilities.html#invokeAndWait-- ?
I have had problem like this before. so you are not alone. I made mistakes like this.
Your Problem
while (!enteredField) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Solution
Thread thread = new Thread(() -> {
while (!enteredField) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
* Detailed Response*
' What you did was that you created a thread inside a while loop. Basically You paused the whole GUI for 10 milliseconds, the whole program for matter of fact. Furthermore, I do not understand what your objective is. You said that you want to wait for the user to click on the GUI.Suggestions would be, listen for the button click. for example Button.setOnAction(() -> {}); That would do he job instead of sleeping. I just the only case that you would want to pause or sleep is if you are animating somethings.
Related
This question already has answers here:
Thread.interrupt () doesn't work
(2 answers)
Closed 6 years ago.
onIncomingCall() is a overridden method from a class in third party library pjsip. This method is called when an incoming call is made using SIP. Somehow this method makes it possible for the call to be answered ONLY if the Call answering code be inside the same method or called within the same method. But I want the call to be answered when the user presses the button. I have created a call back and make the user press the button when the call comes but the call answering code is not working if its called outside of onIncomingCall() method. So I decided to put Thread.sleep(10000) in onIncomingCall() and when the user presses the button I would like to cancel this thread so that the call answering code can be executed.
I used Thread.currentThread().interrupt() but the Thread.sleep is not cancelled at all. I wrote a separate activity to test this functionality but it failed, meaning Thread.currentThread.interrupt is not working in for me at all. What is the best option to achieve this? Kindly please update me .. I am really struggling with this.
#Override
public void onIncomingCall(OnIncomingCallParam prm) {
onIncomingCallParam = prm;
try {
Thread.sleep(10000);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
answerCall();
}
UPDATE:
I fixed the issue with the below approach
resetThread();
while (testThread) {
try {
Log.d(TAG,"testThread true");
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
Log.d(TAG,"Call Answering code");
private void resetThread() {
Thread newThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
testThread = false;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
});
try {
newThread.start();
} catch (Exception ie) {
ie.printStackTrace();
}
}
The problem here is related to the fact that you don't interrupt the right Thread, if you call Thread.currentThread().interrupt(), you will interrupt the current thread not the one that it is currently sleeping.
Here is a clear example to show the main idea:
// Here is the thread that will only sleep until it will be interrupted
Thread t1 = new Thread(
() -> {
try {
Thread.sleep(10_000L);
System.err.println("The Thread has not been interrupted");
} catch (InterruptedException e) {
System.out.println("The Thread has been interrupted");
}
}
);
// Start the thread
t1.start();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with Thread.currentThread().interrupt()
System.out.println("Trying to call Thread.currentThread().interrupt()");
Thread.currentThread().interrupt();
// Reset the flag to be able to make the current thread sleep again
Thread.interrupted();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with t1.interrupt()
System.out.println("Trying to call t1.interrupt()");
t1.interrupt();
Output:
Trying to call Thread.currentThread().interrupt()
Trying to call t1.interrupt()
The Thread has been interrupted
As you can see in the output, the thread is interrupted only when we call t1.interrupt(), in other words only when we interrupt the right Thread.
Maybe all calls has to be done on the same thread, which created library instance. Try using HandlerThread for posting it messages and handle those messages inside custom Handler instead of suspending thread.
I've been trying to figure it out for some time,
I'm trying to write a chat - server app, just for learning.
I have an obstacle that I cannot understand,
The while loop inside of the GUI class freeze, but just when it trying to read:
public void run(){
Platform.runLater(() -> {
do {
try {
msg = getFromServer.readUTF(); // <--- freeze GUI
chatWindow.appendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
});
}
You can see that it's running in a thread, but i did try to run it in other ways...
Only the DataInputStream make it stuck,
msg = getFromServer.readUTF();
And this it the methud that it's coming from:
public void connectToServer(){
try {
serverConectionState = new Socket("127.0.0.1", 6789);
getFromServer = new DataInputStream(serverConectionState.getInputStream());
sendToServer = new DataOutputStream(serverConectionState.getOutputStream());
onlineOffline.setText("Online");
onlineOffline.setTextFill(javafx.scene.paint.Color.web("#0076a3"));
} catch (IOException ex){
chatWindow.appendText("server connection fail\n");
}
}
This class, is the Controller.class - if it's make any diffrent.
My first question in stackoverflow, after a lot of help from the community.
Thanks in advance
I'm assuming the run method you showed is part of a Runnable that is executed in a background thread.
You are running the entire loop on the FX Application Thread (by using Platform.runLater()). So you block that thread and prevent it from repainting. You should run only the UI updates on the FX Application Thread:
public void run(){
do {
try {
String msg = getFromServer.readUTF(); // <--- freeze GUI
Platform.runLater(() -> chatWindow.appendText(msg));
} catch (IOException e) {
e.printStackTrace();
}
} while (true);
}
instead of using platform.runlater you should use java task, so that you can run the code in different thread, without freezing the UI thread
I have a program where I am loading a file while at the same time I am displaying a window to inform the user that the file is being loaded. I decided to make a FileLoader class that was a SwingWorker which actually handled loading the file and a ProgressWindow that implements PropertyChangeListener to inform the user about the status of the SwingWorker that was passed into it.
My code currently looks like this:
FileLoader loader = new FileLoader(filePath);
new ProgressWindow(loader, "Loading File", "Loading File");
//ProgressWindow's constructor calls loader.execute() inherited from SwingWorker
doc = loader.get(); //GUI Freezes when called
The problem is that whenever I call loader.get(), it freezes the GUI, thus the progress bar in the Progress Window doesn't run and the whole thing is pointless. As far as I can tell, this is because the thread controlling the GUI is the same thread that calls loader.get(), which goes on hold while loader.execute() is running.
So far, I've tried creating a new thread for either the loader.get() command or the loader.execute() method, and calling SwingUtilities.invokeLater() on the thread, but then the whole program freezes.
I've considered creating a ChangeListener for when SwingWorker.isDone() and then running loader.get(), but this would require some reworking of my code that I would rather not do.
Could anyone tell me what the best way is to get this to work?
get() is like join() in that it will block until called, and will wait for the SwingWorker to finish before being called. Using it wrongly can completely nullify all the advantages of using a SwingWorker in the first place.
Solution: Don't call get() until you know that the SwingWorker is done with its processing, by either calling it in the SwingWorker's done() method, or if you need to call it from the calling code, then in a PropertyChangeListener that has been added to the SwingWorker when the SwingWorker's "state" property is SwingWorker.StateValue.DONE.
Something like:
final FileLoader loader = new FileLoader(filePath);
loader.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("state".equals(evt.getPropertyName())) {
// since DONE is enum, no need for equals(...) method
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
try {
loader.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
});
new ProgressWindow(loader, "Loading File", "Loading File");
Note: code not compiled nor tested
Edit: try/catch added.
So far, I've tried creating a new thread for either the loader.get() command or the loader.execute() method, and calling SwingUtilities.invokeLater() on the thread, but then the whole program freezes.
If you call SwingUtilities.invokeLater() on the thread that will execute the thread in the EDT which freezes the GUI. Instead, run the thread by calling it's start() method and only use SwingUtilities.invokeLater() when you need to update the progress bar in the PropertyChangeListener.
I have create a WorkerThread class which take care of Threads and GUI current/main thread .
i have put my GUI application in construct() method of WorkerThread when an event fire to start XXXServer then all threads are activate and GUI work smoothlly wihout freeze. have a look.
/**
* Action Event
*
* #see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent ae) {
log.info("actionPerformed begin..." + ae.getActionCommand());
try {
if (ae.getActionCommand().equals(btnStart.getText())) {
final int portNumber = 9990;
try {
WorkerThread workerThread = new WorkerThread(){
public Object construct(){
log.info("Initializing the Server GUI...");
// initializing the Server
try {
xxxServer = new XXXServer(portNumber);
xxxServer.start();
btnStart.setEnabled(false);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("actionPerformed() Start button ERROR IOEXCEPTION..." + e.getMessage());
e.printStackTrace();
}
return null;
}
};workerThread.start();
} catch (Exception e) {
log.info("actionPerformed() Start button ERROR..." + e.getMessage());
e.printStackTrace();
}
} else if (ae.getActionCommand().equals(btnStop.getText())) {
log.info("Exit..." + btnStop.getText());
closeWindow();
}
} catch (Exception e) {
log
.info("Error in ServerGUI actionPerformed==="
+ e.getMessage());
}
}
I have a java class like below. Its job is monitor a file, if that file's size does not change at certain interval, it will raise alert.
I'd like to write two UTs for it.
1.Simulates the file size keeps unchanges.
2.Simulate file size keeps changes for a while. After that file size will change.
The UT will verify alerter.alert() or alerter.harmless() is really invoked when condition is or isn't met. I mocked Alerter and passed it to Task's constructor. But how to control the timing for run()? I know timing for multi-thread cannot be controlled accurately. I just would like to know what is the best practice to write ut for this kind of class. If possible, please write a test sample.
You can regard that "some condition" as checking if a specified file's size changes at a certain interval. If not changed, some condition will be true.
class Task implements Runnable{
Alerter alerter;
boolean stop=false;
public Task(Alerter alerter){
this.alerter=alerter;
}
public void run() {
while (!stop){
if (some condition){
alerter.alert();
} else{
alerter.harmless();
}
Thread.sleep(5000);
}
}
public synchronized void stop(){
stop=true;
}
}
I'm thinking of writing uts like below. But I don't think it is good enough.
#Test
public void testRunWithFeed() {
Alerter mockAlerter=mock(Alerter.class);
Task task=new Task(mockAlerter);
Thread thread =new Thread(task);
thread.start();
try {
Thread.sleep(1000); // give Task.run() a change to run
} catch (InterruptedException e) {
e.printStackTrace();
}
task.stop();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
verify(mockAlerter,atLeastOnce()).alert();
verify(mockAlerter,never()).harmless();
}
#Test
public void testRunNoFeed() {
Alerter mockAlerter=mock(Alerter.class);
Task task=new Task(mockAlerter);
Thread thread =new Thread(task);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeFileSize();
try {
Thread.sleep(6000); //because every 5000ms file size will be checked once in run()
} catch (InterruptedException e) {
e.printStackTrace();
}
task.stop();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
verify(mockAlerter,atLeastOnce()).alert();
verify(mockAlerter,atLeastOnce()).harmless();
}
Thanks in advance.
I think that you should not call sleep() and obviously should not call stop in your test.
If you task runs and is expected to terminate calling join() is enough: your main thread will wait until the worker thread is done. Then you will verify the result.
And yet another tip. You should prevent your test from being stuck. Both JUnit and TestNG have annotations that define the test timeout. If timeout is expired the test will be killed by framework and will fail automatically.
For example for JUnit it is the attribute timout: #Test(timeout=3000) means 3 seconds.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Does a finally block always run?
I learned that the finally clause of a try catch statement, executes always. But some guy said to me that it is possible to avoid executing it(removing it is not an option).
-Does someone how is that possible?
-Also i am curious in knowing why would someone want to avoid to execute it?
Kill it with an uncaught exception within the finally block, or kill the overall JVM (which kills the thread, among other things).
There is no good reason to stop the execution of a finally block except poor design. If it's not supposed to run every time, then don't put it in a finally block.
Using the below test code, I run two different scenarios to see what happens when killing the Thread:
Start the Thread and sleep the main thread for 2 seconds. Within the Thread, pretty much immediately enter the finally block and then sleep for 5 seconds. Once the main thread is finished waiting, kill the Thread using stop.
Start the Thread and sleep 2 seconds. Within the Thread, sleep 5 seconds before entering the finally block and then sleep some more within the finally to give it a chance to be killed.
In the first case, the result is that the finally block stops executing.
In the second case, the result is that the finally block executes completely, and on the Thread that was stopped no less.
Output (note the name of the current thread added for all output):
thread-starting [main]
trying [Thread-0]
catching [Thread-0]
finally-sleeping [Thread-0]
thread-stopped [main]
[main]
thread-starting [main]
trying-sleeping [Thread-1]
thread-stopped [main]
finally-sleeping [Thread-1]
finally-done [Thread-1]
Code:
public class Main
{
public static void main(String[] args)
{
testThread(new TestRunnable());
println("");
testThread(new TestRunnable2());
}
private static void testThread(Runnable runnable)
{
Thread testFinally = new Thread(runnable);
println("thread-starting");
testFinally.start();
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
println("main-interrupted...");
}
testFinally.stop();
println("thread-stopped");
}
private static class TestRunnable implements Runnable
{
#Override
public void run()
{
try
{
println("trying");
throw new IllegalStateException("catching");
}
catch (RuntimeException e)
{
println(e.getMessage());
}
finally
{
println("finally-sleeping");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("finally-interrupted");
}
println("finally-done");
}
}
}
private static class TestRunnable2 implements Runnable
{
#Override
public void run()
{
try
{
println("trying-sleeping");
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("trying-interrupted");
}
finally
{
println("finally-sleeping");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
println("finally-interrupted");
}
println("finally-done");
}
}
}
private static void println(String line)
{
System.out.printf("%s [%s]%n", line, Thread.currentThread().getName());
System.out.flush();
}
}
-Does someone how is that possible?
System.exit(0);
-Also i am curious in knowing why would someone want to avoid to execute it?
To answer questions like these and appear smart. ;)
BTW, Thread.stop() doesn't prevent finally being called.
Thread t = new Thread() {
#Override
public void run() {
try {
System.out.println("Thread start");
Thread.sleep(1000);
System.out.println("Thread end");
} catch (InterruptedException ie) {
System.out.println("Thread Interrupted");
} catch (Error e) {
System.out.println("Thread threw an error " + e);
throw e;
} finally {
System.out.println("Thread finally");
}
}
};
t.start();
t.join(100);
t.stop();
prints
Thread start
Thread threw an error java.lang.ThreadDeath
Thread finally
There's no way of avoiding it, unless something external happens such as the Java Virtual Machine shutting down.
As a general rule you should always assume that a finally block will run. The whole point of it is to ensure that it runs regardless of what happens in the try block - there should be no reason to avoid it!
To your first question i think the only way that comes to my mind is by creating an infinite loop or something.(But it makes no sense at all)
try{
while(true);
}
catch(Exception e) {
}
finally {
//..
}
To your second question, i don't really know why would someone want to do something like that
See this link: https://stackoverflow.com/posts/6228601/edit
I can't think of a good reason that you would want to avoid a finally block. If you really don't want to use this feature, then just don't implement a finally block (at your own risk however).
Killing the JVM would do it, but that's not really an acceptible solution for any production code.
Why is removing a finally block not an option?