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
//...

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() 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.

  • Closing lid to suspend and then resuming causes capslock and shift key failures

    When I close the lid of my NB205, the computer enters hibernate.  When I open the lid and press the power key to resume, the computer starts back up but the caps lock key light is on. The keyboard responds the same as if the caps lock were on and the shift key were depressed at the same time.  Typing any letter results in a lower case.  Typing on the upper row of numbers produces the symbols (same as when shift key is depressed).  Also, my bluetooth mouse is not functional but the cursor can be moved using the keypad.
    By pressing the caps lock key a couple of times I can get the caps lock key light to go off.  Then the keyboard still functions like the shift key is depressed - producing capital letters plus symbols for the upper row.  I have to press the shift key a couple of times to fix that and then press Fn+F8 to restore bluetooth to get the computer to work correctly.  I tried changing the lid suspend action to Standby in lieu of Hibernate but the result was the same.  I do not have these problems when resuming from hibernate or standby if I enter them using the start/shutdown commands.
    The computer worked fine for the first two months before this began. I have tried scanning with McAfee virus scanner and have restored the system to a restore point well before the problems began but nothing helps. Does anyone have any ideas I can try before I return this under the warranty?

    VPN-User,
    Ok - I see the list of issues and will ensure our X300 specialist takes a look at it.   
    Please do understand that while you have put together a very coherent list, I try to ensure priority to threads in which multiple customers are focused on a single issue, as we deliver the most benefit to the community in working on those.   This forum is primarly a peer to peer discussion forum rather than a Lenovo chat / tech support where we try to solve each and every issue put forth.
    Individuals with a long list of issues on a particular machine may find benefit from either contacting technical support and working through their list, or publishing it as you have done and wait for other users of the same system to share their experiences.
    Thanks for your patience
    Mark
    ThinkPads: S30, T43, X60t, X1, W700ds, IdeaPad Y710, IdeaCentre: A300, IdeaPad K1
    Mark Hopkins
    Program Manager, Lenovo Social Media (Services)
    twitter @lenovoforums
    English Community   Deutsche Community   Comunidad en Español   Русскоязычное Сообщество

  • Thread.sleep and Thread.yield

    hi,
    anyone knows the difference between these 2 methods ?
    so far as i can see, the only diff is that sleep takes in an argument (time in millis) whereas yield does not.
    also, both methods hold on to the locks and dont give them up.
    pls comment

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#sleep(long)
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#yield()
    pretty clear...

  • Thread.yield() and Thread.sleep(), what's the difference

    Folks'es,
    can anyone enlighten me, as to the difference between yield() and sleep() in the Thread class?
    i know, with sleep, one can specify the amount of time to sleep, but does that mean the thread yields for that amount of time?
    if i use yield(), how long will my thread stop running?
    any information is appreciated
    thomas

    Thread.yield() is used to give other threads a chance to get a processor time slice, according to the thread dispatcher rules. If there are no other threads ready to run, the current thread will gain the processor again.
    Thread.sleep() will always release the processor for at least the amount of time specified, even if there are no other threads requesting it.

  • Process and threads

    Dear community
    Very kindly pleasant about information that is fiber in thread process and threads it interface between user and application ?
    is this answer on user ask in application run ?
    About any advises who concerns this matter , please .

    Hello RB_1.
    You can find more informations about fibers
    here and
    here on the MSDN Library.
    Bye.
    Luigi Bruno
    MCP, MCTS, MOS, MTA

  • Threads minimum vs Threads Count

    Hi,
    What's the difference in teh execute queue between threads minimum and
    threads count? Any comments will help!
    Docs say:
    Thread Count: Specify the number of threads assigned to this queue. If
    you do not need to use more than 15 threads (the default) for your work,
    do not change the value of this attribute.
    Thread Minimum:
    Specify the minimum number of threads that WebLogic Server should
    maintain in this execute queue to prevent unnecessary overflow
    conditions. By default, the Threads Minimum is set to 5
    I don't undersatnd what "maintain in this execute queue" means?
    Obviuosly, there will be 15 threads assigned to the execute queue.
    When the "queue lengthh threshold" is reached, "Thread Increase" will be
    added to number of threads, until a maximum of "Thread Maximum".
    I don't know how "Threads Minimum" plays a role.
    Thanks!
    Q

    Don't run into troubles, and don't misuse threads, the only thing that decides when your thread will execute is the Thread-scheduling system (which is part of the Java system) not you. So, you never must call run() to execute your thread, instead you always must use start(). The call of start() actually makes the scheduling-system to pay attention to your thread, and the calling of start() more than once will not have effect.

  • Suspend and Resume a certain thread

    The question is quite simple.
    How do I suspend a thread, and then wake him up from another thread?
    I can't use wait and notify, because the idea is to have a list of suspended thread, and wake up
    only one of them from another running thread, using a certain policy.
    The idea would be to do something like
    Thread 1,2,3,4 etc...
    1.Save thread id, or thread object in the list
    2. Suspend the thread
    Thread N
    1.Pick up a thread to wake up using a certain policy
    2.Pop out the thread from the list
    3.wake him up.
    How do I do that in Java? If possible..
    Thanks,
    Salvo

    Basically the new object created is placed into a list, and then
    from another method, I call notify on one of the object stored in the list,
    so what I expect is to wake up the thread who initially call the wait on the very
    same object.
    By adding making display the stack track into the exception handler, I realized
    that the wait actually fails with the following.
    java.lang.IllegalMonitorStateException
            at java.lang.Object.wait(Native Method)
            at java.lang.Object.wait(Object.java:485)
            at SemaphoreFifo.Down(SemaphoreFifo.java:58)
            at Cliente.run(Cliente.java:29)I looked up for this exception and found
    Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
    By owning, does it mean it has to be a member of the thread class?

  • Halt/Reboot fails if triggered after Suspend and Resume

    I'm using arch linux with gnome-shell and pm-utils. Halt/Reboot works alright normally, but when the sytem suspends and resumes, and then is halted/rebooted, the same fails.
    The screen shows an indication (message on console) that it's halting/rebooting, but it gets stuck there. There aren't any indication of failures/errors.
    Is there someone else facing the same problem? The cause? I'll be happy to give any relavant information required for this matter, in the form of system information or any logs,
    but at this point i'm not sure what would be relavant.

    Sorry this seems to be an existing issue in the forum: https://bbs.archlinux.org/viewtopic.php?id=113985
    Will update if any of the suggestion in the above mentioned thread fixes the problem.

  • Difference between LockSupport.parkUntil and Thread.sleep method

    Hi
    Could someone please explain the difference between LockSupport.parkUntil and Thread.sleep methods.
    Thanks in advance.

    javaLearner wrote:
    The thing that I am trying to understand is - the difference / correlation between the two methods mentioned.
    In the javadoc, there is a mention of correlation between the LockSupport methods park, unpark and the Thread methods suspend, resume - but not park and sleep.Then that suggests that there isn't any difference /correlation -- whatever you meant by that. Perhaps your question is like asking for the difference between a fish and a bicycle.
    Also, I would like to understand the statement
    These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. (from the javadoc)Again, you're going to have to explain what you don't understand about it.

  • 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.

  • 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 count higher than max worker threads... Large number of suspended worker threads

    I have a SQL 2012 SP2 server that is getting High Thread count alerts in SCOM.  looking into the issue I found some interesting things that I am now at a loss for.  I have been searching around for a few hours now and havent found much other than
    making it more confusing.  I found this MSDN blog:
    Are my actual worker threads exceeding the sp_configure 'max worker threads' value?
    Running through that I found some interesting things.
    -Max worker threads is set to default for x64 of 512 threads
    running a thread count query found 547 current worker threads:
    SELECT
    SUM(current_workers_count) as [Current worker thread] FROM sys.dm_os_schedulers
    Taking it a step further found that there was 523 worker threads in a suspended state with a last_wait_type of MISCELLANEOUS:
    select is_preemptive,state,last_wait_type,count(*) as NumWorkers from sys.dm_os_workers
    Group by state,last_wait_type,is_preemptive
    order by count(*) desc
    is_preemptive    state    last_wait_type    NumWorkers
    0    SUSPENDED    MISCELLANEOUS    523
    This is not yet a production server, no one is connecting to the database and the front end software application is not being used on this server yet.  Essentially this is just an idle database server so I thought it might be a fluke, so I restarted
    the sql services and the thread counts cleared.  I left it alone and overnight the high thread count alert popped back up.  I looked at it again this morning and the exact same thing happend.  Same number of suspended workers etc and total worker
    threads of 523 and 547 respectively.
    Other than the one article I have found above I have not been able to find anything to help explain this or what the heck suspended miscellaneous worker threads are.  Any help would be appreciated...Thanks!

    Hello,
    Please run the following query. The text column should tell us what is running.
    SELECT
     task.task_address,
     task.parent_task_address,
     task.task_state,
     REQ.request_id,
     REQ.database_id,
     REQ.session_id,
     REQ.start_time,
     REQ.command,
     REQ.connection_id,
     REQ.task_address,
     QUERY.text
    FROM
    SYS.dm_exec_requests
    req
    INNER
    JOIN sys.dm_os_tasks
    task on
    req.task_address
    = task.task_address
    or req.task_address
    = task.parent_task_address
    Cross
    apply sys.dm_exec_sql_text
    (req.sql_handle)
    as query
    WHERE
    req.last_wait_type
    = 'MISCELLANEOUS'
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Problem with StatelessConnectionPool and Threads on Windows XP

    I am trying to use a StatelessConnectionPool in a multithreaded app under Windows using 10g. The problem is that when my application is exiting and I go to terminate the StatelessConnectionPool, I get an access violation inside Environment::terminateStatlessConnectionPool.
    A short program that demonstrates the problem is at the end of this post. One thing I have noticed is that by calling terminateConnection inside the thread instead of releaseConnection the problem goes away. However, performance really degrades. Thanks in advance.
    #include <windows.h>
    #include <occi.h>
    #include "RegisterDataMappings.h"
    #include "Consumers.h"
    #include "Thread.h"
    using namespace oracle::occi;
    Environment* env = NULL;
    StatelessConnectionPool* connPool = NULL;
    //Derived from opur Thread class
    class TestThread : public Thread
    public:
         TestThread(void){}
    protected:
         //get an object 10 times, sleeping every 500 msecs in between
         virtual DWORD run(void)
              printf("Thread 0x%08x Enter...\n", GetCurrentThreadId());
              Sleep(500);
              int i = 0;
              while(i < 10)
                   try
                        Connection* conn = connPool->getConnection();
                        Statement* stmt = conn->createStatement("select Ref(c) from consumers c where pid = 7038878582");
                        ResultSet* rs = stmt->executeQuery();
                        if(rs->next())
                             Ref<Consumers> consumer = rs->getRef(1);
                             printf("Thread 0x%08x #%d - %.0f\n", GetCurrentThreadId(), i+1, (double)consumer->getconsumerid());
                        stmt->closeResultSet(rs);
                        conn->terminateStatement(stmt);
                        connPool->releaseConnection(conn);
                        //connPool->terminateConnection(conn);
                        Sleep(500);
                        ++i;
                   catch(SQLException& sql)
                        printf("Oracle exception: %s\n", sql.getMessage().c_str());
              printf("Thread 0x%08x Leave...\n", GetCurrentThreadId());
              return 0;
    //Helper function to create a connection
    void createConnection(void)
         env = Environment::createEnvironment((Environment::Mode)(Environment::OBJECT|Environment::THREADED_MUTEXED));
         RegisterDataMappings(env);
         connPool = env->createStatelessConnectionPool("user", "pass", "orcldev", 10, 10, 0, StatelessConnectionPool::HOMOGENEOUS);
    //Helper function to terminate a connection
    void terminateConnection(void)
         env->terminateStatelessConnectionPool(connPool);
         Environment::terminateEnvironment(env);
    int main(int argc, char* argv[])
         try
              //Connect to the database
              createConnection();
              //Create 10 threads and wait for them to complete
              const int numThreads = 10;
              HANDLE handles[numThreads];
              for(int i = 0; i < numThreads; i++)
                   TestThread* thread = new TestThread;
                   thread->start();
                   handles[i] = thread->getThreadHandle();
              WaitForMultipleObjects(numThreads, handles, TRUE, INFINITE);
              //Clean up
              terminateConnection();
         catch(SQLException& sql)
              printf("SQLException caught: %s\n", sql.getMessage().c_str());
         return 0;

    When I search MetaLink for bug 4183098, it says there's nobug 4183098. Any information on this?

Maybe you are looking for