[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

How Do i kil a thread

This is similar to a question I asked earlier. Thanks to the folks who asnwered that one. Here's a straight forward app. my questions are in the comments below
-jbd


import java.util.*;

public class tester {
   
     public static void main (String[] args) {
        new tester().tester1();
     }  
       
       public void tester1 () {
            try{
                Thread thread1 = new ReadThread(i);
                    Thread thread2 = new ReadThread(i+1);
                    thread1.join();
                    thread2.join();
               
                //----1-----
// I need to figure out how to kill a thread that 'hangs'.
//basically, something is happening in readThread that is causing it to keep living.
// i'm sure the best practice would be to figure out what that is, and fix it
///but it's a really long chunk of code that parses files, and I can't prepare for every eventuality (although I am catching errors)
//[i think the error is occuring while running a mysql load because when i try to delete the load text file, i'm told another process is using it.
// so i need to force the thread to give up, leave that file alone and die. die thread die.]
//
//Do i need to add the thread.interrupt() to my catch clauses?
           

               
           } catch (Exception ex) {
                   System.out.println(ex);
                   ex.printStackTrace();
           }
       }
       
       static class ReadThread extends Thread {
           public int thisThreadNum;
                     
           ReadThread(){
                start();
            }

            public void run() {
               
              ///here's where the error is happening

           
            }
       }
}
0
jacobbdrew
Asked:
jacobbdrew
  • 10
  • 5
1 Solution
 
jacobbdrewAuthor Commented:
note-- I just figure out that I'm running out of memory. I get a java.lang.outOfMemory error--

this is strange to me because I'm running limiting the number of threads running at one time (thus the join()s, which, as I undestand it, force the app to wait)
do I need to force a thread to drop the memory it's occupying after it dies? shouldn't that happend automatically?

-jbd
0
 
ksivananthCommented:
is that the OOM desc is "unable to create native threads"?, then you r running out of threads. There is a limitation in creating threads per process in OS, it varies between os's and jdk versions. you may have to implement something like thread pool!

if the join method hangs indefenitely, then you can pass time val for the join method so that it not waits more than that time.

thread.join( timeInMiliSecs ) ;
0
 
ksivananthCommented:
you cant kill a thread but there are mechanism to terminate the thread execution like returning from run method based on some flag...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
ksivananthCommented:
what do u mean thread die?
0
 
jacobbdrewAuthor Commented:
so I was trying to limit the number of threads I was using so that I didn't run into this problem. but I guess this isn't working. essentially, i'm' looping over a directory full of text files, then starting a thread for each one to parse the text files (some directories have over a thousand files), but I'm trying to limit the number of started threads to ten... here's my code:

File[] aryLogDirFiles = fLogDir.listFiles();
           int z = aryLogDirFiles.length;
           int intLogNum;
           Thread reader1 = new Thread();
           Thread reader2 = new Thread();
           Thread reader3 = new Thread();
           Thread reader4 = new Thread();
           Thread reader5 = new Thread();
           Thread reader6 = new Thread();
           Thread reader7 = new Thread();
           Thread reader8 = new Thread();
           Thread reader9 = new Thread();
           Thread reader10 = new Thread();
           for (int i=0; i<z; i=i+10){
                sNowFile1 = aryLogDirFiles[i].toString();
                intLogNum = 1;
                reader1 = new ReadThread(sNowFile1, intLogNum);
                if ((i+1)<z){
                    sNowFile2 = aryLogDirFiles[i+1].toString();
                    intLogNum = 2;
                    reader2 =  new ReadThread(sNowFile2, intLogNum);
                }
                if ((i+2)<z){
                    sNowFile3 = aryLogDirFiles[i+2].toString();
                    intLogNum = 3;
                    reader3 = new ReadThread(sNowFile3, intLogNum);
                }
                if ((i+3)<z){
                    sNowFile4 = aryLogDirFiles[i+3].toString();
                    intLogNum = 4;
                    reader4 = new ReadThread(sNowFile4, intLogNum);
                }
                if ((i+4)<z){
                    sNowFile5 = aryLogDirFiles[i+4].toString();
                    intLogNum = 5;
                    reader5 = new ReadThread(sNowFile5, intLogNum);
                }
                if ((i+5)<z){
                    sNowFile6 = aryLogDirFiles[i+5].toString();
                    intLogNum = 6;
                    reader6 = new ReadThread(sNowFile6, intLogNum);
                }
                if ((i+6)<z){
                    sNowFile7 = aryLogDirFiles[i+6].toString();
                    intLogNum = 7;
                    reader7 = new ReadThread(sNowFile7, intLogNum);
                }
                if ((i+7)<z){
                    sNowFile8 = aryLogDirFiles[i+7].toString();
                    intLogNum = 8;
                    reader8 = new ReadThread(sNowFile8, intLogNum);
                }
                if ((i+8)<z){
                    sNowFile9 = aryLogDirFiles[i+8].toString();
                    intLogNum = 9;
                    reader9 = new ReadThread(sNowFile9, intLogNum);
                }
                 if ((i+9)<z){
                    sNowFile10 = aryLogDirFiles[i+9].toString();
                    intLogNum = 10;
                    reader10 = new ReadThread(sNowFile10, intLogNum);
                }

                    reader1.join();
                    reader2.join();
                    reader3.join();
                    reader4.join();
                    reader5.join();
                    reader6.join();
                    reader7.join();
                    reader8.join();
                    reader9.join();
                    reader10.join();
                 //shouldn't these force the app to wait until the thread is dead before starting another?

           }

0
 
ksivananthCommented:
No the code is wrong here, let me correct it!
0
 
ksivananthCommented:
the below block is not required,

>>Thread reader1 = new Thread();
           Thread reader2 = new Thread();
           Thread reader3 = new Thread();
           Thread reader4 = new Thread();
           Thread reader5 = new Thread();
           Thread reader6 = new Thread();
           Thread reader7 = new Thread();
           Thread reader8 = new Thread();
           Thread reader9 = new Thread();
           Thread reader10 = new Thread();
>>

Thread reader2 = new ReadThread(...) inside the loop is enough
0
 
ksivananthCommented:
the problem in your code is, even if one thread takes much time to complete all the other threads also has to wait that much time

So creating worker threads and maintaining a pool will help here
0
 
jacobbdrewAuthor Commented:
will that limit the number of threads created at one time, or do I need a thread pool? (which I know nothing about)
0
 
jacobbdrewAuthor Commented:
how do you create worker threads and a pool?

0
 
ksivananthCommented:
please wait for some time to give u some sample
0
 
jacobbdrewAuthor Commented:
this looks decent, but it was written in 2001. not sure I should spend the time checking it our. what do you think?
http://www.informit.com/articles/article.asp?p=30483&seqNum=5
0
 
ksivananthCommented:
Hi I am ready, here is the complete example,

import java.util.Vector;
import java.io.File;

public class TestThreadPool{

    public static void main( String arg[] ){
        ThreadPool threadPool = new ThreadPool( 10 ) ;

        for( int i = 0; i < 100; i++ ){
            MyTask task = new MyTask( null ) ;
            WorkerThread thread = threadPool.getWorkerThread() ;
            thread.addTask( task );
        }
    }
}

class ThreadPool{
    private Vector free ;
    private Vector used ;
    private int poolSize ;

    ThreadPool( int poolSize ){
        free = new Vector( poolSize ) ;
        used = new Vector( poolSize ) ;
        this.poolSize = poolSize ;
    }

    public WorkerThread getWorkerThread(){
        WorkerThread thread = null ;
        synchronized( free ){
            while( thread == null ){
                if( ! free.isEmpty() ){
                    thread = ( WorkerThread )free.elementAt( 0 ) ;
                    free.removeElementAt( 0 );
                }else if( used.size() < poolSize ){
                    thread = new WorkerThread( this, "WT-" + ( used.size() - 1 ) ) ;
                    thread.start();
                }

                if( thread == null ){
                    System.out.println( "Worker is not available - waiting!" ) ;
                    try{ free.wait(); }catch( InterruptedException ie ){}
                }
            }

            addToUsedPool( thread ) ;
        }

        return thread ;
    }

    public void releaseWorkerThread( WorkerThread thread ){
        synchronized( free ){
            free.addElement( thread );
            removeFromUsedPool( thread ) ;
            free.notify();
        }
    }

    private void addToUsedPool( WorkerThread thread ){
        used.addElement( thread );
    }

    private void removeFromUsedPool( WorkerThread thread ){
        used.removeElement( thread ) ;
    }
}

class WorkerThread extends Thread{
    ThreadPool pool ;
    MyTask task ;
    boolean shutdown ;

    WorkerThread( ThreadPool pool, String name ){
        this.pool = pool ;
    }

    public synchronized void run(){
        while( ! shutdown ){
            if( task != null ) task.execute();

            pool.releaseWorkerThread( this );
            try{ wait() ; }catch( InterruptedException ie ){}
        }
    }

    public synchronized void addTask( MyTask task ){
        this.task = task ;
        notify() ;
    }

    public synchronized void shutdownMe(){
        shutdown = true ;
        notify() ;
    }
}

class MyTask{

    private File read ;

    MyTask( File file ){
        read = file ;
    }

    public void execute(){
        for( int i = 0; i < 100; i++ ){
            System.out.println( Thread.currentThread().getName() +
                    "Hey, here I have to do the file read job :) " + i ) ;
            try{ Thread.sleep( 100 ) ; }catch( InterruptedException ie ){} //just to delay the work
        }
    }
}
0
 
ksivananthCommented:
you done already???
0
 
ksivananthCommented:
I forgot to add the shutdown mech, hope you know and implement on yourself!!!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 10
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now