Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #2260 > unrolled thread

Please help me kill this java thread..... code example

Started bykedward777@gmail.com
First post2012-11-15 07:06 -0800
Last post2012-11-15 13:37 -0800
Articles 9 — 4 participants

Back to article view | Back to comp.lang.java.help


Contents

  Please help me kill this java thread..... code example kedward777@gmail.com - 2012-11-15 07:06 -0800
    Re: Please help me kill this java thread..... code example kedward777@gmail.com - 2012-11-15 07:09 -0800
      Re: Please help me kill this java thread..... code example Knute Johnson <nospam@knutejohnson.com> - 2012-11-15 08:42 -0800
    Re: Please help me kill this java thread..... code example Eric Sosman <esosman@comcast-dot-net.invalid> - 2012-11-15 11:49 -0500
      Re: Please help me kill this java thread..... code example kedward777@gmail.com - 2012-11-15 10:16 -0800
        Re: Please help me kill this java thread..... code example Eric Sosman <esosman@comcast-dot-net.invalid> - 2012-11-15 13:33 -0500
          Re: Please help me kill this java thread..... code example kedward777@gmail.com - 2012-11-15 10:56 -0800
            Re: Please help me kill this java thread..... code example Eric Sosman <esosman@comcast-dot-net.invalid> - 2012-11-15 14:21 -0500
    Re: Please help me kill this java thread..... code example Roedy Green <see_website@mindprod.com.invalid> - 2012-11-15 13:37 -0800

#2260 — Please help me kill this java thread..... code example

Fromkedward777@gmail.com
Date2012-11-15 07:06 -0800
SubjectPlease help me kill this java thread..... code example
Message-ID<b18cadc9-199f-4900-9f44-b25ec90acbd4@googlegroups.com>
I am using a JVM for a mobile device based on java 1.4, ~old I know, but it is what I must use.

I am creating a simple swing application with a gui and a barcode laser scanner api. I place the swing gui thread in the AWT-EventQueue, and then I place barcode scanner code in a worker thread to feed the gui scanned item codes. Problem is, that when I click exit on the gui, ONLY the gui shuts down. I can't seem to kill the worker thread. Have a look:

public class Main extends javax.swing.JFrame implements ActionListener, ScannerListener, ItemListener, KeyListener {
   Scanner scanner;

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

 public Main() {
         //display GUI - a simple field to display the item number when the
         // barcode scanner trigger is pressed, and a exit button to close the app
        initComponents();
        // launch the scanner code to feed the gui scanned items
        worker = new Runnable()
                           {
                              public void run()
                              {
                                 try
                                 {
                                  //a while loop to scan and wait   
                                   launchScanner();  
                                 }
                                 catch (Exception e) {                               }
                            };
                            scannerThread = new Thread(worker);
                            scannerThread.start();
    }



  private void shutdown(java.awt.event.ActionEvent evt) {                          
          //this will shutdown the gui when the exit button is pressed. BUT how do I kill the scanner thread?
        System.exit(0); 
    }                         

[toc] | [next] | [standalone]


#2261

Fromkedward777@gmail.com
Date2012-11-15 07:09 -0800
Message-ID<4e56eec9-e5d5-4452-a8c5-de90d175426c@googlegroups.com>
In reply to#2260
 Here is the scanner while loop:

public synchronized void launchScanner(){
        // Get physical scanner device list
        devList = Symbol.getScannerDeviceList();
        if (devList == null){
            System.out.println("No physical scanner device available");
            return;
        }

        // Create and enable scanner
        try{
                scanner = new Scanner(devList[0]);
                scanner.enable();
                scanEnabled = true;
        }catch (Exception e){
            System.out.println("can't initialize scanner object: " + e.getMessage());
            return;
        }
		
        exiting = false;
        while (!exiting){
            try{
          
                    scanner.read(null, this);
                    wait();
            }catch (Exception e){
                   System.out.println("Got Error: " + e.getMessage());
                return;
            }
        }
			
    }

[toc] | [prev] | [next] | [standalone]


#2262

FromKnute Johnson <nospam@knutejohnson.com>
Date2012-11-15 08:42 -0800
Message-ID<k8361v$jhj$1@dont-email.me>
In reply to#2261
On 11/15/2012 7:09 AM, kedward777@gmail.com wrote:
>   Here is the scanner while loop:
>
> public synchronized void launchScanner(){
>          // Get physical scanner device list
>          devList = Symbol.getScannerDeviceList();
>          if (devList == null){
>              System.out.println("No physical scanner device available");
>              return;
>          }
>
>          // Create and enable scanner
>          try{
>                  scanner = new Scanner(devList[0]);
>                  scanner.enable();
>                  scanEnabled = true;
>          }catch (Exception e){
>              System.out.println("can't initialize scanner object: " + e.getMessage());
>              return;
>          }
> 		
>          exiting = false;
>          while (!exiting){
>              try{
>
>                      scanner.read(null, this);
>                      wait();
>              }catch (Exception e){
>                     System.out.println("Got Error: " + e.getMessage());
>                  return;
>              }
>          }
> 			
>      }
>

One of the simplest ways to terminate a thread from another thread is to 
interrupt that thread.  You can detect the interrupt by catching an 
InterruptedException and checking the status of the thread with 
Thread.interrupted() or Thread.isInterrupted().  If the thread is 
blocked on I/O you can usually close the stream and force a IOException.


-- 

Knute Johnson

[toc] | [prev] | [next] | [standalone]


#2263

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2012-11-15 11:49 -0500
Message-ID<k836e1$l25$1@dont-email.me>
In reply to#2260
On 11/15/2012 10:06 AM, kedward777@gmail.com wrote:
> I am using a JVM for a mobile device based on java 1.4, ~old I know, but it is what I must use.
>
> I am creating a simple swing application with a gui and a barcode laser scanner api. I place the swing gui thread in the AWT-EventQueue, and then I place barcode scanner code in a worker thread to feed the gui scanned item codes. Problem is, that when I click exit on the gui, ONLY the gui shuts down. I can't seem to kill the worker thread. Have a look:

     You've not given us much to look at, but I'll have a try.

> public class Main extends javax.swing.JFrame implements ActionListener, ScannerListener, ItemListener, KeyListener {
>     Scanner scanner;
>
> public static void main(String args[]) {
>          java.awt.EventQueue.invokeLater(new Runnable() {

     Aside: Why not SwingUtilities.invokeLater()?  Probably makes
little or no difference, but ...

>              public void run() {
>                  new Main().setVisible(true);
>              }
>          });
>      }
>
>   public Main() {
>           //display GUI - a simple field to display the item number when the
>           // barcode scanner trigger is pressed, and a exit button to close the app
>          initComponents();
>          // launch the scanner code to feed the gui scanned items
>          worker = new Runnable()
>                             {
>                                public void run()
>                                {
>                                   try
>                                   {
>                                    //a while loop to scan and wait
>                                     launchScanner();
>                                   }
>                                   catch (Exception e) {                               }

     Ugh, barf, bleahh!  This is a bit like unplugging that noisy
smoke alarm so you can get back to sleep.  It is *very* occasionally
all right to catch and ignore an exception, but even then you should
write a comment explaining *why* you believe *this* exception is safe
to ignore.  If you can come up with an explanation of why *every*
kind of Exception is safe to ignore, you're bolder than I will ever be.

>                              };
>                              scannerThread = new Thread(worker);
>                              scannerThread.start();

     Aside: It's not a good idea to start threads inside constructors.
The problem is that the constructed object isn't "truly constructed"
until the entire chain of constructors has returned, so you shouldn't
allow the outside world to see `this' yet.  Starting a thread exposes
`this' (via the nested Runnable), thus letting the rest of the program
observe the Main object before it's complete.  You'll probably get
away with it in this instance, but cure yourself of this bad habit.

>      }
>
>
>
>    private void shutdown(java.awt.event.ActionEvent evt) {
>            //this will shutdown the gui when the exit button is pressed. BUT how do I kill the scanner thread?
>          System.exit(0);

     This should shut down the entire JVM: GUI, worker threads,
garbage collector, daemons, the whole shebang.  I have only three
guesses about why you observe the worker still running:

     1) The shutdown() method is never called.  You haven't shown
        us any of the arrangements you've made to have it called,
        so we can't tell whether they're correct (or even whether
        they exist).  Try `System.out.println("Kilroy was here");'
        at the start of shutdown(), just to find out whether you
        do or do not ever get there.

     2) A security manager forbids exit() from doing anything.
        If this happens a SecurityException will be thrown, and
        that might (or might not) be what stops the GUI.  Perhaps
        your habit of catching and ignoring exceptions has blinded
        you to what's going on here.

     3) You're wrong: The worker thread does in fact stop.  You've
        not explained why you think it's still running, so we can't
        tell whether your conclusion is correct.

     I'm not a betting man, but if I were my money would be on (1).

>      }
>


-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#2264

Fromkedward777@gmail.com
Date2012-11-15 10:16 -0800
Message-ID<b571f064-315f-4fb5-81fc-b850984727d7@googlegroups.com>
In reply to#2263
Thank you for your help! Sorry, I did have many more printouts to stdout, but stripped them to make it easier to read.... It is interesting that you said the System.exit should should down everything, now I am stumped...but here are my responses:

>      1) The shutdown() method is never called.  You haven't shown
>         us any of the arrangements you've made to have it called,
>         so we can't tell whether they're correct (or even whether
>         they exist).  Try `System.out.println("Kilroy was here");'
>         at the start of shutdown(), just to find out whether you
>         do or do not ever get there.
>      2) A security manager forbids exit() from doing anything.
>         If this happens a SecurityException will be thrown, and
>         that might (or might not) be what stops the GUI.  Perhaps
>         your habit of catching and ignoring exceptions has blinded
>         you to what's going on here.

I am sure shutdown is being called, because I can see that the GUI does shutdown/closes.


>      3) You're wrong: The worker thread does in fact stop.  You've
>         not explained why you think it's still running, so we can't
>         tell whether your conclusion is correct.

I do not believe the worker thread is stopping because AFTER I click on the shutdown button, I then see the GUI shutdown/close, BUT I still see the netbeans JMV stdout window say the jvm is running still, AND I can perform ONE LAST scan, AND THEN I see the netbean jvm window close, and the scanner beam is then silent.

[toc] | [prev] | [next] | [standalone]


#2265

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2012-11-15 13:33 -0500
Message-ID<k83chd$tmt$1@dont-email.me>
In reply to#2264
On 11/15/2012 1:16 PM, kedward777@gmail.com wrote:
> Thank you for your help! Sorry, I did have many more printouts to stdout, but stripped them to make it easier to read.... It is interesting that you said the System.exit should should down everything, now I am stumped...but here are my responses:
>
>>       1) The shutdown() method is never called.  You haven't shown
>>          us any of the arrangements you've made to have it called,
>>          so we can't tell whether they're correct (or even whether
>>          they exist).  Try `System.out.println("Kilroy was here");'
>>          at the start of shutdown(), just to find out whether you
>>          do or do not ever get there.
>>       2) A security manager forbids exit() from doing anything.
>>          If this happens a SecurityException will be thrown, and
>>          that might (or might not) be what stops the GUI.  Perhaps
>>          your habit of catching and ignoring exceptions has blinded
>>          you to what's going on here.
>
> I am sure shutdown is being called, because I can see that the GUI does shutdown/closes.

     There are many things that might stop the GUI, so the fact
that it vanished does not prove shutdown() was called.  Have you
tried the suggested println()?

>>       3) You're wrong: The worker thread does in fact stop.  You've
>>          not explained why you think it's still running, so we can't
>>          tell whether your conclusion is correct.
>
> I do not believe the worker thread is stopping because AFTER I click on the shutdown button, I then see the GUI shutdown/close, BUT I still see the netbeans JMV stdout window say the jvm is running still, AND I can perform ONE LAST scan, AND THEN I see the netbean jvm window close, and the scanner beam is then silent.

     Okay: I've come up with a fourth guess.  Perhaps exit() has in
fact been called (and allowed), and the JVM is in the process of
shutting down.  But perhaps shutdown cannot complete while the scanner
code holds a lock or other resource (JNI?) that the JVM's shutdown
needs before shutdown can complete.  Firing the scanner one last time
might jar things loose.  (Remember: This is still just a guess.)

     The scanner code (in another thread you called it "the motorola
sample program") is not known to me, so I can't say what it might be
hanging on to.  Knute Johnson's suggestion of interrupting the thread
might work, if the code is well-behaved (and doesn't, for example,
just catch and ignore exceptions); I'd suggest giving it a try.  If
that doesn't help -- well, you say you're using NetBeans, which means
you have a debugger available; have you used it to find out what the
threads are doing instead of exiting?

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#2266

Fromkedward777@gmail.com
Date2012-11-15 10:56 -0800
Message-ID<286880a2-9d51-45a5-892a-1bad72e69ad9@googlegroups.com>
In reply to#2265
Thank you again! I think you are right about the a lock on the JVM by the scanner thread. 

One key point is that I am also tried setting the "exiting" variable in the shutdown method, which should stop the while loop of the scanner thread... but I don't think the thread is being woken in the shutdown, BUT then when I press the scan trigger, it wakes the thread and it sees that exiting is true, and THEN dies...

 private void shutdown(java.awt.event.ActionEvent evt) {                           
        existing=true;
        System.exit(0); 
    }                         

QUESTION: how do I wake the scanner thread from the event thread (shutdown) ... I tried notifyAll(), but I get an exception:
java.lang.IllegalMonitorStateException: current thread not owner

> 
>      Okay: I've come up with a fourth guess.  Perhaps exit() has in
> fact been called (and allowed), and the JVM is in the process of
> shutting down.  But perhaps shutdown cannot complete while the scanner
> code holds a lock or other resource (JNI?) that the JVM's shutdown
> needs before shutdown can complete.  Firing the scanner one last time
> might jar things loose.  (Remember: This is still just a guess.)
> 
>      The scanner code (in another thread you called it "the motorola
> sample program") is not known to me, so I can't say what it might be
> hanging on to.  Knute Johnson's suggestion of interrupting the thread
> might work, if the code is well-behaved (and doesn't, for example,
> just catch and ignore exceptions); I'd suggest giving it a try.  If
> that doesn't help -- well, you say you're using NetBeans, which means
> you have a debugger available; have you used it to find out what the
> threads are doing instead of exiting?

[toc] | [prev] | [next] | [standalone]


#2267

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2012-11-15 14:21 -0500
Message-ID<k83fco$g5e$1@dont-email.me>
In reply to#2266
On 11/15/2012 1:56 PM, kedward777@gmail.com wrote:
> Thank you again! I think you are right about the a lock on the JVM by the scanner thread.
>
> One key point is that I am also tried setting the "exiting" variable in the shutdown method, which should stop the while loop of the scanner thread... but I don't think the thread is being woken in the shutdown, BUT then when I press the scan trigger, it wakes the thread and it sees that exiting is true, and THEN dies...
>
>   private void shutdown(java.awt.event.ActionEvent evt) {
>          existing=true;

     Elsethread you posted code for a launchScanner() method where
`exiting' (not `existing', by the way) is tested:

	public synchronized void launchScanner(){
	//...
         exiting = false;
         while (!exiting){
             try{
                     scanner.read(null, this);
                     wait();
             }catch (Exception e){
                    System.out.println("Got Error: " + e.getMessage());
                 return;
             }
         }
	//...

     We don't know what class this method belongs to, so we don't
know why it's synchronized, nor what object it synchronizes on,
nor what you expect the wait() call to do.  Maybe there are answers
and reasons, but the code looks a bit suspect.

     You don't show the declaration of `exiting' so we can't tell
whether it's `volatile', which it pretty much needs to be for this
sort of purpose.  If it's not `volatile' the test in the `while'
loop might be eliminated entirely.

     Even if it *is* `volatile', it won't be tested until after the
scanner.read() and the very peculiar wait() calls both return, so
if you're sitting in one or the other of those setting `exiting'
will have no immediate effect.

>          System.exit(0);
>      }
>
> QUESTION: how do I wake the scanner thread from the event thread (shutdown) ... I tried notifyAll(), but I get an exception:
> java.lang.IllegalMonitorStateException: current thread not owner

     Quite plainly, you have no idea what you're doing.  This is not
a shameful state of affairs unless it persists; we all start from a
position of ignorance.  But if you don't understand *why* you can't
call notify()/notifyAll() without holding the object's lock, that
also suggests you don't know what they do -- which in turn suggests
that you don't know what wait() does, either.  Are you just making
plausible-seeming but random changes in hopes of stumbling upon some
working code?  A random walk eventually goes everywhere, but it may
take several lifetimes to get anywhere useful.  I think it's time
you read a book or something.

     (Long years ago I had a student who approached his programming
tasks the way you seem to be approaching this one: Throw something
together that sort of looks somewhat believable, then start shaking
and kicking and beating it until one test case succeeds.  Trouble
was, the work he turned in almost never ran the second test case.
In most programming, *especially* in multi-threaded programming, you
need enough understanding to be able to reason about the code: Just
observing it a few times simply won't do.  I think you need to set
about increasing your level of understanding.)

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#2269

FromRoedy Green <see_website@mindprod.com.invalid>
Date2012-11-15 13:37 -0800
Message-ID<v0oaa89ofgf5tfc0nispjifuqj8fptchij@4ax.com>
In reply to#2260
On Thu, 15 Nov 2012 07:06:01 -0800 (PST), kedward777@gmail.com wrote,
quoted or indirectly quoted someone who said :

>          //this will shutdown the gui when the exit button is pressed. BUT=
> how do I kill the scanner thread?


see com.mindprod.common11.StoppableThread.
Code available at http://mindprod.com/products1.html#COMMON11 free.
-- 
Roedy Green Canadian Mind Products http://mindprod.com
Ironically, even though the Internet was created by the US military 
[DARPA (Defense Advanced Research Projects Agency)]
to withstand a nuclear attack, it is almost defenceless against malice
from any of its users

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.help


csiph-web