Say I have the following test:
#Test(timeout = 1)
public void test(){
while(true){}
}
This simulates a test that would take a long time to return, not from sleeping, but from raw calculation time. How does the test exit? If I create a thread and try the same thing, it does not compile.
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
try {
while (true) {
}
} catch (InterruptedException e) {//Exception 'java.lang.InterruptedException' is never thrown in the corresponding try block'
e.printStackTrace();
}
}
};
thread.start();
thread.interrupt();
}
I can even attempt to replicate the implementation, but it still does not interrupt the thread:
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
try {
doTest();
} catch (InterruptedException throwable) {
System.out.println("interrupted");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
private void doTest() throws Throwable {
while (true) {
}
}
};
thread.start();
thread.interrupt();
}
The java.lang.Exception: test timed out after 1 milliseconds exception claims to be originating strait from the while loop when running the regular test.
I am confused as to how the test is 'interrupted', but I cannot do the same with a regular thread. How is this 'interrupting' feature implemented in JUnit?
The code tells you the truth: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java
Related
I was asked at an interview to write java code which is guaranteed deadlock. I wrote a standard code which presents at every Java book, like create 2 threads and call synchronized methods at different order, sleep a little before call the 2nd.
Of course this stuff didn't satisfy the interviewers, so now I'm proceeding to figure the solution out.
I discovered a piece of code:
public class Lock implements Runnable {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public void run() {
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
}
But I'm not sure if this code satisfied them? Sure. The code never ends execution, but is it a true deadlock? Aren't deadlocks about synchronization? And, for example, I can also write an endless cycle, put a Thread.sleep inside and name it a "deadlock".
So the question is: is it possible to write a classic deadlock using synchronized methods but 100% guaranteed? (Please don't tell me about very, very, very likely deadlock cases. I know it.)
Thanks.
Create two resources, and have each thread try to get one before releasing the other, but in different orders. For instance:
CountDownLatch a = new CountDownLatch (1);
CountDownLatch b = new CountDownLatch (1);
void one() throws InterruptedException {
a.await();
b.countDown();
}
void two() throws InterruptedException {
b.await();
a.countDown();
}
The thread that runs one can't release b, because it's waiting for a. It'll wait forever, because the thread that runs two can't release a because it's waiting for b.
One or the classic deadlock scenarios is when you acquire locks in reverse order.
class Resource1 {
synchronized static void method1() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
Resource2.method1();
}
}
class Resource2 {
synchronized static void method1() {
Resource1.method1();
}
}
public class MultiThreadApp {
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
Resource2.method1();
}
}).start();
Resource1.method1();
}
}
public class Deadlock {
public static void main(String[] args) {
String res1 = "a";
String res2 = "s";
new Thread(
() -> {
synchronized (res1) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res2) {
}
}
}
).start();
new Thread(
() -> {
synchronized (res2) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
}
synchronized (res1) {
}
}
}
).start();
}
}
I made a simple function to test interrupt() & InterruptedException in Java:
public static void main(String[] args) {
checkInterrupt();
}
private static void checkInterrupt() {
Runnable runMe = new Runnable() {
#Override
public void run() {
for(int i=0; i<6; i++) {
System.out.println("i = "+i);
if(i==3) {
System.out.println("i==3, Thread = "+Thread.currentThread().getId());
//I invoke interrupt() on the working thread.
Thread.currentThread().interrupt();
}
}
}
};
Thread workingThread = new Thread(runMe);
System.out.println("workingThread("+workingThread.getId()+") interrupted 1 ? "+workingThread.isInterrupted());
workingThread.start();
try {
workingThread.join();
} catch (InterruptedException e) {
//I thought I should get InterruptedException, but I didn't, why?
System.out.println("workingThread("+workingThread.getId()+") is interrupted.");
}
System.out.println("workingThread("+workingThread.getId()+") interrupted 2 ? "+workingThread.isInterrupted());
}
As you see above, in run(), I interrupt the working thread by invoking Thread.currentThread().interrupt() when i==3. I thought my code should catch InterruptedException during workingThread.join(). But there is no exception at all. Why?
You'll get an InterruptedException if the thread calling join is interrupted while waiting for the other one to die. That's not what happens in your case - you're interrupting the thread you're joining which is an entirely different matter.
You are interrupting the wrong thread. From the documentation of Thread.join():
InterruptedException - if any thread has interrupted the current thread.
You are interupting the thread that is being joined, not the thread that is doing the joining (referred to as current thread in the documentation).
Try this instead
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
public void run() {
while (true) {}
}
};
t.start();
Thread.currentThread().interrupt();
t.join();
}
Here is another variant, this time interrupting from the thread that is being joined.
public static void main(String[] args) throws InterruptedException {
final Thread mainThread = Thread.currentThread();
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(10000);
mainThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
t.join();
}
Where and how to implement addShutdownHook in a class, which have no main method? Can this used to kill all the active sockets initialized by that class?
This Might work for you,
public class AddShutdownHookSample {
public void attachShutDownHook(){
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Inside Add Shutdown Hook");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
And in main Method:
public static void main(String[] args) {
AddShutdownHookSample sample = new AddShutdownHookSample();
sample.attachShutDownHook();
System.out.println("Last instruction of Program....");
System.exit(0);
}
Describe whole thing that you are trying to do and show the very exact point where you are having trouble this would be easier for other to help you.
The following is an example, this may help you
public class RuntimeDemo {
// a class that extends thread that is to be called when program is exiting
static class Message extends Thread {
public void run() {
System.out.println("Bye.");
}
}
public static void main(String[] args) {
try {
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());
// print the state of the program
System.out.println("Program is starting...");
// cause thread to sleep for 3 seconds
System.out.println("Waiting for 3 seconds...");
Thread.sleep(3000);
// print that the program is closing
System.out.println("Program is closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Done like this...
static {
Runtime.getRuntime().addShutdownHook ( new Thread() {
public void run() {
server.shutdown();
}
} );
}
In the Java tutorial it says about try { ... } finally { ... }:
Note: 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.
Is it true that a thread can be interrupted or killed (I thought that was impossible?) such that the finally block will not be executed while the JVM running this thread is not exited/killed? (I am puzzled because the quote above is pretty explicit about this, not much room for misunderstanding.)
Edit: Broke the question down to its core intend.
Well, I stand corrected. It is possible by using deprecated methods:
#Test
public void testThread() throws Exception {
Thread thread = new Thread(new MyRunnable());
thread.start();
Thread.sleep(100);
thread.suspend();
Thread.sleep(2000);
}
class MyRunnable implements Runnable {
#Override
public void run() {
System.out.println("Start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Done");
}
}
}
Due to the pausing which will (most likely) occure while the thread is asleep, the finally block will never be executed.
Rafael, I believe this is one of the edge cases you are after. If a thread is blocked on something native (eg reading from STDIN or a Socket), and the JVM is in a state of shutdown, and the thread is interrupted, then finally may not be invoked.
The following example indicates this without invoking deprecated methods:
Sleep - finally is invoked.
SystemIn - finally is not invoked.
The example is very contrived, and is purely provided for demonstrative purposes :)
public class Interrupted {
static final List<Thread> THREADS = Arrays.asList(
new Thread(new Sleep()),
new Thread(new SystemIn())
);
static final CountDownLatch LATCH = new CountDownLatch(THREADS.size());
public static void main(String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));
for (Thread thread : THREADS) {
thread.start();
}
System.out.println("[main] Waiting for threads to start...");
LATCH.await();
System.out.println("[main] All started, time to exit");
System.exit(0);
}
static abstract class BlockingTask implements Runnable {
#Override
public void run() {
final String name = getClass().getSimpleName();
try {
LATCH.countDown();
System.out.printf("[%s] is about to block...%n",name);
blockingTask();
} catch (Throwable e) {
System.out.printf("[%s] ", name);
e.printStackTrace(System.out);
} finally {
System.out.printf("[%s] finally%n", name);
}
}
abstract void blockingTask() throws Throwable;
}
static class Sleep extends BlockingTask {
#Override
void blockingTask() throws Throwable {
Thread.sleep(60 * 60 * 1000); // 1 hour
}
}
static class SystemIn extends BlockingTask {
#Override
void blockingTask() throws Throwable {
System.in.read();
}
}
static class ShutdownHook implements Runnable {
#Override
public void run() {
System.out.println("[shutdown-hook] About to interrupt blocking tasks...");
for (Thread thread : THREADS) {
thread.interrupt();
}
System.out.println("[shutdown-hook] Interrupted");
try {
for (int i=0; i<10; i++) {
Thread.sleep(50L);
System.out.println("[shutdown-hook] Still exiting...");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have some problem with java.
for Example,
public class Test implements Runnable{
Thread thread;
public Test() throws Exception{
thread = new Thread(this);
thread.setName(getClass().getName() + thread.getId());
thread.start();
}
public void run() {
System.out.println("start");
try {
while(!thread.isInterrupted())
Thread.sleep(Long.MAX_VALUE);
}
catch(InterruptedException ie) {
System.out.println("interrupted");
}
System.out.println("stop");
}
public void stop() {
thread.interrupt();
}
}
this code now is infinite sleep status.
then, I find this thread by name in another Java code (something like this way - http://www.ehow.com/how_7467934_java-thread-runtime.html)
I casted "found thread" to Test class
Test test = (Test)Found Thread;
finally,
test.stop();
work!
I want to find and stop this thread in the other application (absolutely not same)
I`m not familiar with Java, also this like code way will not work in C++ or others as I know.
Is my code in sense? no problem? I worry about...
please advise me. thanx a lot.
(I`m not good at english. sorry)
There is no problem in your code! Everything is just perfect. You may omit checking interrupted status of thread in sleep loop, because once thread is interrupted, it will going to throw that exception when it tries to sleep or wait.
public class Test implements Runnable {
Thread thread;
public Test() throws Exception {
thread = new Thread(this);
thread.setName(getClass().getName() + thread.getId());
thread.start();
}
public void run() {
System.out.println("start");
try {
while (true) {
Thread.sleep(Long.MAX_VALUE);
}
} catch (InterruptedException ie) {
System.out.println("interrupted");
}
System.out.println("stop");
}
public void stop() {
thread.interrupt();
}
public static void main(String [] args) throws Exception{
Test t = new Test();
t.stop();
}
}