Terminating thread from inside it's run method in Eclipse-RCP - java

I have done something like this in my code
public void doWork()
{
Job job = new Job("Job")
{
#Override
protected IStatus run(IProgressMonitor monitor) {
while (rsMemName.next()) {
Display.getDefault().syncExec(new Runnable() {
#Override
public void run() {
try {
String memId = rsMemName.getString("id");
if (doMemberTasks(memId)==false)
{
cnn.rollback();
return;
}
} catch (Exception ex) {
ex.printStackTrace();
try {
cnn.rollback();
return;
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
}
job.schedule();
}
What i want to do is exit from the whole method if doMemberTasks(memId) returns false.
But it doesn't return from the method and keep looping on ResultSet. how can i terminate the thread from the run method?
Please give any suggestions how could i achieve that.....
Thanks in advance....

This is because return will return only from the thread run method. What you can do is set a variable(flag) probably static, and check its value after the run code to put another return statement.

Yeah your best bet would be to have a flag,
boolean doWork = true;
...
while( doWork && rsMemName.next(){
...
if (doMemberTasks(memId)==false)
{
cnn.rollback();
doWork = false;
return;
}

Related

Java Thread interrupt() - how fast is it performed?

How much time does a Thread need to stop/disappear after its interrupt() method has been called?
Consider the following code:
public class MyThread {
public boolean flag = true;
public void run() {
while(flag) {
doSomething();
Thread.sleep(20);
}
}
}
void foo() {
MyThread t = new MyThread();
t.start();
Thread.sleep(100);
t.flag = false;
t.interrupt();
}
Does the assignment t.flag = false; have any effect? In other words, can a thread exit its run() method and terminate "normally" before it is interrupted?
similar question
For sharing data one needs volatile. Better would be to catch the InterruptedException.
public class MyThread {
public volatile boolean flag = true;
public void run() {
try {
while(flag) {
doSomething();
Thread.sleep(20);
}
} catch (InterruptedException ie) {
...
}
}
}
Check agains isInterrupted, anhd throw it again since when it returns true it consumes the message.
public class MyThread {
public void run() {
try {
while(!Thread.isInterrupted()) {
doSomething();
Thread.sleep(20);
}
} catch (InterruptedException ie) {
Thread.interrupt();
}
}
}
Making the flag unecessary.
If you want to use the flag and finish the code gracefully you don't need to use interrupt and catch the Exception.

How to wait for callback before leaving method (Java)

I have a method in which I call another method that has a callback. I want to receive this callback before leaving my method. I saw some other posts in which latches are used. My code looks like this:
public void requestSecurityToken(<some params>){
final CountDownLatch latch = new CountDownLatch(1);
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
//TODO
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This doesn't work, the method is stuck in the await() function. What happens is that, the method immediately jumps to the await(), and doesn't go into the onRequestSuccess() or onRequestFailure() method again. I guess this is a concurency problem... Any ideas on how to fix this issue?
EDIT: Added the line of code where I create the latch.
When you are doing this
new RequestListener<Login>
You are passing an object to your function , which implements an interface.
That is why those methods are not getting called , those methods are called only when you get the request result (success or failure).
You can do this instead.
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
someFunction();
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
someFunction();
latch.countDown();
}
});
public void someFunction()[
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

How to use InterruptedException effectively

Given code is working in doInBackground(). Where while loop is always true but i don't know how it calls other methods in catch.
Can someone explain me the technique and how can we benefit with this technique. I don't know how and when we get out of the loop.
doInBackground
if(isRunning)
{
while (true) //this loop should run always.
{
try
{
Thread.sleep(1L);
}
catch (InterruptedException ex)
{
Log.e("Testing Interuption", "error=" + ex.getMessage());
// some working here is also running
}
}
}
Can it call any statement after while or not? I mean can it also get out of while loop or not.
Edit
When did the Interuption Occur.It means when another AsyncTask is calling Thread.sleep(); it will interupt(means go to catch). Am I right?
I am calling Multiple AsyncTasks to set a CameraPreview using Bitmap.
#TargetApi(11)
public void start()
{
if (Build.VERSION.SDK_INT >= 11)
{
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
return;
}
execute(new Void[0]);
}
The while (true) statement will never end, since there's nothing to break out of the loop, so no, it can not get out of the while loop. (Depends on what's in // some working here is also running though.)
The code in the catch statement is executed if another thread sends an interrupt to this thread. When the code has been executed under catch the while loop re-starts again.
If you want to break out of the while loop if an InterruptedException is received, add a break; statement inside the catch.
It can call anything, as long as you break out of your loop, like this:
if (isRunning) {
while (true) //this loop should run always.
{
try {
Thread.sleep(1L);
}
catch (InterruptedException ex) {
Log.e("Testing Interuption", "error=" + ex.getMessage());
// some working here is also running
break; // <--
}
}
doStuffAfterWhileLoop();
}
i wrote some code, which should help you to understand how it is working.
public class Test2 {
boolean doBreakOut = false;
public Test2() {
Runnable runnable = new Runnable() {
#Override
public void run() {
while (true) // this loop is running while
// !(doBreakOut == true && isInterrupted()).
{
try {
Thread.sleep(1L);
} catch (InterruptedException ex) {
// this is executed when interrupt() is called.
if (doBreakOut) {
break;
}
System.out.println(("Testing Interuption -> "
+ "error=" + ex.getMessage()));
}
}
System.out
.println("did leave loop, threat will shut down now.");
}
};
try {
Thread threat = new Thread(runnable);
threat.start();
// Thread.sleep(x) makes the main thread wait for x milliseconds
Thread.sleep(2000);
threat.interrupt();
Thread.sleep(2000);
threat.interrupt();
Thread.sleep(2000);
doBreakOut = true;
threat.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test2();
}
}

Thread not continue running

I have a following code as below:
new Thread(new Test1Runnable()).start(); // Line (a)
public class Test1Runnable implements Runnable {
public void run() {
Test2Runnable task1 = new Test2Runnable();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(task1);
while(true) {
if(task1.isDone()) {
break;
}
// Thread.sleep(2000); // Line (b)
}
if(!task1.hasError()) { // Line (c)
executor.submit(new Test3Runnable());
}
} catch(Exception ex) {
if(executor != null) {
executor.shutdown();
}
}
}
}
public class Test2Runnable implements Runnable {
private Exception error;
private boolean done;
public void run() {
reset();
doRun();
done = true;
}
protected void doRun() {
try{
// ...
// ....
} catch(Exception ex) {
}
}
private void reset() {
error = null;
done = false;
}
public boolean isDone() {
return done;
}
public boolean hasError() {
return getError() != null || getNonSuccess() > 0;
}
public Exception getError() {
return error;
}
}
I have an issue when I run Test1Runnable at line (a) and comment Line (b) then the thread hang and not run to Line (c). If I uncomment line (b) or I add breakpoint at line (c) and activate remote debug the thread continue to run to the end as normal. Could anyone can give me some advice about this? Why the Thread not continue running? All threads run without any exception.
Looks like you have a race conditioin here, so result of the execution depends on timings, debug enabled, etc. The code posted is more or less fine, the error is likely to be in Test2Runnable class. I suppose there are some flags (isDone, hasError) that have visibility issues. Try to declare them volatile.
Please add Test2Runnable code here and I'll be able to give more precise answer.

Java Thread StackOverflowError

...
Thread showWordThread = new Thread() {
public void run() {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
this.run();
}
};
showWordThread.run();
}
...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
But error still occured.
Others have explained that you should use a while loop instead. You're also trying to call the run method inside your anonymous class declaration. Additionally, you should call start, rather than run - when the new thread has started, it will call run automatically. I'd actually suggest implementing Runnable rather than extending Thread, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
#Override public void run() {
while (someCondition) {
try {
Thread.sleep(config.delayTime * 1000);
// Presumably do something useful here...
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
Alternatively, consider using a Timer or ScheduledExecutorService.
You are calling run method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow exception throws.
Maybe you want increasing Heap Size of JVM but this solution don't solve your problem and StackOverflow will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
public void run()
{
try
{
sleep(config.delayTime * 1000);
}
catch (Exception e)
{
System.out.println(e.toString());
}
// this.run(); this snnipet code make error
}
};
showWordThread.run();
}
Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while loop.
Thread showWordThread = new Thread() {
public void run() {
while(condition) {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
showWordThread.start();
}
Your code have infinity recursive, you should change the code to:
Thread showWordThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
};
showWordThread.start();
Your function calls itself each time you run it.
That results in a stack overflow.
Maybe because you call run method (this.run()) from itself?

Categories

Resources