Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How Do i kil a thread

Posted on 2006-06-09
15
Medium Priority
?
240 Views
Last Modified: 2011-09-20
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
Comment
Question by:jacobbdrew
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 5
15 Comments
 
LVL 1

Author Comment

by:jacobbdrew
ID: 16875182
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875223
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875229
you cant kill a thread but there are mechanism to terminate the thread execution like returning from run method based on some flag...
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 26

Expert Comment

by:ksivananth
ID: 16875343
what do u mean thread die?
0
 
LVL 1

Author Comment

by:jacobbdrew
ID: 16875357
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875375
No the code is wrong here, let me correct it!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875403
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875418
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
 
LVL 1

Author Comment

by:jacobbdrew
ID: 16875419
will that limit the number of threads created at one time, or do I need a thread pool? (which I know nothing about)
0
 
LVL 1

Author Comment

by:jacobbdrew
ID: 16875424
how do you create worker threads and a pool?

0
 
LVL 26

Accepted Solution

by:
ksivananth earned 2000 total points
ID: 16875443
please wait for some time to give u some sample
0
 
LVL 1

Author Comment

by:jacobbdrew
ID: 16875456
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875572
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
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875579
you done already???
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 16875592
I forgot to add the shutdown mech, hope you know and implement on yourself!!!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question