Hello i am having a problem with resuming a thread my code is
public boolean Wait(String Reply){
if (Reply.equalsIgnoreCase("Y")){
try {
t.resume();
}
catch (Exception e){
System.out.println("\n" + "The exception in resume thread method:::: " + e);
}
System.out.println("\n" + "In the Wait Function of Sender");
return true;
}
JOptionPane.showMessageDialog(j ,
"Please Wait While The User Accpets the Trasmission ",
"",
JOptionPane.INFORMATION_MESSAGE);
try{
t = new Thread(this);
t.sleep(100000);
}
catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
return false;
}
I might explain you how it works as it will help u determine the problem.
First the thread is put to sleep......Then i call this public boolean Wait() function from another function named ReplyYes which passes the value "Y" and i then try to resume the thread but the t.resume() function call, instead of resuming the thread gives me a Java.Lang.Null.PointerException and the thread isn't resumed resulting in returning a FALSE value. Plus because of this thread i can't even Stop my Service i have to wait for the thread to timeOut.
Can anyone explain how to make it work correctly!!
Thank you
I think you misunderstand how Thread.sleep works. It is a static method.
The line t.sleep(100000); puts the current thread to sleep, not the thread t.
From the documentation:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
Emphasis mine.
You should start the thread and call sleep from that thread. See the following article for two different ways to start a thread:
Defining and Starting a Thread
Furthermore, resume is only for use with suspend and they have both been deprecated. From the documentation:
Deprecated. This method exists solely for use with suspend(), which has been deprecated because it is deadlock-prone. For more information, see Why Are Thread.stop, Thread.suspend,
Thread.resume and Runtime.runFinalizersOnExit Deprecated?
The reason you get a NullPointerException is probably because you try to create the new Thread object after you call t.resume(). So at that point, t still has the value null. Basically, your code needs to be completely rewritten from scratch. I would suggest following the tutorial I linked to above, then once you understand how to create threads move to the next chapters:
Pausing Execution with Sleep
Interrupts
at first you must start new Thread: t.start(); then try to wake up your thread: t.interrupt();
Call Thread.sleep() inside your run() method, this causes to sleep thread that calls this method
Related
I have a java-program which runs on a schedule and fetches some data from external sources via RFC calls. The RFC calls are threaded and shall be canceled after 60 seconds. This is how I do it:
Future<String> future = executor.submit(new MyCallable());
try {
future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
}
This worked for a long time until I came accross a situation, where the external RFC call became stuck and future.cancel(true) was unable to interrupt the thread-execution. So my java-program never finished and continued running until I manually canceled the corresponding process within the external system.
My question now is, how can one guarantee the code to finish in any situation? I saw that stopping the thread is depreciated.
Would it be a good idea to do sth like this?
try {
future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
if(!future.isDone()){
System.exit(1);
}
}
Thanks for any ideas on this.
Cheers, Jooo
I believe that there's no way in Java to just kill off a thread if during execution not implemented InterruptedException . If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.
No need to check after every line, of course, but methods which can take a long time to execute are responsible for properly handling interrupts
kill the process in which the thread is running. (E.g., call System.exit(int).)
I currently have the following problem:
I have made a 'Cache Updater Thread', which checks for updates and then sleeps for some amount of time. I have also build a Button, which enables the user to check for updates manually. The Thread is built like this:
public static Thread cacheUpdater = new Thread(new Runnable() {
int milliSecondSleepTime = 10000;
public void run() {
try {
cacheUpdater.setPriority(Thread.MIN_PRIORITY);
//Infinite loop
while (!terminate) {
syncStatus.set(0);
//Check for updates with some methods, not important here.
syncStatus.set(1);
Thread.sleep(this.milliSecondSleepTime);
}
}
catch (InterruptedException e) {
//First check if it is termination time
if (!terminate) {
syncStatus.set(0);
this.run();
}
}
catch (Exception e) {
System.out.println(e);
}
return;
}
});
If the user clicks the manual-update button, the following code is being runned:
#FXML public void syncOnRequest() {
//Only call interrupt, because then it will start again when terminate is still false
CacheManager.cacheUpdater.interrupt();
System.out.println(CacheManager.cacheUpdater.getState().equals(State.TIMED_WAITING));
while (!CacheManager.cacheUpdater.getState().equals(State.TIMED_WAITING)) {
//LOOP FOREVER
}
//Some code that needs to be executed after the cache is updated
}
I would like to continue executing code in the syncOnRequest() method, when the cache updater is ready with its manual update. I had the idea to check if it is sleeping, but this is not working, because the System.out.println() immediately returns true. I have measured the time it takes to do the update, and its between 200 and 400 ms.
What am I doing wrong here? And why is it always returning true?
Additional question: sometimes a click on the button just kills the Thread, because it just woke up. The InterruptedException is not thrown.
How can I make sure the Thread will also restart in that case?
Note that Thread#interrupt() is the only polite way to ask your thread to interrupt itself (unless you explicitly implement another). Using it to restart the check is therefore a bad practice. So is checking the thread state for synchronization purposes and exposing the thread that keeps your cache up-to-date to external clients.
You manager should have a updateCache() method you will call directly from UI code and auto-update thread will call the same method periodically*. In that method, make sure that access to your cached data is either correctly synchronized or it happens atomically.
*) Instead of implementing your own periodic thread, consider using
Timer and TimerTask classes as well as making it a daemon thread.
I have code that schedules one-time tasks to execute and does this over and over. It looks something like this.
public static void main(String[] args)
{
while(true)
{
....
TimerTask closeTask = new CloseTask(cli);
Timer timer = new Timer(true);
timer.schedule(closeTask, (long) (iPeriod * 60 * 1000));
...
}
}
public class CloseTask extends TimerTask
{
Client client;
CloseTask(Client in_client)
{
client = in_client;
}
public void run()
{
try
{
for(int iRetries = 0; state == OPEN; iRetries++)
{
logger.log_trade_line_grablock( "Thread " + Thread.currentThread().getId() + ": About to send message", true, true, true, true, true);
client.send_mesg("close");
logger.log_trade_line_grablock( "Waiting 5 seconds before retrying ", true, true, true, true, true);
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The intent of the run() method in the CloseTask class is to loop until the state variable changes from OPEN state to something else. However, intermittently the timer threads simply disappear, while state still equals OPEN, which I know by printing out all the thread ID's of the currently running threads every 5 minutes.
So my questions:
1) The only explanation I can think of is that the CloseTask object is throwing uncaught exceptions. Is that correct?
2) If 1) is correct why isn't my try catch block catching these exceptions?
3) If 1) is correct is there a way to catch these exception that slip through uncaught?
Thanks for any insight into this issue.
You're creating a Timer instance, but not making sure that it doesn't get garbage collected.
From the documentation:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection).
So basically, you need to hold on to the reference to the Timer you created instead of just using a local variable.
The boolean you are passing in tells whether or not the thread created will be daemon. If it is daemon, the thread will be stopped once all non-daemon threads are finished. Since the only non-daemon thread being run in your application is the main thread then it will immediately be stopped after the main method is completed.
As Jon Skeet mentioned there is some completion operations done if no live thread is referencing the Timer and the tasks complete, but if it's daemon and the main method completes, it may not exit gracefully. To continue the documentation
... However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.
To answer your question
The only explanation I can think of is that the CloseTask object is throwing uncaught exceptions. Is that correct?
If the JVM kills a non-daemon thread, it won't throw any exception. So you won't really know that it happened.
I am having a scenario :
I have a thread which is calling a method where i use Default HTTP client to execute a request. for getting the response I open an InputStream and use a Buffred Reader to read the stream.
While(s = buffer.readline .... )
Inside the while loop i keep looking at the response and see for a string " Hello " ...If i get the string i send the response object back ..
The While loop executes till i get the string
The while loop executes till i press the back key ( android )
Now the scenario works for my 1st point. But i face issue in the 2nd point.
When i press back key, i need to stop my thread.
but i am not able to do it. I tried :
thread.destroy
thread.interrupt
thread = null
None of the above works. In fact my thread is always running...
I am not clear if the issue is with Thread or the issue is with the While loop of the stream.
Because i see that the while loop is executing always..
Please help me the best way i can solve this issue...Whether close the thread or close the stream.
Please help me find way to close the stream and close the thread.
thread.destroy() is deprecated. Do not use it.
The safest way to stop an IO bound thread is by interrupting it.
The thread's logic must cooperate by (1) checking for isInterrupted() status and
(2) catching InterruptedException exception.
It is important that both #1 and #2 above will be handled. interrupt()ing a
thread can in some occasions result in exceptions and in others in setting of
status with no exception!
A safe thread implementation goes like this:
class MyThread {
private volatile boolean wasStopped;
public void run() {
try {
while (!Thread.currentThread().isInterrupted() && !wasStopped) {
do_thread_work();
}
} catch (InterruptedException e) {
return; // gracefully stop thread
}
}
public void gracefullyStop() {
wasStopped = true;
this.interrupt();
}
}
To stop the thread call
thread.gracefullyStop();
This pattern will work fine as long as the thread logic function (do_thread_work)
will not internally catch & dismiss InterruptedException. Be aware.
You will see other implementations that rely solely on isInterrupted() check
without the additional wasStopped flag. I think this is a bad practice.
Why?
Because if the interrupt() was raised while the thread was in a waiting mode
i.e. inside functions wait() join() or sleep(), the thread will indeed be woken,
but its interrupted status will be set to false.
Good luck.
try
{
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
I understand what the first part is doing. But what is the catch part waiting for? Like what needs to happen to execute this part.
Every piece of code is run by a "thread". You can think of that as a little virtual processor dedicated to running that particular piece of code.
By calling the Thread.sleep() method, you put this thread in the WAITING state for a certain amount of time. While WAITING, the thread cannot do anything, and in particular, it cannot "hear" calls from other threads.
The only way to wake up the thread and having it run its code again, is to sent it an interruption, which is a very strong signal. This is done by calling the interrupt() method of this thread, from another thread.
When waked up, the thread goes to the RUNNING state again, but to signal the developer that it was waked up earlier than expected, it throws an InterruptedException, which is a checked exception. This is why you have to catch it and deal with it.
The sleep method halts execution of the current thread, in your case 5000 milliseconds (5 seconds). This method however throws InterruptedException which has to be caught.
Because the Thread#sleep() method is defined to throw an InterruptedException under some circumstances, the developer should take care of it when this exact exception occurs. This is why the catch block is needed - to hold the logic which handles the InterruptedException
You thread is going to sleep for 5 seconds.
If another thread tries to wake this thread up (Interrupt). It will end up in the exception block and your stacktrace will be printed.
public class InterruptedException
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise occupied, and
the thread is interrupted, either before or during the activity.
Occasionally a method may wish to test whether the current thread has
been interrupted, and if so, to immediately throw this exception.
Best Explanation is Given ╠══ HERE
If InterruptedException throws(Thread interruption may cause this) from try block that will catch by catch block and as you define in the catch block,it will print the Exception stack trace.
If the Thread is interrupted then it will throw the exception and it will be catched in the catch block.
This is relevant to multithreaded applications.When you have reference to an object of a class that either implements Runnable or extends Thread, and inside that object, a Thread.sleep(i) method has been idling the process, you can call reference.interupt() on that reference and it will trigger the InterruptedException. Here's an example:
In the below code, the Scratch class's run method goes to sleep for 60000 ms (or 1 minute) and prints "I've been interrupted" if it receives an InterruptedExection. The way the code is written, it will not receive this exception and will sleep the entire time. But run it a second time with the line //scratch.interrupt(); uncommented and see what happens.
package scratch;
/**
*
* #author bstidham
*/
public class Scratch extends Thread {
public void run() {
System.out.println("Hello from a thread!");
System.out.println("Going to sleep for 1 minute...");
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
System.out.println("I've been interrupted!");
}
System.out.println("Awake now");
}
public static void main(String args[]) {
Scratch scratch = new Scratch();
scratch.start();
//scratch.interrupt();
}
}