Implementation of addShutdownHook - java

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

Related

How are timeouts handled in JUnit?

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

Java - is it possible to find thread with name and cast it to class?

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

Trying to stop thread, but it start again

Hi I'm using the next code to try to stop a thread, but when I see that Running is false it becomes true again.
public class usoos {
public static void main(String[] args) throws Exception {
start();
Thread.sleep(10000);
end();
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(){
System.out.println("finished.");
start().shutdown();
}
}
And the thread
public class SimpleThreads extends Thread {
volatile boolean running = true;
public SimpleThreads () {
}
public void run() {
while (running){
System.out.println("Running = " + running);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread" + "======Running = " + running);
}
public void shutdown(){
running = false;
System.out.println("End" );
}
}
The problem is that when I try to stop it(I set running to false), it starts again..
Look at this line in the end method:
start().shutdown();
You are not stopping the original instance; you are starting another one, which you then immediately shut down.
There is no connection between your start and end methods—no information, no reference is passed from one to the other. It is obviously impossible to stop the thread you started in the start method.
Your end method should not be static; in fact, you don't even need it, shutdown is already it:
SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();
Because in the end method you just create a new Thread and kill it, save the thread instance and kill it:
Your code should look something like this:
public class usoos {
public static void main(String[] args) throws Exception {
SimpleThreads id = start();
Thread.sleep(10000);
end(id);
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(SimpleThreads id){
System.out.println("finished.");
id.shutdown();
}

How do I implement thread wait notify in this case?

I have 2 classes. One method of the class calls the other class' method, but it has to wait until the method finishes to proceed to the execution of the rest of the code.
This is a rough code of what I'm trying to make. And I know this doesn't work.
public class Example
{
Thread thread;
public Example(Thread thread)
{
this.thread = thread;
}
public void doSomethingElse()
{
System.out.println("Do something else");
thread.notify();
}
}
public class Example2
{
Thread thread;
Example example;
public Example2()
{
example = new Example(thread);
thread = new Thread()
{
public void run()
{
example.doSomethingElse();
try {
this.wait();
} catch (InterruptedException ex) {
}
System.out.println("Do something");
}
};
}
public void doSomething()
{
thread.run();
}
}
Now do you know how to make this right?
Not sure if your constrained to using this particular approach (wait/notify) however a better approach is taking advantage of the Java Concurrency API
public class ExampleCountDownLatch
{
public void doSomething () throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread()
{
public void run ()
{
System.out.println("do something");
latch.countDown();
}
};
System.out.println("waiting for execution of method in your example class");
thread.start();
// wait for reasonable time otherwise kill off the process cause it took
// too long.
latch.await(3000, TimeUnit.MILLISECONDS);
// now I can do something from your example 2
System.out.println("now i can execute from example 2 do something else");
}
}
Anyway just another approach if you had an option.
UPDATE:
Here is a blog about this very topic.
Couple of points :
you should acquire lock before calling wait or notify method. The
lock must be on same object. In code you are calling wait on example2
object but calling notify on different object.
thread.run() means calling run method of thread object, its not
creating new thread its same as example.doSomething(). When you
create thread start that thread by calling start method.
Here is my implementation
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
synchronized(this){
System.out.println("Do something else");
try{
Thread.sleep(1000);
this.notify();
}catch (InterruptedException ignore) {}
}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
doSomething();
}
public void doSomething(){
synchronized(example){
System.out.println("waiting for example 1 to complete");
try{
example.wait();
}catch (InterruptedException ignore) {}
}
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
Thread t2 = new Thread(example);
t2.start();
}
}
In code Thread.sleep(1000); statement is not needed.
Here is one more implementation using join method
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
System.out.println("Do something else");
try{
Thread.sleep(1000);
}catch (InterruptedException ignore) {}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
System.out.println("waiting for example 1 to complete");
Thread t = new Thread(example);
try{
t.start();
t.join();
}catch(InterruptedException ie){
}
doSomething();
}
public void doSomething(){
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
}
}

Thread Dependency Java

I have a main class which spawns a thread, let's call them MainClass and MyThread.
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
#Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
The problem is I do not know how to implement the while condition which checks if the MainClass instance is still alive and if it is, it has to use the this.main_class.getSharedVariable() to get the value of sharedVariable, then wait for x amount of time. MainClass has the main method .
I would recommend holding onto the Thread instance and then calling threadInstance.interrupt() right before the main(...) method exits.
Something like:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
Then in your thread you'd do:
while(!Thread.currentThread().isInterrupted()){
...
}
You'd also want to handle InterruptedException correctly:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
Btw, it is very bad form to leak the instance of an object during construction to another thread:
new MyThread(this);
See here: Why shouldn't I use Thread.start() in the constructor of my class?
Also, you aren't starting a thread when you call threadInstance.run();. You are just running it in the current thread. You should use threadInstance.start() but not inside of the constructor like that.
You can use CountDownLatch which is very convenient for such tasks as waiting other threads to finish some activity (you can change Thread.sleep(...) argument in main to, say, 12000L and see what happens):
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class OtherThread extends Thread {
private final CountDownLatch sharedLatch;
OtherThread(CountDownLatch sharedLatch) {
this.sharedLatch = sharedLatch;
}
#Override
public void run() {
boolean wokenByMain = false;
try {
wokenByMain = sharedLatch.await(10000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
return; // or not return, whatever makes more sense in your case
}
System.out.println("heh: " + wokenByMain);
}
}
class SOSample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
OtherThread otherThread = new OtherThread(latch);
otherThread.start();
System.out.println("Scheduled other thread to be started");
Thread.sleep(1000L);
System.out.println("going to release other thread");
latch.countDown();
}
}
public class MainClass extends JFrame implements Runnable {
public static void main(String [] args) {
final Thread t=new Thread(new MainClass() {
public void run(){
//something
});
Thread t2=new Thread(new MyThread() {
public void run() {
while(t.isAlive) {
//something
}
}
});
}
}

Categories