Android - do threads stop on their own? - java

I've been looking around and I really haven't found an answer to this. I know it's good practice to stop the threads yourself, but I've been wondering what happens when I forget to stop them. If I create a new thread and have it run some task, what happens to the thread when the task is completed? For example what happens to the thread in this case:
Thread t = new Thread(new Runnable(){
public void run() {
for (int i = 0;i<10;i++){
foo;
}
}
});
t.start();
Does thread t stop automatically, does it just keep eating up resources, or does it do something else?

The thread will stop when the end of the run method is completed. In your example this would be after 10 iterations of the for loop, assuming foo did not block. If there are no more references to this thread it will then be garbage collected by the JVM.

When run() completes, the thread finishes, yes. It is not good practice to stop() a Thread, if that's what you mean.

If not a daemon, it won't consume all the resources upon the completion of the task.

Related

stop an infinite loop within a thread

Thread d = new Thread(new Runnable() {
#Override
public void run() {
while(true);
}
});
d.start();
How can I quit the infinite loop, without changing the code inside the method public void run(),
and without using d.stop(); (deprecated method).
P.S: I'd prefer publishing the whole exercise details I need to do. That's kinda the thing I need to dill with. They gave me a function which sometimes goes inside infinite loop, and I can't change that method.
How can I quit the infinite loop, without changing the code inside the method public void run(), and without using d.stop(); (deprecated method).
I assume this is some sort of academic or interview question. If you can't change the thread code then you can't add an interrupt or volatile boolean check. And you can't call .stop() (which is btw deprecated and never a good idea).
The only thing I can think of is to set the thread be a daemon thread.
Thread d = new Thread(new Runnable() { ... });
...
d.setDaemon(true);
d.start();
It needs to be set daemon before it is started. This is a hack but maybe within the framework of the question. This won't kill the thread immediately but if the last non-daemon thread exits then the thread will be killed by the JVM.
Of course you can also remove the .start() line but that seems outside the realm of the question. System.exit(0); would also bring down the JVM as #MattBall pointed out but that also seems like cheating.
Outside of killing the JVM running the thread, I don't see how you can quit the loop.
A better method would at minimum check for thread interruption:
Thread d = new Thread(new Runnable() {
#Override
public void run() {
while(!Thread.currentThread().isInterrupted());
};
d.start();
d.interrupt();
You can't. The only way to stop a thread asynchronously is the stop() method. But without that, you can't.
Without .stop() you need to change the code in the thread itself. see here here for some ideas.
Always avoid while(true). Try while(running). That condition should determine the life of the loop. Then when you set running = false, the life of the loop ends and subsequently the thread.

Can I start a thread again after it has died?

If I use start() on a Thread object and the run() method returns, is it possible to call start() again?
eg,
MyThread myThread = new MyThread();
myThread.start();
// run method executes and returns in 2 seconds
// sleep for 5 seconds to make sure the thread has died
myThread.start();
I'm just wondering because my code is throwing IllegalThreadStateExceptions, so want to know if it's because you can't do the above.
No, you can't. And the Javadoc for the Thread.start() method tells you that!
From a comment:
Is there anything else I could do to re-start a thread?
You could use ThreadPoolExecutor, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
So, you don't restart a thread, but you would redo/resume a task.
Nope.
From the Javadoc for java.lang.Thread:
It is never legal to start a thread
more than once.
From the javadoc:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
See the Thread.start() javadoc for more information.
There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.
Perhaps there is a better way of doing this if you want the thread to stop and restart multiple times. I have a tile caching thread in C++ that does something similar; it pauses when it's finished, and unpaused when it's needed again. I am new to Java, but from what I can tell, you can use Object.wait() to pause, and Object.notify() to resume threads. Maybe you could check those out in the documentation and redesign your thread to pause and resume instead of exiting.

isAlive() method of java thread is not working properly?

I was trying a example of isAlive() method of java threading. But i found that isAlive() method is returning false even if thread has been already started. Can someone please tell me what am i doing wrong? Here is the code snippet.
package app;
public class ThreadAliveDemo {
public static void main(String[] args) {
Thread myThread;
myThread = new Thread()
{
public void run()
{
Thread.sleep(3000);
System.out.println("My Thread.");
}
};
myThread.setName("My Thread");
myThread.start();
if(!myThread.isAlive())
{
myThread.setName("My Thread");
myThread.start();
}
}
}
There's a good chance the thread will have started, executed, and finished, between your call to start() and your call to isAlive().
Java offers no guarantees on the sequence in which these things happen. It could execute the spawned thread immediately, or it may choose to defer it until a bit later.
Incidentally, your code is trying to re-start the thread after it has died. This is not permitted:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
So calling start() after checking isAlive() is never going to work.
If my memory serves me well java has quite long periods between thread switching so it is possible that the isAlive fails because the thread is not yet alive. Try to add some waiting time between thread.start() and thread.isAlive()
I haven't done any multithreading in java yet, but it looks to me like your thread probably will have run and exited before the isAlive() check. After all, looks like your thread just prints something out and then dies.
Happened to me recently, fixed it using
if(yourThread.getState() == Thread.State.NEW){
yourThread.start();
}
instead of yourThread.isAlive();
I don't see the point of the code you have posted. Thread.start() starts the thread: you don't need to start it twice. I don't see how your code can realistically into a situation where it has a Thread and doesn't know whether it has been started or not; anyway there are plenty of ways to code around that so it can't happen.

java background task

I was wondering which would be the most efficient approach to implement some kind of background task in java (I guess that would be some kind of nonblocking Threads). To be more precise - I have some java code and then at some point I need to execute a long running operation. What I would like to do is to execute that operation in the background so that the rest of the program can continue executing and when that task is completed just update some specific object which. This change would be then detected by other components.
You want to make a new thread; depending on how long the method needs to be, you can make it inline:
// some code
new Thread(new Runnable() {
#Override public void run() {
// do stuff in this thread
}
}).start();
Or just make a new class:
public class MyWorker extends Thread {
public void run() {
// do stuff in this thread
}
}
// some code
new MyWorker().start();
You should use Thread Pools,
http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html
Naïve idea : you might be able to create Thread, give it a low priority, and do a loop of :
doing a little bit of work
using yield or sleep to let other threads work in parrallel
That would depend on what you actually want to do in your thread
Yes, you're going to want to spin the operation off on to it's own thread. Adding new threads can be a little dangerous if you aren't careful and aware of what that means and how resources will interact. Here is a good introduction to threads to help you get started.
Make a thread. Mark this thread as Daemon. The JVM exits when the only thread running are all daemon threads.

Is it legal to call the start method twice on the same Thread?

The following code leads to java.lang.IllegalThreadStateException: Thread already started when I called start() method second time in program.
updateUI.join();
if (!updateUI.isAlive())
updateUI.start();
This happens the second time updateUI.start() is called. I've stepped through it multiple times and the thread is called and completly runs to completion before hitting updateUI.start().
Calling updateUI.run() avoids the error but causes the thread to run in the UI thread (the calling thread, as mentioned in other posts on SO), which is not what I want.
Can a Thread be started only once? If so than what do I do if I want to run the thread again? This particular thread is doing some calculation in the background, if I don't do it in the thread than it's done in the UI thread and the user has an unreasonably long wait.
From the Java API Specification for the Thread.start method:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
Furthermore:
Throws:
IllegalThreadStateException - if the thread was already started.
So yes, a Thread can only be started once.
If so than what do I do if I want to
run the thread again?
If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.
Exactly right. From the documentation:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
In terms of what you can do for repeated computation, it seems as if you could use SwingUtilities invokeLater method. You are already experimenting with calling run() directly, meaning you're already thinking about using a Runnable rather than a raw Thread. Try using the invokeLater method on just the Runnable task and see if that fits your mental pattern a little better.
Here is the example from the documentation:
Runnable doHelloWorld = new Runnable() {
public void run() {
// Put your UI update computations in here.
// BTW - remember to restrict Swing calls to the AWT Event thread.
System.out.println("Hello World on " + Thread.currentThread());
}
};
SwingUtilities.invokeLater(doHelloWorld);
System.out.println("This might well be displayed before the other message.");
If you replace that println call with your computation, it might just be exactly what you need.
EDIT: following up on the comment, I hadn't noticed the Android tag in the original post. The equivalent to invokeLater in the Android work is Handler.post(Runnable). From its javadoc:
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* #param r The Runnable that will be executed.
*
* #return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
So, in the Android world, you can use the same example as above, replacing the Swingutilities.invokeLater with the appropriate post to a Handler.
No, we cannot start Thread again, doing so will throw runtimeException java.lang.IllegalThreadStateException.
>
The reason is once run() method is executed by Thread, it goes into dead state.
Let’s take an example-
Thinking of starting thread again and calling start() method on it (which internally is going to call run() method) for us is some what like asking dead man to wake up and run. As, after completing his life person goes to dead state.
public class MyClass implements Runnable{
#Override
public void run() {
System.out.println("in run() method, method completed.");
}
public static void main(String[] args) {
MyClass obj=new MyClass();
Thread thread1=new Thread(obj,"Thread-1");
thread1.start();
thread1.start(); //will throw java.lang.IllegalThreadStateException at runtime
}
}
/*OUTPUT in run() method, method completed. Exception in thread
"main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
*/
check this
The just-arrived answer covers why you shouldn't do what you're doing. Here are some options for solving your actual problem.
This particular thread is doing some
calculation in the background, if I
don't do it in the thread than it's
done in the UI thread and the user has
an unreasonably long wait.
Dump your own thread and use AsyncTask.
Or create a fresh thread when you need it.
Or set up your thread to operate off of a work queue (e.g., LinkedBlockingQueue) rather than restarting the thread.
What you should do is create a Runnable and wrap it with a new Thread each time you want to run the Runnable.
It would be really ugly to do but you can Wrap a thread with another thread to run the code for it again but only do this is you really have to.
It is as you said, a thread cannot be started more than once.
Straight from the horse's mouth: Java API Spec
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
If you need to re-run whatever is going on in your thread, you will have to create a new thread and run that.
To re-use a thread is illegal action in Java API.
However, you could wrap it into a runnable implement and re-run that instance again.
Yes we can't start already running thread.
It will throw IllegalThreadStateException at runtime - if the thread was already started.
What if you really need to Start thread:
Option 1 ) If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.
Can a Thread be started only once?
Yes. You can start it exactly once.
If so than what do I do if I want to run the thread again?This particular thread is doing some calculation in the background, if I don't do it in the thread than it's done in the UI thread and the user has an unreasonably long wait.
Don't run the Thread again. Instead create Runnable and post it on Handler of HandlerThread. You can submit multiple Runnable objects. If want to send data back to UI Thread, with-in your Runnable run() method, post a Message on Handler of UI Thread and process handleMessage
Refer to this post for example code:
Android: Toast in a thread
It would be really ugly to do but you can Wrap a thread with another thread to run the code for it again but only do this is you really have to.
I have had to fix a resource leak that was caused by a programmer who created a Thread but instead of start()ing it, he called the run()-method directly. So avoid it, unless you really really know what side effects it causes.
I don't know if it is good practice but when I let run() be called inside the run() method it throws no error and actually does exactly what I wanted.
I know it is not starting a thread again, but maybe this comes in handy for you.
public void run() {
LifeCycleComponent lifeCycleComponent = new LifeCycleComponent();
try {
NetworkState firstState = lifeCycleComponent.getCurrentNetworkState();
Thread.sleep(5000);
if (firstState != lifeCycleComponent.getCurrentNetworkState()) {
System.out.println("{There was a NetworkState change!}");
run();
} else {
run();
}
} catch (SocketException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread checkingNetworkStates = new Thread(new LifeCycleComponent());
checkingNetworkStates.start();
}
Hope this helps, even if it is just a little.
Cheers

Categories

Resources