Thread suspending..

Whats the best way of implementing a Thread so that you can start/stop the thread, and between each cycle cause the thread to sleep for a period of time ??
I have the following code, but need a way of stopping the Thread hogging all the CPU time when it is not running:
public class MyThread extends Thread()
  private int sleepPeriod = 1000; // 1000ms == 1sec
  private boolean alive = false;
  private boolean running = false;
  private void setRunning(boolean val)
    running = val;
  private boolean isRunning()
    return (running && alive);
  private void setAlive(boolean val)
    alive = val;
  private boolean isAlive()
    return (alive && super.isAlive());
  private void startThread()
    setRunning(true);
    setAlive(true);
    start();
  private void startThreadSuspended()
    setRunning(false);
    setAlive(true);
    start();
  private void run()
    while (alive) {
      while (alive && running) {
        // do work
        // Sleep
        try {
          Thread.sleep(sleepPeriod);
        } catch (Exception e) {}
      // What to put in here to force thread to sleep/wait until told to carry on
      // wait() ??
}Ive tried with a wait() where indicated above, but if i place notify() or notifyAll() in the setRunning() method, then an exception is thrown, stating that current thread is not owner of lock !??
There is some guidance at http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html, but this seems to throw the same exception !

The best way I think of suspending the thread is to have a shared variable (probably, static in nature). The value of this variable decides execution and suspention. For example, a boolean variable ..
public static boolean abc = false ;
// Run a thread and check the value of abc. If it is false then change the value of abc = true and do your work.
if ( abc == false )  {
  // Do you work
} else {
// Keep on sleep or wait and keep on checking the value after fix interval of wait.
}Hope this help.
Shozi
Btw: Your problem is typically related to critical section problem. I suggest you look at this topic in any operting system concepts book.

Similar Messages

  • Java Thread suspend and resume problem

    Hi,
    I am trying to write a program to implement thread suspend and resume using wait() and notify without using the deprecated methods like resume and suspend.
    I have written the following program which compiles but when I run it hangs without terminating. There seems to be some logic error but I am not able to catch it.
    Please help
    public class TestSuspendResume {
      public static void main(String[] args) {
        MyThread m1= new MyThread("--One-- ");
        MyThread m2= new MyThread("--Two-- ");
        m1.suspendMe();
        try {
          Thread.sleep(1500);
          m1.t.join();
          m2.t.join();
        } catch(InterruptedException e) {
          e.printStackTrace();
        m1.resumeMe();
        System.out.println("Now : end main thread");
    class MyThread implements Runnable {
      boolean suspend = false;
      Thread t;
      MyThread(String name) {
        t = new Thread(this,name);
        t.start();
      void resumeMe() {
        suspend = false;
        notify();
      void suspendMe() {
        suspend = true;
      public void run() {
        try {
          for(int i=0;i<20;i++) {
            System.out.println("Now : "+Thread.currentThread().getName()+i);
            Thread.sleep(200);
            synchronized(this) {
              while(suspend)
                wait();
        } catch(InterruptedException e) {
          e.printStackTrace();
    }

    Thanks for that response. I figured out that was the problem in the logic. I have modified the code to make it simpler but it is still hanging.
    public class TestSuspendResume {
      public static void main(String[] args) {
        MyThread m1= new MyThread("--One-- ");
        try {
          m1.suspendMe();
          Thread.sleep(1000);
        } catch(InterruptedException e) {
          e.printStackTrace();
        try {
          m1.resumeMe();
        } catch(Exception e) {
          System.out.println("ASASAS");
          e.printStackTrace();
        try {
          m1.t.join();
        } catch(InterruptedException e) {
          System.out.println("WOWOW");
          e.printStackTrace();
        System.out.println("Now : end main thread");
    class MyThread implements Runnable {
      boolean suspend = false;
      Thread t;
      MyThread(String name) {
        t = new Thread(this,name);
        t.start();
      void resumeMe() {
        if(suspend==true) {
          suspend = false;
          notify();
      void suspendMe() {
        suspend = true;
      public void run() {
        try {
          for(int i=0;i<20;i++) {
            System.out.println("Now : "+Thread.currentThread().getName()+i);
            Thread.sleep(200);
            synchronized(this) {
              while(suspend)
                wait();
        } catch(InterruptedException e) {
          System.out.println("-- E In run method -- "+e.getMessage());
    }

  • Thread.suspend()

    I realize that there are very good reasons Thread.suspend() has been deprecated; however, I believe I've found a good use for it. I have a very CPU intensive external application that I want to run. I want to put it in its own thread and have the ability to pause it. Since I can't modify it in any way, I can't add code to provide thread safe suspending. In this situation, I want to wrap the external process in a Thread object, let it run and occasionally call Thread.suspend(). I won't touch the thread until it's done running. Additionally, the external process does no IO, so I don't have to worry about interrupting it at the wrong time.
    Is it appropriate to use Thread.suspend() here? If not, is there another way to provide the same functionality? If I use Thread.suspend(), what are the chances that it will be removed from future versions of Java?

    Have a look at this page, its all described there:
    http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html

  • Thread.suspend and Thread.resume

    I'm trying to build a class to replace the use of Thread.suspend() and Thread.resume() deprecated methods.
    I tried to as recommended on sun web page but it doesn't work : illegate state monitor exception.
    Does anyone have a solution ?
    Note :
    Source code
    package com.utils;
    public class SuspendableThread extends Thread {
         private Object mutex = new Object() ;
         private volatile boolean suspended = false ;
         private Runnable runnable ;
         public SuspendableThread ( Runnable runnable )
              super(runnable) ;
              this.runnable = runnable ;
         * Suspend the current thread
         public void doSuspend()
              synchronized (mutex) {
                   suspended = true ;
                   while(suspended) {
                        try {
                             runnable.wait() ;
                        } catch (InterruptedException e) {
                             e.printStackTrace();
         * Resume the current thread if suspended
         public void doResume()
              synchronized (mutex) {
                   if (suspended) {
                        suspended = false ;
                        runnable.notify() ;
    Exception
    java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.wait(Native Method)
         at java.lang.Object.wait(Unknown Source)
         at com.utils.SuspendableThread.doSuspend(SuspendableThread.java:39)

    If you're synchronizing on the mutex, you should wait() and notify() on the mutex.
    synchronized (mutex) {
        suspended = true ;
        while(suspended) {
            try {
                mutex.wait(); //wait on the mutex
            } catch (InterruptedException e) {
                e.printStackTrace();
    synchronized (mutex) {
        if (suspended) {
           suspended = false ;
            mutex.notify(); //notify threads waiting on the mutex
    //...

  • Thread: suspend() and resume()

    Hi,
    Both suspend() and resume() methods are deprecated, but I've used it anyway. I've realised my code can get into a deadlock.
    Is there anything I could use other than suspend and resume, but providing the same functionality?
    Many Thanks

    You should use wait and notify. There is a good
    discussion of this at the bottom of the deprecation
    notes on stop, suspend and resume.Yes, I just saw that. Before, I was looking at an old API.

  • How to solve: Main Thread (Suspended: Error: value of pendingCustomerTokenList must be a collection)

    Hi All,
    Have an app that I am creating in flashbuilder 4, java axis 2 web service and mysql.
    In my app I have defined a service.  I have had not problems with pulling data and inserting data
    by calling my java functions through the service.
    I added a new property and then made it available in flex.  it display on label field,  Ran the app and got the error:
    Error: value of pendingCustomerTokenList must be a collection
      at valueObjects::_Super_PendingTokensResponse/set pendingCustomerTokenList()[F:\vEngage\flexworkspace\FBAgentApp\src\valueObjects\_Super_Pe ndingTokensResponse.as:104]
      at com.adobe.serializers.utility::TypeUtility$/assignProperty()[/Users/sameer/depot/flex/ide _builder/com.adobe.flexbuilder.dcrad/serializers/src/com/adobe/serializers/utility/TypeUti lity.as:559]
      at com.adobe.serializers.utility::TypeUtility$/convertToStrongType()[/Users/sameer/depot/fle x/ide_builder/com.adobe.flexbuilder.dcrad/serializers/src/com/adobe/serializers/utility/Ty peUtility.as:498]
      at com.adobe.serializers.utility::TypeUtility$/convertResultHandler()[/Users/sameer/depot/fl ex/ide_builder/com.adobe.flexbuilder.dcrad/serializers/src/com/adobe/serializers/utility/T ypeUtility.as:372]
      at mx.rpc.soap::Operation/http://www.adobe.com/2006/flex/mx/internal::processResult()[E:\dev\4.y\frameworks\projects \rpc\src\mx\rpc\soap\Operation.as:953]
      at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.y\frameworks\projects \rpc\src\mx\rpc\AbstractInvoker.as:313]
      at mx.rpc::Responder/result()[E:\dev\4.y\frameworks\projects\rpc\src\mx\rpc\Responder.as:56]
      at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.y\frameworks\projects\rpc\src\mx\rpc\AsyncReq uest.as:84]
      at DirectHTTPMessageResponder/completeHandler()[E:\dev\4.y\frameworks\projects\rpc\src\mx\me ssaging\channels\DirectHTTPChannel.as:451]
      at flash.events::EventDispatcher/dispatchEventFunction()
      at flash.events::EventDispatcher/dispatchEvent()
      at flash.net::URLLoader/onComplete()
    I looked at the Network Monitor tab and examined the call/response.  Response body shows no error and the Response result shows the data returned by my java axis 2 function.  Its all correct.
    Ran configure return type again.  Let it auto-detect and return type from sample data. The properties returned looked just fine.
    Looked at the _Super_PendingTokensResponse.as on line 104
    var oldValue:ArrayCollection = _internal_pendingCustomerTokenList;              
            if (oldValue !== value)
                if (value is ArrayCollection)
                    _internal_pendingCustomerTokenList = value;
                else if (value is Array)
                    _internal_pendingCustomerTokenList = new ArrayCollection(value);
                else
                    throw new Error("value of pendingCustomerTokenList must be a collection");
            this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "pendingCustomerTokenList", oldValue, _internal_pendingCustomerTokenList));
    How to I correct this problem ?
    thanks for any help.

    Have a look at these docs:
    E-CA Change Assistant gives error: All agents should be running and sending pulses for all application, batch, file and web servers for the environment before the Change Assistant is started (Doc ID 1073464.1)
    E-CA: PT8.53, PT8.52, PT8.51, PT8.50: EMF Agents not Finding Configuration Files for App Server, Batch Server (Doc ID 1080590.1)

  • How can I implement This? - Via Multiple Threads

    Hi Friends,
    I m getting a list of 4000 emails in an ArrayList. Now I want to put 300 addresses in a mail at a time, and Want to create a new Thread and Send a Mail.
    I want to run 20 threads at a time to do so, Means Each thread is taking 300 addresses from array assigning it to Message and send it. After Sending it should return to ThreadPool.
    Also the 300 addresses should be removed from arraylist.
    Here are code snippet, i m using..
    MailBean.java - A bean which have all the MailProperty and Send Method.
    MailSender.java - It implements Runnable Interface, In its constructor A MailBean Object is Created and in run method it is sending the Mail.
    FileReader.java - It extends ArrayList, it takes a fileName, parse the Emails add email.
    Main.java - Here i want to send mails using ExecutorService class of java.util.concurrent.
    Mailer.java (Main Class)
    public class Mailer {     
         private final FileReader toEmails;
         private ArrayCollection<String> emails ;
         public Mailer(String addressFile){          
              toEmails = new FileCollection(addressFile);
              emails = new ArrayCollection<String>();
                          Here I want to read the 300 emails from toEmails append it in a String and add it to emails ArrayCollection.
        public static void main(String[] args) {
            try{
                 BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(200);
                 Executor e = new ThreadPoolExecutor(50, 50, 1, TimeUnit.SECONDS, queue);
                    if (args.length != 1) {
                         System.err.println("Usage: java ExecutorExample address_file" );
                         System.exit(1);
                  Mailer mailer = new Mailer(args[0]);
                  MailBean bean = new MailBean();
                  bean.setSubject("Mail Bean Test");
                  bean.setMessage("Hi This is a Test Message, Please Ignore this Message");
               /*  I want to run the send mails to all the emails (300 emails per String.) with the Exceutor.
                   Can somebody tell, I want a new object of MailSender for each mail
                   and sendmails
                 System.out.println("Creating workers");
                 for(int i = 0; i < 20; i++)
                     e.execute(new MailSender(bean));
                 System.out.println("Done creating workers");
            }catch(Exception ex){
                 ex.printStackTrace();
    } Can Somebody give me hint, How can we do it?

    The problem is the sound buffer. You may stop the method which dispatch the notes to be played... but not clear your sound card buffer....
    anyway: you should implement it in daemon threads. This way you can control the thread suspend, stop, restart, etc.
    use Thread.sleep(milliseconds);

  • Can't kill a running thread...

    I'm having some problems killing a thread. Becuase thread.stop() is no longer used, I basically set a flag to tell all the threads to return by checking this flag in the run() method. The problem now is that there is a thread that is getting "stuck" in a class that I have no access to. So basically I assume that its a really long loop, or an infinite loop... either way, that thread doesn't stop even if the "parent" (spawning) thread is "stopped". Any suggestions?
    -L

    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

  • The problem about multi-thread in java application

    i have problem with the multi-thread in java application, i don't know how to stop and restart a thread safely, because the function thread.stop(),thread.suspend() are both deprecated.
    now what i can only do is making the thread check a flag(true or false) to determine whether to start or to stop, but i think this thread will always be in the memory and maybe it will lower the performance of the system, as the program i am developping is working under realtime enviorement.
    please help me about it. thanks !

    hi,
    you can stop a thread by exiting it's run()-method which in terms can be done by checking the interrupted-flag:
    public void run(){
    while(interrupted()){ //if the thread consists of a loop
    or
    public void run(){
    if(interrupted())return;
    if(interrupted())return;
    or by the use of the return-statement anywhere withing the run-method. Afterwards, that is when the thread is no longer needed, you clear all the references to the specific thread object by setting them to null:
    Thread t;
    ... //working
    t.interrupt(); //interrupting
    while(t.isAlive()){
    Thread.yield(); //wait till thread t has stopped
    t=null;
    best regards, Michael

  • Java FX task daemon thread

    Hello,
    I'm working on a large scale GUI and running in to OOMs. Looking at the threads, there are hundreds of them sitting around named Java FX task daemon thread.
    Daemon Thread [Java FX task daemon thread] (Running)            
                                    Daemon Thread [Java FX task daemon thread] (Suspended)      
                                                    Unsafe.park(boolean, long) line: not available [native method]              
                                                    LockSupport.park(Object) line: 158        
                                                    AbstractQueuedSynchronizer$ConditionObject.await() line: 1987          
                                                    DelayQueue<E>.take() line: 160              
                                                    ScheduledThreadPoolExecutor$DelayedWorkQueue.take() line: 609   
                                                    ScheduledThreadPoolExecutor$DelayedWorkQueue.take() line: 602   
                                                    ScheduledThreadPoolExecutor(ThreadPoolExecutor).getTask() line: 947            
                                                    ThreadPoolExecutor$Worker.run() line: 907      
                                                    Thread.run() line: 662    Can anyone shed some light on what is starting these threads?

    I had similar issues with a server running on XP, where it kept dying randomly with no problems.
    I tracked down what was happening by getting the exit value of the java process - which may give you information regarding what happened to the process.
    For example, if CTRL+C was pressed you get a value of 130 returned in the Linux environment. Using this error information I found out why my server kept dying (which was the XP telnet window was sending dodgy key presses to the window the server was running in).
    The exit code of a process is available after it exits via $status in Unix or %errorlevel% in a PC .bat file.

  • Thread Realted

    I am running Class ThreadTestB. I am not able to get the region why
    ThreadTestB b1 = new ThreadTestB("b1.......");
    ThreadTestB b2 = new ThreadTestB("b2 ****");
    Is also executing.
    If &#8220;b1&#8221; will execute Infinite time then lock will not released . so &#8220;b2&#8221; execution is not possible. But when u run
    Class ThreadTest B. B2 execution is also done . Why it is passible ?.
    public class ThreadTestB extends Thread {
    ThreadTestB(){}
    ThreadTestB(String str){
    super(str);
    //FileOutputStream fout= new FileOut
    ThreadTestA a = new ThreadTestA();
    public void run()
    a.Am1();
    a.Am2();
    public static void main(String[] args) {
    ThreadTestB b1 = new ThreadTestB("b1.......");
    ThreadTestB b2 = new ThreadTestB("b2 ****");
    b1.start();
    b2.start();
    public class ThreadTestA {
    //FileOutputStream fout= new FileOut
    public synchronized void Am1(){
    System.out.println(" Am1 start to execute .."+Thread.currentThread().getName());
    while(true){
    System.out.println(" Am1 ...........00000 current thread "+Thread.currentThread().getName());
    // try{Thread.sleep(1000);
    // }catch(Exception exp){}
    public synchronized void Am2(){
    while(true){
    System.out.println(" Am2 ***********1111current thread "+Thread.currentThread().getName());
    // try{Thread.sleep(1000);
    // }catch(Exception exp){}
    public static void main(String[] args) {

    Thank ,
    but pls explain by Example. I'm sure the tutorial has examples.
    Here are a couple more examples.
    http://www.javaalmanac.com/cgi-bin/search/find.pl?words=thread
    You might also want to check out Doug Lea's Concurrent Programming in Java
    Here's yawmark's list of goodies. I'm sure you'll find examples there too:
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
    Go through some of this stuff, and if you have a question more specific than "How do I use threads to handle multiple requests?" then post again.
    Oh, also, if you need an intro to the socket side of it:
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
    The Java&trade; Tutorial - Lesson: All About Sockets
    Sockets programming in Java: A tutorial

  • Shutting down rogue threads: impossible?

    While designing a system that accepts 'plugins' that are sent by untrusted users, I ran across this problem:
    Imagine a malicious user intentionally sends this plugin:
    public void init()
    int[][] a = new int[123456][10]; //allocate tons of memory.
    while ( true ) ; //waste tons of CPU cycles.
    I want to 'defend' against this kind of thing, whether done intentionally or not.
    So far, I have found out the following things:
    A) There is no java-based profiler information. In other words, there is no such thing as a thread.getCpuLoad() kind of method. There is the JVMPI, so for now I guess I'll write various JNI libraries that will make the JVMPI interface callable from java.
    B) Even if the thread is identified, there is no way at all to destroy it. Thread.destroy() is unimplemented (returns NoSuchMethodError). Thread.suspend() still works, eventhough it is deprecated, and will stop a thread when doing something like while ( true ) ;. However, I have not found a way of reclaiming any allocated memory. Removing all references to the thread object and then running the garbage collector didn't help.
    C) There does not appear to be any thread kill functionality in JVMPI, though I might have missed something.
    D) There does not appear to be a relatively simple way to start up a new 'lite' JVM to run the untrusted code in. Starting up an entire new java executable through Runtime.getRuntime.process() might work, but the endgoal is to get tons of these little plugins running in their own threads. One JVM can actually handle this admirably, but I doubt one system can handle 70 to 80 concurrent JVMs.
    leading me to the conclusion:
    There is no way to really 'sandbox' untrusted code. Even if you can prevent them from opening files and such, they can perform a DoS attack bij allocating large amounts of memory and getting stuck in while ( true ) ; loops. Even if this behaviour is detected, there is no way to guard against it happening aside from suspending the thread and accepting the memory as unreclaimable until the JVM is restarted.
    I really hope there is a better solution than suspending and writing off the used memory, but if there is no way to really kill a thread, perhaps this can be worked on ASAP for the next release? destroy() exists. It needs implementation.
    Incidentally, there is no risk here of contaminating the state or causing deadlocks due to monitors being locked 'forever', as each such 'plugin' uses its own loader and cannot exchange data between the main system or any other plugin, except through serialized/deserialized stuff. While I understand the dangers of just cutting threads off, in this case, I have already taken precautions that one 'plugin' can't mess in any way with another.
    I did a 'test run' and wrote exactly such an applet. While it didn't hang the web-browser (Opera), it did cause Opera to use up all free CPU cycles, and there was no way to stop Opera from using up all CPU (or reclaiming the memory), short of completely exiting the browser.
    Didn't test with IE, or netscape.
    (That's Opera using JDK1.4 as JVM).
    I could of course be mistaken in all this and completely missed a way to completely kill an unresponsive thread, so I am hopefully awaiting corrections.
    --Reinier Zwitserloot.

    Weird.
    rogueThread.stop();
    rogueThread = null;
    System.gc();
    drops CPU use down to 0, and reduces the memory footprint back down to the original minimum. In other words, seems to do all the required functionality.
    I got the impression from the documentation explaining why stop/suspend/resume are deprecated that it wouldn't work unless the Thread was stuck in some kind of IO blocking call.
    Thanks a bunch!
    NB: Would anybody know of a code sample which won't respond to a stop and/or suspend? this quote from the deprecation explanation has me worried:
    "It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either."

  • Threads and stop()

    Hi
    I am struggling with the deprecated stop() method.I have a requirement in which I have to stop the thread from whatever it is doing after X amount of time.I cant go the interrupt route as my code doesnt satisfy any conditions for the interrupt to work (For Ex. sleep() and wait() ; running in a loop ; etc).
    Stop method seems ideal to me ; as it does the work I want ; but cant use it as its not a good programming practice.
    Assigning Thread to null also doesnt work.
    Any ideas.
    Thanks
    Pankaj

    Hope this helps
    The proper way to stop a running thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it should return from the run() method.
    Note: Thread.suspend() and Thread.stop() provide asynchronous methods of stopping a thread. However, these methods have been deprecated because they are very unsafe. Using them often results in deadlocks and incorrect resource cleanup.
        // Create and start the thread
        MyThread thread = new MyThread();
        thread.start();
        // Do work...
        // Stop the thread
        thread.allDone = true;
        class MyThread extends Thread {
            boolean allDone = false;
            // This method is called when the thread runs
            public void run() {
                while (true) {
                    // Do work...
                    if (allDone) {
                        return;
                    // Do work...
    Alternatively declare a stop() method inside your thread or runnable class and call this method to set allDone variable to false.

  • Suspend in jdb

    Does the "suspend" command of "jdb" use the deprecated "Thread.suspend()" method? I hope not!!!
    When a breakpoint is hit in jdb, are all threads suspended? If not, how can that be arranged?
    TIA,
    Reggie

    Does the "suspend" command of "jdb" use the deprecated
    "Thread.suspend()" method? I hope not!!!The debug interface does not use the deprecated java.lang.Thread
    methods. Take a look at:
    http://java.sun.com/j2se/1.4.1/docs/guide/jpda/jdi/com/sun/jdi/VirtualMachine.html#suspend()
    When a breakpoint is hit in jdb, are all threads
    suspended? If not, how can that be arranged?This is controlled by a parameter on the EventRequest
    (A BreakpointRequest is a kind of EventRequest). For
    more information, refer to:
    http://java.sun.com/j2se/1.4.1/docs/guide/jpda/jdi/com/sun/jdi/request/BreakpointRequest.html
    The default behavior in jdb is SUSPEND_ALL when a breakpoint
    is hit.

  • Thread Interaction

    I am writing a server - client program to transfer some data. First the main listens for a socket connection (main thread)
    while (listening) new ServerComm(serverSocket.accept()).start();The class ServerComm(socket) is the second thread, it also implements an interface called PacketReader:
    public interface PacketReader {
         public void processPacket(CommPacket packet);
    public class ServerComm extends Thread implements PacketReader {
        private Socket socket = null;
        private CommTxRx comm = null;
        private boolean ack = false;
        private int status = 0x00;
        public ServerComm(Socket socket) {
          super("ServerComm");
          this.socket = socket;
        public void run() {
            comm = new CommTxRx(socket,this); comm.start();
            synchronized (this) {
                 while (status != DONE || status != ABORT) {
                      try { wait(400);
                        } catch (InterruptedException e) { status = ABORT; }
              comm.close();
         public void processPacket(CommPacket packet) {
              switch (packet.cmd) {
                case CommDef.ACK: ack = true;
    }CommTxRx actually does the reading and writing to the socket, and it is also a thread. It calls processPacket() when it recieves a new data packet
    public class CommTxRx extends Thread {
         private Socket socket = null;
        private ObjectInputStream in = null;
        private ObjectOutputStream out = null;
        private PacketReader reader = null;
        private boolean streamOk = false;
        public boolean abort = false;
        public boolean pause = false;
        public CommTxRx(Socket socket, PacketReader reader) {
          this.socket = socket; this.reader = reader;
        public void run () {
             try {
                in = new ObjectInputStream(socket.getInputStream());
              out = new ObjectOutputStream(socket.getOutputStream());
             } catch (IOException e) {
              System.err.println("Stream Setup Error");
              streamOk = false;
              return;
             streamOk = true;
             synchronized(this) {
                while(streamOk) {
                 try { this.wait(20); } catch (InterruptedException e) {
                          if (abort) close();
                 try {
                   if (in.available() != 0 && reader != null && !pause ) {
                        reader.processPacket(read());
               } catch (IOException e) { System.out.println("Read err"); }
                 catch (ClassNotFoundException n) {System.out.println("Read err CNF");}
        public CommPacket read() throws IOException, ClassNotFoundException  {
            if (!streamOk) return null;
            return (CommPacket) in.readObject();
        }Here is my question, is this actually going to work, calling the processPacket inside the ServerComm thread from the CommTxRx thread, and does the CommRxTx thread suspend until the code in the ServerComm thread completes. What I would like to do is when a packet arrives and is processed by processPacket, it sends a reply and then waits until an ack packet is received, that would mean a second instance of processPacket would have to be launched to change the ack boolean, that would be in a wait() loop in the first call to processPacket. Am I going to have to setup every processPacket as a thread also in order to make that happen or because I already have two threads running is that going to work. I have not written the code to do that yet, I would like to find out if it is going to work before I get that far.

              while(streamOk) {
              try { this.wait(20); } catch (InterruptedException e) {Pointless. Remove.
                   if (in.available() != 0 && reader != null && !pause ) {
                        reader.processPacket(read());Pointless. Remove. Just block in the readObject() method. If you want to poll, set a short read timeout.
    I don't see the need for this class & thread at all, it should all be folded into the previous one.

Maybe you are looking for

  • Default Batch value in sale Order items

    Hello SD Experts, Please, is there a way to recover a default value for the batch of all posts in a Sale Order (SO). In fact I want to have a default value Z001 in the batch field of all post's of  SO type ZS01. is that possible? if so how the custom

  • Photo not showing up in Kens window.

    Hello, I have been working in Imovie with pictures and video. I am almost done. I went back to do some tweaking, (change times on pictures, trans) Now some of the pictures I need to change time on do not show up in the box. Its black. I am confused b

  • Ipod nano 6th generation wont connect to computer or itunes, but still charges

    I have an Ipod nano 6 that will not connect to my computer. It still charges however. I tried a new cord. I uninstalled and reinstalled itunes. I reset my computer and the ipod. I looked to see if it was a problem with my usb drivers and the ipod did

  • Location to download IPS software upgrade Version 7.1(5)E4

    Hi, In last month I found latest released IPS software version 7.1(5)E4 for IPS appliance 4260 on cisco site. However it is no more available over there now can I have exact download location of the software upgrade as I want to upgrade my device wit

  • PO LONG TEXT of Length 400+ char

    Hello ABAPers, I have a case where i want to update the PO_Long_Text field in MM02. The Text Editor  in the Po Long Text screen can take only 72 char per line and an internal tables variable to which I will import my actual long text of approx 400 ch