How to use InterruptedException effectively - java

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();
}
}

Related

how to make main thread wait for another one to finish in Java?

I have come up with following thread 'halo' to make it connect to db (redis, in this case) and in the event that server fails, would wait for a second and try again. In my unit test class, method is executing, and not long after new thread starts, server will fail. But then this new thread 'halo' is immediately shut down. What am I doing wrong?
// almost infinitely large number of sets, interrupted by server seg-fault
// you gotta try company methods
Thread halo = new Thread(new Runnable() {
#Override
public void run() {
int count = 0;
while (count < Integer.MAX_VALUE) {
if (JedisPoolFactory.getStatus()) {
try {
for (int i = 0; i < 10000; i++) {
master.set(String.format("key_%d", count), String.format("value_%d", count));
System.out.println(master.get(String.format("key_%d", count)));
count++;
}
} catch (JedisConnectionException igr) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {}
}
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException ignrod) {}
}
}
}
});
halo.start();
try {
master.debug(DebugParams.SEGFAULT());
halo.join();
} catch (JedisConnectionException ignored) {
} catch (InterruptedException igr) {}
thread joining should be done outside of exceptions, when master goes segfault it invokes jedisconnectionexception.

Briefly taking control of an object owned by another thread

I hava a Java-controlled robot. It has an ultrasonic sensor that is rotated back and forth by Motor B.
Normally, I have a separate thread that scans the environment and sends the collected data to another machine in order to draw a map.
However, sometimes the main thread needs to briefly use the sensor to look in a specific direction.
Here's my scanner thread:
public void run() {
while (!stop) {
Motor.B.forward();
while (Motor.B.getTachoCount() < 90 && !stop) {
try{Thread.sleep(20);} catch (InterruptedException ex) {ex.printStackTrace();}
Mapperbot.sendCommand("S US "+sonic.getDistance()+" "+Motor.B.getTachoCount());
}
Motor.B.backward();
while (Motor.B.getTachoCount() > -90 && !stop) {
try{Thread.sleep(10);} catch (InterruptedException ex) {ex.printStackTrace();}
}
}
Motor.B.stop();
}
And here's the "tell me the direction now" function, it belongs to the same class:
public synchronized int getDistanceInDirection(int direction) {
Motor.B.rotateTo(direction);
return sonic.getDistance();
}
The required behavior: Whenever "getDistanceInDirection" is called, it must briefly stop scanning and turn to the given direction, return the distance, and continue scanning.
What is the correct way to tell my scanner thread for the time it takes to execute the second function?
I would use a semaphore:
final Semaphore semaphore = new Semaphore(1);
//in the scanner thread
semaphore.acquire();
try {
while (! stop) {
semaphore.release();
semaphore.acquire();
...use sensor...
} finally {
semaphore.release();
}
//in the main thread
semaphore.acquire();
try {
...use sensor...
} finally {
semaphore.release();
}
Throw in a synchronized(this)
public void run() {
while (!stop) {
synchronized(this) {
Motor.B.forward();
while (Motor.B.getTachoCount() < 90 && !stop) {
try{Thread.sleep(20);} catch (InterruptedException ex) {ex.printStackTrace();}
Mapperbot.sendCommand("S US "+sonic.getDistance()+" "+Motor.B.getTachoCount());
}
Motor.B.backward();
while (Motor.B.getTachoCount() > -90 && !stop) {
try{Thread.sleep(10);} catch (InterruptedException ex) {ex.printStackTrace();}
}
}
}
Motor.B.stop();
}
Which will then ensure that the loop contents and getDistanceInDirection never run simultaneously

Infinite while loop with break statement

I am a beginner and I was analyzing this java code:
// t is a thread running
while (true) {
try {
t.join();
} catch (InterruptedException e) { e.printStackTrace(); }
break;
}
t=null;
What I am asking is: is there a need to put that inside an infinite loop? Because as I see the loop will run only once i.e due to that break statement. I need some explanation please.
No, there's no need. Your observation is correct, the loop will be executed only once.
So the OP-posted code is equivalent to the following code.
// t is a thread running
try {
t.join();
} catch (InterruptedException e) { e.printStackTrace(); }
t=null;
Code posted by OP:
// t is a thread running
while (true) {
try {
t.join();
} catch (InterruptedException e) { e.printStackTrace(); }
break;
}
t=null;
As everyone has already pointed out, the code is incorrect as it stands.
The loop, however is necessary!
The correct code looks like this:
while (true) {
try {
t.join();
break;
} catch (InterruptedException e) { e.printStackTrace(); }
}
t = null;
Without the loop, it is possible for t to be set to null, before the current thread successfully joins it.
t.join(); waiting the finishing of thread.
After that, loop is broken by your "break".
=> always loop only 1 time => no need loop and break, only need t.join();
No need to have a while loop, because t.join() waits for the thread to die.
is like a loop already, in the program at the line of t.join() the program will be blocked while the thread is not dead.
The correct code is:
// t is a thread running
try {
t.join();
} catch (InterruptedException e) { e.printStackTrace(); }
t=null;
Here you have an example :
http://www.tutorialspoint.com/java/lang/thread_join.htm
Loop is not necessary!.
It is said that thread t is already started. Therefore it makes no sense "t=null". Thread t is already started and it will finish its job. You can use t.join() without while loop. In this context while loop does not make sense. The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread(main thread in below example) to pause execution until t's thread terminates.Run following code snippet and know the ropes.
public class Main {
public static void main(String[] args) {
Thread t=new Thread(
new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t = null; // no sense, t is already started
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"--Thread--"+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

thread stops unwantingly

I have a thread that is running and performing a task repeatedly. I've implemented a counter to show me the iterations of the task performed by the thread. Every now and then I see that the counter is stuck somewhere and it's not increasing anymore. I don't receive any error or exceptions. The application runs but it looks like the thread just stopped without me asking it.
I will add some code to show the thread execution:
notice the int "c" - thats the counter for iterations.
public void check() {
Thread check = new Thread() {
public void run() {
for (;;) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Update GUI here on EventQueue.
try {
Task.readTasks();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (NoteInfo == null || NoteInfo == "") {
btnViewNote.setEnabled(false);
} else {
btnViewNote.setEnabled(true);
}
textField.setText(Task.printNextTask);
c++;
lblCycle.setText("Cycle: " + c);
}
});
try {
Thread.sleep(5000);
// Task.initializeIt();
} catch (InterruptedException ie) {
break;
}
if (killcheck)
break;
}
}
};
check.start();
}
public static void stopChecking() {
killcheck = true;
progressBar.setValue(0);
textArea.setText("");
textField.setText("");
c = 0;
lblCycle.setText("Cycle: " + c);
}
The check thread gets interrupted by another thread. Print the stack trace in the catch block and verify it.
try {
Thread.sleep(5000);
// Task.initializeIt();
} catch (InterruptedException ie) {
// break; // just ignore it
}
I don't see the definitions of killcheck or c but it is possible that these have not been marked as volatile?
If multiple threads are reading and writing a shared value then there must be some sort of synchronization otherwise they could be dealing with stale values. You can either use one of the atomic classes such as AtomicBoolean or AtomicInteger, use the synchronized keyword, or mark the variable as volatile. All three would allow the main thread and the inner thread to see each other's changes to the shared fields.
volatile int c;
volatile boolean killcheck;
For posterity, here's how you use the atomic classes:
final AtomicInteger c = new AtomicInteger();
final AtomicBoolean killcheck = new AtomicBoolean();
...
c.incrementAndGet();
...
if (killcheck)
break;
...
killcheck.set(true);
...
c.set(0);

Time out method in java

In a java class I have a method that sometimes takes a long time for execution. Maybe it hangs in that method flow. What I want is if the method doesn't complete in specific time, the program should exit from that method and continue with the rest of flow.
Please let me know is there any way to handle this situation.
You must use threads in order to achieve this. Threads are not harmful :) Example below run a piece of code for 10 seconds and then ends it.
public class Test {
public static void main(String args[])
throws InterruptedException {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("0");
method();
}
});
thread.start();
long endTimeMillis = System.currentTimeMillis() + 10000;
while (thread.isAlive()) {
if (System.currentTimeMillis() > endTimeMillis) {
System.out.println("1");
break;
}
try {
System.out.println("2");
Thread.sleep(500);
}
catch (InterruptedException t) {}
}
}
static void method() {
long endTimeMillis = System.currentTimeMillis() + 10000;
while (true) {
// method logic
System.out.println("3");
if (System.currentTimeMillis() > endTimeMillis) {
// do some clean-up
System.out.println("4");
return;
}
}
}
}
Execute the method in a different thread, you can end a thread at anytime.
Based on the above snipplet, I tried creating a glorified spring bean.
Such executor runs the passed limitedRuntimeTask in limited runtimeInMs.
If the task finishes within its time limits, the caller continues normally in execution.
If the limitedRuntimeTask fails to finish in the defined runtimeInMs,
the caller will receive the thread execution back. If a timeBreachedTask was defined,
it will be executed before returning to caller.
public class LimitedRuntimeExecutorImpl {
public void runTaskInLessThanGivenMs(int runtimeInMs, final Callable limitedRuntimeTask, final Callable timeBreachedTask) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
LOGGER.info("Started limitedRuntimeTask");
limitedRuntimeTask.call();
LOGGER.info("Finished limitedRuntimeTask in time");
} catch (Exception e) {
LOGGER.error("LimitedRuntimeTask exception", e);
}
}
});
thread.start();
long endTimeMillis = System.currentTimeMillis() + runtimeInMs;
while (thread.isAlive()) {
if (System.currentTimeMillis() > endTimeMillis) {
LOGGER.warn("LmitedRuntimeTask did not finish in time (" + runtimeInMs + ")ms. It will run in vain.");
if(timeBreachedTask != null ){
try {
LOGGER.info("Executing timeBreachedTask");
timeBreachedTask.call();
LOGGER.info("Finished timeBreachedTask");
} catch (Exception e) {
LOGGER.error("timeBreachedTask exception", e);
}
}
return;
}
try {
Thread.sleep(10);
}
catch (InterruptedException t) {}
}
}
}
I feel the approach in accepted answer is a bit outdated. With Java8, it can be done much simpler.
Say, you have a method
MyResult conjureResult(String param) throws MyException { ... }
then you can do this (keep reading, this is just to show the approach):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws Exception {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
}
of course, throwing Exception is bad, here is the correct extended version with proper error processing, but I suggest you examine it carefully, your may want to do some things differently (logging, returning timeout in extended result etc.):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws MyException {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
try {
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
//something interrupted, probably your service is shutting down
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
//error happened while executing conjureResult() - handle it
if (e.getCause() instanceof MyException) {
throw (MyException)e.getCause();
} else {
throw new RuntimeException(e);
}
} catch (TimeoutException e) {
//timeout expired, you may want to do something else here
throw new RuntimeException(e);
}
}

Categories

Resources