Avatar of Yogeshup
Yogeshup asked on

Facing a problem while killing thread from java [JDK 1.6, JDK1.4]

Hi All,
I am facing a problem while killing thread from java [JDK 1.6, JDK1.4] running on windows. Here is my flow, I have three class;
Server Class :- Listens request broadcasted by source system,
Parent Class :- Holds the logic for creating thread class.
Child Class :- Holds the logic doing some  stuff related to business logic involves db operations[Eg.Proc execution].
I have a created a listener in java which will act as a server and will keeps on listening the request broadcasted. After getting the request it creates the object of parent class. Parent class creates the thread [child class object] which does some operation. Parent class is basically used for terminating thread [child class object] after specified timeout period. In parent class, after completion of specified time it interrupts the created thread by using .interrupt() method. But since this is just the Boolean flag it shows me correct flag if check thread status by using .isInterrupted() but in real scenario it doesnt stops the execution. I cached the interrupted thread as follows
catch (InterruptedException  iex){
      Thread.currentThread().interrupt();
      iex.printStackTrace();}
It doesnt seems to work. I know that there is a limitation with threads in java but I tried lots of alternatives like,
1. I used .isInterrupted() method and by using system.exit() I terminated the thread but it shut downs my server class execution also which should not.
2. Thread terminates only after completion of its run method hence I tried to maintain the variable which will hold the Boolean value and in while block I checked it every time.
    public class Child extends Thread {
    public Child() {
        // put constructor stuff here!
    }
    public void run () {
        //do something
        if (isStopped) return;
    }
}
 Since this could not work in my case because in run method hold some business logic related to database hence it keeps on executing and keeps holding all it's locks and its references.
Any suggestions are highly appreciable
Thanks in advance.
Java

Avatar of undefined
Last Comment
Computer101

8/22/2022 - Mon
CEHJ

Can we see the actual thread close please?
Mick Barry

>  but in real scenario it doesnt stops the execution

Its not meant to. Its up to you to check for an interruption and handle it appropriately.
Also some operations (ie. calls you make from your thread) may not be interruptable.

Mick Barry

1. I used .isInterrupted() method and by using system.exit() I terminated the thread but it shut downs my server class execution also which should not.

you should be calling exit(). You should be instead doing any cleanup worlk required, and then exit the run() method.

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
Yogeshup

Thanks for your replay objects,
In run method of my thread class i am calling the package of oracle. Here once it goes into the oracle package till completion i can not do anything hence my parent thread does this to terminate thread class.
Here is the code sample,
The problem is that it never comes into catch block of InterruptedException  
//package Listner;
final class Server {
	public static void main(String[] args) throws Exception{
		System.out.println("Please wait starting server....");
		System.out.println("Server started");
		Server _objServer = new Server();
 		_objServer.ReadData();
	}
	private void ReadData() throws Exception
		{
		Parent _ObjParent;
		for(int i=0;i<=5;i++){			
                     
                     //Temp loop for fetching five requests
		     System.out.println("Listning to client....");
		     //Step 1  Recive the request from source.
 
		     //Step 2 Start the process.
		     _ObjParent = new Parent();
	 	     _ObjParent.Invoke();
				
		     //Step 3 Send response.
		}
	}
}
 
 
---------------- Class Parent 
//package Listner;
 
public class Parent implements Runnable
{
 Thread MainThread;
 public static boolean Finished = false;
 public Parent(){
}//  Creates a new instance of Main 
 
 public void run() 
 {   
    Child ChildThreadObj = new Child();
    Thread procThread = new Thread(ChildThreadObj);                             
    procThread.start();									      
    try 
    {
	synchronized (ChildThreadObj)
         {
	     ChildThreadObj.wait(2000);				
/* Wait for 20 (20000 msec) seconds and then interrupt. Will force to go in catch block of ProcedureThread run method where the method returns */
	     procThread.interrupt();                                   		             Finished = true;	
	     if (Child.checkFlag.equalsIgnoreCase("Y")){
                   //Do nothing
	     }else if (Child.checkFlag.equalsIgnoreCase("N")){
		   if (procThread.isInterrupted()){
    	               procThread.currentThread().interrupt();
	               //System.exit(0);
                   }else
		      throw new Exception(Child.errorMsg);			
             }else
		   throw new Exception("Invalid checking flag found!");
/*Force exit becuase Written because thread was waiting on object which is waiting for colmplition of object. */
           }	 
	}catch (InterruptedException iex){
		iex.printStackTrace();
	}catch(Throwable t){
		t.printStackTrace();
        }
}
 
 public static void main(String[] args) throws Exception{
 }
 public static void Invoke() throws Exception{
   Parent m = new Parent();
   m.MainThread = new Thread(new Parent()); 
   m.MainThread.start();							   // To start the parent thread which will call procedure ka thread
  }
}
		
		
--------------------- Class Child 
//package Listner;
public class Child implements Runnable{
 
    public static String checkFlag = "N";					    public static String errorMsg ="";					
    public Child(){
    }  																			
    public void run() {
    try {
        Parent _ObjParent = new Parent();
    	     while(_ObjParent.Finished=true){
		System.out.println("Test");
		Thread.sleep(0);
	     }
	checkFlag = "Y";							        errorMsg  = "";
	
	}catch (InterruptedException  iex){
	     Thread.currentThread().interrupt();
	     errorMsg= "Process is terminated" + iex;
             checkFlag="N";
             return;
        }catch (Exception e){
	     errorMsg = "[Child class]: "+ e;
             checkFlag="N";
	     return;
        }finally{
	    synchronized(this){								        //Notify to parent class that transaction is succesful.
                this.notifyAll();
	    }
        } 
    }
}

Open in new window

CEHJ

Mick Barry

> . Here once it goes into the oracle package till completion i can not do anything hence my parent thread does this to terminate thread class.

Just set a flag and exit the thread once it returns from oracle.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Yogeshup

Thanks for your suggestion objects,
Assume that oracle package took 10 min to complete its execution due to some interruption. Here I don't want to keep on waiting till the package completes its execution hence i used threading for that.
As i have already written in question that i tried this alternative but since its line by line execution i can set the flag = True[Thread terminated] only after complete execution of oracle pkg.
Hence this solution doesn't satisfy my requirements. I hope u r understanding my problem???

Thanks in advance

CEHJ

>>Here I don't want to keep on waiting till the package completes its execution hence i used threading for that.

That's why i made that suggestion
Mick Barry

> As i have already written in question that i tried this alternative but since its line by line execution i can set the flag = True[Thread terminated] only after complete execution of oracle pkg.

No, you can set it from a different thread at any time such that when the call returns from oracle it can check the flag and return.

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER
Yogeshup

Hi Objects,
Still your are not getting my question may be because of terminology but,
what i am trying to explain you is that, if you set the flag from different thread even then also in while loop it will check for the value only after successful/complete execution of the database pkg or if i removed the while loop it will only exit after the same. I want to interrupt in between the execution of databse pkg. The code snippet which i have already attached, if you see there i am setting flag from parent thread not from the child class thread.
Or even in child thread class i may not required the while loop because i want to execute pkg only once hence once thread run() method gets executed it will call my database package.
My parent thread will calculate the time and after timeout it will interrupt the thread and will set the flag = true.Here thread who is executing database pkg will not came to know that parent has already interrupted the chid thread.
Mick Barry

> I want to interrupt in between the execution of databse pkg.

you can't, but you shouldn't need to.
Once the flag has been set, any other threads that are waiting on execution of the db thread to complete can stop waiting. They don't need to wait until the thread finishes.
One way of implementing this is to add listener support to your thread such that it calls any listeners when it either completes or times out.

http://exampledepot.com/egs/java.util/CustEvent.html

If you don't need notification then that may not be necessary.

ASKER
Yogeshup

Hi,
I agreed whatever you said but, since my problem is that,
My java method [in current scenario its Run() method] is busy in executing oracle pkg. How can use listeners in this scenario.
When i said execute procedure from java by using callable statement it will wait their until and unless oracle finishes its execution. Now assume that by using different thread if i set the flag or i call the listner even then also that thread is still executing the procedure because oracle doesnt releases its resources and locks. Now to achieve this if i need to kill the oracle session then i would have directly done that by using oracle session kill but its does not seems feasible.  
What i want is that when i said thread.intrrupt from my parent class child thread should stop its executing and should return safely to my parent class. Java is doing it properly he says that thread is intrrupted by using isInterrupted() but in actual scenario it doesnt stop the execution.
 
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Mick Barry

you can't interrupt the oracle call, but should not be a problem (other than any locks which you can't do much about)

ASKER
Yogeshup

Thanks objects!
ASKER
Yogeshup

Hi Objects,
I resolved the issue by using java callablestatement.cancel() method. This method interrupts procedure execution. Here thread gets interrupted due to database call gets terminated.

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Mick Barry

good work :)

ASKER CERTIFIED SOLUTION
Computer101

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question