Thread Interruptded Exception, release semaphore resources - java

I have three threads and they need some resources to run (A,B,C) that I have implemented using Semaphores.
public void run(){
while(!Thread.currentThread().isInterrupted){
try{
A.acquire(2);
B.acquire(2);
//some-stuff
}
catch(InterruptedException ex){}
finally{
A.release(2); //PROBLEM
B.release(2);
}
}
Problem: while running, the thread could be interrupted but, going in the finally method I don't know where I was during the interruption so I don't know if I have to release something or not.
I have tried a lot of different implementation, like using the method (boolean) tryAcquire() but another problem comes up: if I get the resource A but not the B, then in the finally block I would release the A again etc.
Do you have any suggestions? Thank you.

Use nested try blocks:
try {
A.acquire(2);
try {
B.acquire(2);
try {
// some stuff
} finally {
B.release(2);
}
} finally {
A.release(2);
}
} catch (InterruptedException ex) {}

You could try to use List like this:
List<Semaphore> acquired = new ArrayList<>(2);
while(!Thread.currentThread().isInterrupted) {
try{
A.acquire(2);
acquired.add(A);
B.acquire(2);
acquired.add(B);
//some-stuff
} catch(InterruptedException ex){}
finally{
for (Semaphore s : acquired) {
s.release(2);
}
s.clear();
}
}

Related

calling catch block from a method when an exception occured in try block

Is it any possible way there to write catch block inside a method and call it from finally when an exception occured in try block
Ex:
try
{
int a=0,b=0;
a=b/0;
}
finally
{
callExceptions();
}
}
public static void callExceptions()
{
catch(Exception e)
{
System.out.println(e);
}
}
catch block must follow a try block. It can't stand alone.
And finally block are made to be after the catch.
You wrote an alone catch inside a finally. That doesn't make sense.
The easiest solution is to pass the exception to the method as a parameter:
public static myMethod() {
try
{
int a=0,b=0;
a=b/0;
}
catch (Exception e)
{
callExceptions(e);
}
finally
{
// do what ever you want or remove this block
}
}
public static void callExceptions(Exception e)
{
System.out.println(e);
}
Ways to uses try/catch/finally
1.- when you want to try to use some method, if everything goes well, will continue else one exception will be thrown on catch block.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
}
2.- It's the same the first but adding finally block means that the finally block will always be executed independently if some unexpected exception occurs.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
} finally {
// some logic after try or catch blocks.
}
3.- try and finally blocks are used to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. For example:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Referencias Official documentation JAVA for try/catch/finally blocks
On your case:
public static myMethod() {
try {
int a=0,b=0;
a=b/0;
} catch (Exception e) {
callException(e);
}
}
public static void callException(Exception e) {
System.out.println(e);
}
This was too long for a comment so sorry it's not a direct answer to your question (as others have pointed out, that's not possible). Assuming what you're trying to do is define a common way to handle your exception logic in one place, Callable might be a way to go. Something like the following might suffice... Although I'm not going to comment on whether any of it is a good idea...
static E callAndHandle(final Callable<E> callable) {
try {
return callable.call();
} catch (final Exception ex) {
System.out.println(ex);
return null;
}
}
static void tryIt() {
final String result = callAndHandle(() -> {
// Thing which might throw an Exception
return "ok";
});
// result == null => there was an error here...
}
Unfortunately Runnable doesn't declare any Exception in the signature, so if you know it always needs to be void and you don't like the return null; or similar hacks, you'd have to define your own interface to pass in.

How to stop a running Thread in Java

I am using a Java based file conversion tool which converts PDF to DOCX, but sometimes while conversion it stuck, if input file size is more then 1 MB and start utilizing 100% CPU and more memory and keep running. I want to stop this continuous thread.
I know stop() function is deprecated.
Calling thread.interrupt(); is not helping, since thread is keep running.
There is no loop in the code ...so cannot check for interrupted flag in loop
How to Stop a running Thread t.
public class ThreadDemo implements Runnable {
Thread t;
PdfToDocConversion objPdfToDocConversion;
ThreadDemo() throws InterruptedException {
t = new Thread(this);
System.out.println("Executing " + t.getName());
// this will call run() fucntion
t.start();
Thread.sleep(2000);
// interrupt the threads
if (!t.interrupted()) {
System.out.println("Interrupted");
t.interrupt();
}
System.out.println(t.isInterrupted()); // true
System.out.println(t.getName());
System.out.println(t.isAlive()); /// still true
// block until other threads finish
try {
t.join();
} catch (InterruptedException e) {
}
}
public void run() {
objPdfToDocConversion = new PdfToDocConversion();
try {
objPdfToDocConversion.convertDocToPdf();//inside this function thread got stuck
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.print(t.getName() + " interrupted:");
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
try {
new ThreadDemo();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You can build your own logic in killing the thread by the help of boolean flag.
public class RunningThread implements Thread {
private volatile boolean running = true;
public void run() {
while (running) {
try {
// Add your code here
} catch (InterruptedException e) {
if(!running){
break;
}
}
}
}
public void stopThread() {
running = false;
interrupt();
}
}
Here is the usecase:
RunningThread thread = new RunningThread();
thread.start(); // start the thread
thread.stopThread(); // stops the thread
The approach above is originally used by Google developers in on of there framework a.k.a Volley library.
Thread.interrupt() only sets a flag within the Thread object that the Thread should be interrupted. It does not cause the target Thread to throw an InterruptedException, instead code that can be interrupted must continually check that flag to see if someone has requested it be interrupted. That code then must handle it, usually by throwing an InterruptedException.
Some of the answers say about stopping the loop with volatile boolean isRunning but I do not see any loop in your example. Interrupting the thread does not actually interrupt it "right now". It just says "thread will be interrupted as soon as there will be such an opportunity". In your case I would suggest to close your PDF file and flag it with some boolean - then you can catch the IOException and if the flag is set - it means that you caused this situation and you can finish the thread.

Ping a server without freezing the Thread

I tried to use multiple threads, sadly no luck:
public synchronized boolean pingServer(final String ip, final short port) {
final boolean[] returnbol = new boolean[1];
Thread tt = new Thread(new Runnable() {
#Override
public void run() {
try {
Socket s = new Socket(ip, port);
s.close();
returnbol[0] = true;
} catch (IOException e) {
returnbol[0] = false;
}
}
});
tt.start();
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
tt.stop();
return returnbol[0];
}
The main thread still Freezes for some reason.
Is there a "lagless" way to ping a server?
What exactly did you want to got in
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
block?
Here you joined to parallel thread and waits till this thread will ends (got ping result).
You have next options:
Wait till ping ends
Don't wait... and don't got result
Use some concurrency classes like Future<> to got result (but you will block thread at moment you ask result if it not retrieved yet)
Or you can use some 'callback' function/interface to threw result from inner 'ping' thread.
You will need to remove the following lines from your code.
The tt.join() will force the main thread to wait for tt to finish.
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
tt.stop();
Use a Future instead to get the result for later use

Perform an action after interrupting a thread

I have two threads, threadOne waits for user input, threadTwo interrupts it with an interrupt() method before user input is received .
I would like to execute a block of code upon successful interruption of threadOne. I tried doing that by catching a ClosedByInterruptException within threadOne's run() method, but the compiler gives the following error:
exception ClosedByInterruptException has already been caught.
Here's the code:
class InputInterruption {
public static void main(String[] args) {
final Thread t2 = new Thread() {
public void run() {
try {
System.out.print("make a selection: ");
String userInput = (new BufferedReader(new InputStreamReader(System.in))).readLine();
System.out.println(String.format("user input: %s", userInput));
} catch (IOException e) {
System.out.println("Oops..somethign went wrong.");
System.exit(1);
} catch(ClosedByInterruptException e) {
System.out.println("Successfully interrupted");
}
}
};
t2.start();
Thread t1 = new Thread() {
public void run() {
try {
sleep(1000);
System.out.println("interrupting InputStreamReader");
t2.interrupt();
System.exit(0);
} catch (InterruptedException e) {
System.out.println("Successfully interrupted");
}
}
};
t1.start();
}
}
ClosedByInterruptionException extends IOException. Try switching the order of your catch statements.
ClosedByInterruptException is a subclass of IOException so your first catch block intercepts all IOException instances including ClosedByInterruptException.
Change the order of catch blocks and you are good.
To wait for a thread to complete, you could use Thread.join(). Change your t1 code to the following:
....
t2.interrupt();
t2.join();
....
Disclaimer: I haven't tried this code myself.
ClosedByInterruptException is actually sub class of IOException. So even if the try block throws ClosedByInterruptException it will be caught by the first catch block with statement:
catch (IOException e). Change the order and you should be good to go.
I tried doing that by catching a ClosedByInterruptException within threadOne's run() method...
Other's have solved the exception compilation error but I do not see any methods that actually throw ClosedByInterruptException so I'm surprised your code compiles. Your code does not compile for me in Eclipse for that reason. Maybe your IDE is not making the unthrown exception an error -- I'd recommend turning on that error/warning. ClosedByInterruptException is only thrown by certain NIO channels that implement InterruptibleChannel.
If you are reading from a normal stream, the only way to stop the thread from reading is to close the underlying stream. In this case you could try to close System.in but that may not actually stop the thread from reading unfortunately. On OS X, closing System.in causes the readLine() method to return null in the reader thread. You then can continue and execute some sort of code block as necessary.
sleep(1000);
System.out.println("closing InputStreamReader");
System.in.close();
Then you can do:
String userInput =
new BufferedReader(new InputStreamReader(System.in)).readLine();
if (userInput == null) {
// stream was closed, do something special
...
Btw, in the interrupting code you have:
try {
sleep(1000);
t2.interrupt();
} catch (InterruptedException e) {
System.out.println("Successfully interrupted");
}
The output message there is misleading. If sleep(...) throws a InterruptedException then it was the thread that was sleeping that was interrupted. It has nothing to do with the t2.interrupt() call. Just FYI.

Java: I have try,catch and finally in a java code and I want after try or catch block finally does not execute

I have following code
public class TEST
{
public static void main(String arg[]){
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
}
catch (Exception e){
System.out.println(e);
}
finally{
System.out.println("execute finally");
}
}
}
what should I write in try or catch block that finally does not run. any idea?
System.exit(0);
If you want something not to run in the "finally" block - do not put it in "finally". Finally runs always (well, except for a few cases like others have mentioned).
You need to shutdown the JVM by calling exit as:
System.exit(exit_status);
From the Java docs:
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
finally is meant to execute regardless of whether the exception occurs, period.
It can't be avoided except by resorting to dubious tactics ( as Joachim said up there ).
If the code you have in the finally block is not meant to be executed every time, don't use a finally construct; Use a simple if-construct instead
public class TEST
{
public static void main(String arg[]){
bool exitFinally = false;
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
}
catch (Exception e){
System.out.println(e);
}
finally{
if(exitFinally)
return;
System.out.println("execute finally");
}
}
}
Put the code in finally into an if.
public class TEST
{
public static void main(String arg[]){
boolean b = true;
try
{
System.out.println("execute try");
if (something()) b = false;
}
catch (Exception e){
System.out.println(e);
}
finally{
if (b){
System.out.println("execute finally");
}
}
}
}
Use boolean flag:
public class TEST
{
public static void main(String arg[]){
boolean success=false;
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
success=true;
}
catch (Exception e){
System.out.println(e);
}
finally{
if (!success)
{
System.out.println("execute finally");
}
}
}
}

Categories