Kill one thread in sleep mode in android - java

I have an android application, that have one thread, which will run after each 1 minute.
So my problem is, when i click one button, i have to reset the app, that means, it'll be
a fresh app.
So now when i clicked on that button, all the database and shared preference will clear.
But the thread will start again.
Now am using like this
if (killthread.isAlive()) {
killthread.interrupt();
}else {
// Here what'll i do, I mean how to kill that thread, which in sleep mode.
}
Thank you
vishnu

Thanks for the reply, Here when i click that button, that will come to the else part, but after 1 minute, the thread will start.So how to stop that in stage?
That will be something to do with the thread itself. My bet is that you have coded it to ignore the interrupt.
OK, here's the code from your comment.
public void run() {
while (true) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
}
What this does is to catch and silently ignore the exception that occurs when the thread is interrupted ... and just keep going.
If you want it to stop on an interrupt it should be this ... or something equivalent.
public void run() {
while (true) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
return;
}
}
}

If a Thread is not alive it means
1) it's dead / finished. You cannot / dont need to do anything.
2) it is newly created / havent started yet. That is Thread.start() has not been called yet. In this case Thread.interrupt() will have no effect. The only thing you can do is some custom logic - notify the code that is going to start the thread that it's not needed anymore

Related

Stopping a Thread / Threads calls interrupt on itself after crash?

I am currently running a Thread from a Service to do some background work.
Now there is the possibility that the Thread crashes or I want to
interrupt the thread from the Service. So how am I supposed to:
stop the Thread realiable, (hard)
catch exceptions and call the Service about the crash
handle InterruptedException if interrupted while sleep()
is Thread.isInterrupted a good way to detect if the Thread stopped?
What I have done so far is the following:
#Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
doMyBackgroundWork();
sleep();
}
}catch(Exception e){
ExceptionHandler.logAndSendException(e);
Thread.currentThread().interrupt();
if(crashedListener != null){
crashedListener.onThreadCrashed();
}
}
LOG.i("Thread stops now.");
}
private void sleep() {
try {
sleep(frequency);
} catch (InterruptedException e) {
//what to do here? it can happen because I stopped it myself
}
}
So at first I am running my Thread until it gets interrupted.
If any exception occurs, I want to start a new Thread, therefore
my Service implements a listener interface and I call it, once an
Exception is thrown. I know that catching everything is discouraged,
but I need to know if the Thread stops, without polling Thread.isAlive()
all the time.
Additionally to my four questions above:
is my code reliable and does what I need?
is it ok to call interrupt on the Thread itself?
Thanks!
You are not actually interrupting your own thread because the catch block is outside of the while loop. Therefore, any exception would stop execution immediately.
Interruption is essentially just a request (usually from another thread) to stop doing what you are doing. The thread is free to ignore it and keep doing what it is doing. Normally you have to throw an exception in response to an interrupt, or stop execution some other way such as just breaking from the loop (you need this around the //what to do here? comment). It so happens that some library methods are "responsive to interruption" meaning they will throw an exception if the thread is ever interrupted, such as Thread.sleep(), which you will most likely have in your sleep call.
I recommend picking Java Concurrency In Practice. Among the excellent concurrency material, there is a chapter on interrupts which is very helpful.
EDIT:
I would remove the code where you interrupt your own thread. You will also need to rethrow the InterruptedException as a runtime exception to get out of the execution loop. Usually people will create a new Exception that extends RuntimeException that is something like MyInterruptedException. You can then add it to the catch block around your loop so that you know when the thread was interrupted vs execution failed.
As a general example you can do something like this:
public void run() {
try {
while (true) {
// check for interrupts in the loop, or somewhere in the work method
if (Thread.interrupted()) {
throw new MyInterruptedException("Important thread interrupted.");
}
doMyBackgroundWork();
sleep();
}
}
catch(Exception e){
ExceptionHandler.logAndSendException(e);
if(crashedListener != null){
crashedListener.onThreadCrashed();
}
}
catch(MyInterruptedException i) {
LOG.i("Execution stopping because of interrupt.");
}
}
private void sleep() {
try {
sleep(frequency);
} catch (InterruptedException e) {
throw new MyInterrptedException(e);
}
}
we have a nice and effective method called stop()(Thread.stop(void):void) which is deprecated, but it works and it's lovely.
Note that stop() throws ThreadDeath at the target thread which is not an exception(and it could any other throwable too), but an Error, so your code will not catch any signal about this.
public void run() {
try {
while (<<using_a_volatile_bool_type_is_better>>) {
...
}
}catch(Throwable t){/**/}/*use throwable instead of exception.*/}
}
Beside dear friend stop() we also have pause() method too, and it really pauses the target thread.
Not just one solution out there, but if it's really critical to keep thread run and run the emergency(or itself) just after any crash, you may run it as a separately app/process, plus get progress status(if any) that ensures you the target thread/app is not freezed(blocked,...)

Thread Interrupted sometimes works and sometimes not

Please help me with my problem. I have 2 JMenuItems, if I Click on Start it shall start and do stuff. If I click on Stop it shall stop :)
After i clicked on Start, I click on Stop and sometimes it stops and sometimes not. But I want that it always stops.
What have I done wrong? :/
class DiashowListener implements ActionListener {
Thread td;
boolean ok = false;
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Start")) {
td = new Thread(new Runnable() {
public void run() {
if (bimg != null) {
while (!ok) {
try {
...
} catch (Exception e2) {
}
frame.repaint();
}
}
}
});
td.start();
} else if (e.getActionCommand().equals("Stop")) {
if (td != null){
ok = true;
}
}
}
}
EDIT: ok I changed something, its working now, but: If I click on Stop it shall stop immediately.
First of all, you are interrupting the wrong thread (should be td). Second, the contents of the try clause that you omitted is actually important (some operations are uninterruptible). Finally, Thread.isInterrupted is likely not what you want to use, as the flag may get cleared by some unrelated code. Depending on what exactly you are interrupting, it may (or may not) be a good idea to just catch InterruptedException, and terminate in case it is thrown. A better approach is to add your own flag, that the thread will check instead of isInterrupted, and the event handler will set instead of (or in addition to) interrupting the worker thread.

Interrupting a normally running thread in java

I am trying to interrupt a normally running thread (which is not in sleep() or wait() state) .
while going through in net i got to know interrupting a normally running thread will just set the flag true and continue the process.
Code snippet is
one.java
......
......
actionperformedmethod {
if (actionCmd.equals("cancel")) {
try {
r1.stop(); // to two.java
} catch (InterruptedException ex) {
....
....
}
}
}
in two.java
.....
.....
stop method() throws InterruptedException{
if(!(t.isInterrupted())){
t.interrupt();
throw new InterruptedException();
}
}
from two.java when i throw InterruptedException i can able to get the exception block at one.java , but how do i stop the thread after that because even after that thread seems to continue the normal process.
Am new to thread concepts please help..
The interrupt() method is co-operative rather than pre-emptive - the background task needs to actively check Thread.interrupted() at suitable intervals, and take action to shut itself down cleanly.
public void run() {
openSomeResources();
try {
while(notFinished) {
if(Thread.interrupted()) return;
doSomeStuff();
}
} finally {
closeTheResources();
}
}
In this example if the thread is interrupted in the middle of doSomeStuff() then it will complete the current "iteration" before responding to the interruption. Getting the correct balance between responding promptly to an interrupt on the one hand, and responding only at a safe point in the execution on the other hand, is something that is inherently specific to the particular task - there is no one-size-fits-all answer.
Note however that any blocking method that throws an InterruptedException will reset the interrupt flag when this exception is thrown. Therefore in order for this sort of checking to work you must re-interrupt yourself whenever you receive an InterruptedException
try {
Thread.sleep(3000);
} catch(InterruptedException e) {
// we were interrupted - set the flag so the next interrupted() check will
// work correctly.
Thread.currentThread().interrupt();
}
Interrupt will not stop the thread. it just sets the flag to true to signal the thread to stop the execution soon.
to stop the execution
add global variable as
private volatile boolean exit = false;
and
you add one method in your 2nd class
public void requestExit(){
exit = true;
}
inside run () of your thread do something like this
if (exit == true){
return;
}
whenever you want to call just call this method requestExit() from your main() or wherever you want to stop
this is the best way to stop the thread.. using stop() on thread is dangerous as it does not clear any resources and its not advisable to use even by oracle hence deprecated.
let me know for any issues
Threads are only running whilst their run() method is on the stack so usually people put a while(true) inside the run method, all you need to do in you thread to stop it is to return somewhere in the run method or break the loop then as soon as the run() method is no longer running the thread has been stopped.

How to add breakpoints to Runnable classes

My while(true) is only running once, so I'm trying to add breakpoints to see what's going on, but they never seem to be reached within my run(). I'm using IntelliJ. In the debugger there's a "Threads" tab. Do I need to do something in that tab like select the right thread in order for my breakpoint to be reached? I also see thread names and am wondering how I can find the right thread in this list.
public class MyClass extends ServerWorkflowProcess<OtherClass> {
private ExecutorService executorService = Executors.newSingleThreadExecutor();
...
#Override
public void bootup() {
logger.info("Booting up: " + this);
BackgroundProcess backgroundImpositioner = new BackgroundProcess(this.getCollection());
executorService.submit(backgroundImpositioner);
}
#Override
public void shutdown() {
executorService.shutdown();
}
}
Background process
public class BackgroundProcess implements Runnable {
protected volatile Logger logger = Logger.getLogger(BackgroundImpositioner.class.getName());
Collection<ImpositionWorkstation> impositionWorkstations;
public BackgroundImpositioner(Collection<ImpositionWorkstation> impositionWorkstation) {
this.impositionWorkstations = impositionWorkstation;
}
public void run() {
while(true) {
logger.info("looping");
for (ImpositionWorkstation workstation : impositionWorkstations) {
if (workstation.canAcceptWork()) {
//go do work in another thread so we're not blocking this
workstation.getWorkFromQueue();
try {
workstation.doWork();
} catch (ImpositionException e) {
logger.severe(e.getMessage());
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
logger.severe("Background impositioner was interrupted");
}
}
}
}
Side note: the console shows "looping", so I know it gets executed once. The breakpoint never gets hit and it doesn't execute more than once.
It happened to me once that i couldn't make Intellij Idea stop in breakpoints. Basically the problem is that once a thread is stopped in a breakpoint the others won't stop.
There is a setting in the breakpoints properties dialog that prevents this.
Right click on a breakpoint and select 'View Breakpoints'.
On the dialog select a breakpoint.
You will notice on the right of suspend checkbox 2 radio buttons: All and Thread. Select All. Aditionally you can make that the default (Make Default button on the right). The default value will be used for any new breakpoints you add. The old ones need to be changed manually.
EDIT
Additional info on the Intellij help site: Breakpoint options
Don’t let exceptions slip through silently. Use the Future returned by the submit method.
Future<?> f=executorService.submit(backgroundImpositioner);
try {
f.get();
} catch(Exception ex) {
ex.printStackTrace();
}
Then you know more.
The code above is just for finding your actual problem. For production environments you wouldn’t wait for completion but rather log the exception when it occurred, e.g.:
executorService.execute(new FutureTask<Object>(backgroundImpositioner, null)
{
#Override
protected void done() {
if(!isCancelled()) try {
get();
} catch(InterruptedException ex) {
throw new AssertionError("on completed task", ex);
} catch(ExecutionException ex) {
logger.log(Level.SEVERE, "in background task", ex.getCause());
}
}
});
For a reason beyond me, I was not able to breakpoint the while(true) line, but was able to drop breakpoints elsewhere within the run().
If there's no exception thrown inside the run method, i can only assume that one of the calls never returns.
Can you put output statements after every single call to see how far you get?
I guess either workstation.canAcceptWork() or workstation.doWork() is the culprit.
I've met a similar problem that IntelliJ never hits my breakpoint in the run() method of a Runnable class. I found that the only position for the breakpoint to be hit is at the line of public void run() {.

Learning Threads - Running a method only after the other has finished

In my button execution, I am calling 2 methods.
plotButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
startPrinterListOperation();
showAplotPlotterDialog();
}
});
The startPrinterListOperation(); takes some time to complete its task. But I do not want the method showAplotPlotterDialog(); to run until the first one has completed. So I am trying to use thread management to achieve this. Here is what I have tried.
plotButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Thread t = new Thread() {
public void run() {
startPrinterListOperation();
}
};
t.start();
try {
t.join();
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
showAplotPlotterDialog();
}
});
But the second method stills starts before the first one has finished.
Extending on my comment: Seems like startPrinterListOperation launches an asynchronous operation and finishes instantly, evidented by the join succeeding.
If the launched async op is out of your control, then you might be able to observe it finishing via some callback, polling, etc. Then you may employ something like the following in startPrinterListOperation:
void startPrinterListOperation() {
final CountDownLatch c1 = new CountDownLatch(1);
launchTheAsyncOp(new SomeCallback() {
void x() {
c1.countDown();
}
});
try {
c1.await(999, TimeUnit.SECONDS)
}
catch (InterruptedException e) {
throw new MyRuntimeException("user didn't finish the op in 999 seconds, fail");
}
}
I would not bother with threads, this will just make your program overly complicated.
Can you edit the startPrinterListOperation() method?
I would instead add showAplotPlotterDialog(); to the end of the startPrinter method, and the last last thing the method does.
Answering your general question in the title, you have a master thread that calls your two methods directly, so that the second method waits for the first method to complete.
I understand that in your specific case, the first method runs for a while, and you would prefer that the user not have to wait.
You should call a generatePrinterList() method in a separate thread while you're constructing the GUI. You do this because your GUI users are very likely to print or plot, and the printer list is not likely to change while the user is using your GUI.
Odds are that the generatePrinterList() thread will finish long before your user has to print or plot. But just to be sure, the thread has to have a way of reporting back that the thread is completed. I use a boolean isCompleted that can be read with a public isCompleted() method.
The isCompleted() method could have a thread sleep loop if you want, so it always returns true. In this case the method doesn't have to return anything.

Categories