Current thread is not owner java как исправить

I assume you were confused by the wait() method name, thinking it may allow you to wait until exec() is finished, but really it’s not and has completely different purpose.

What I believe you wanted here is to call Process.waitFor() method:

try {
    Runtime runtime = Runtime.getRuntime();
    String cmd = new String(C:\abc.bat);
    process = runtime.exec(""" + cmd + """);
    process.waitFor();
} catch (Exception e) {
    e.printStackTrace();
}

which should do what you may originally expected — to wait until batch execution is finished.

On the other hand, wait() method in Java (which comes from Object.wait()) is related to multi-threading programming and to Java implementation of the monitor thread synchronization concept. Historically, it was put to the main Object.java class, so all classes inherit it and that’s what confusion may come from.

In your example it’s definitely not the right method to call. And the IllegalStateMonitor exception message you’re getting:

current thread is not owner

tries to give you an implicit hint on threads synchronization issue.
Though again, when you’re not using multi-threading in your code it may confuse you a lot and doesn’t provide any clue what could go wrong, as you not expecting it.

wait() method should only be called on the monitor objects, when you’re writing code inside of synchronized blocks or methods, e.g.:

private final List<Task> tasks = new ArraList<>();

private synchronized void waitForTasks() throws InterruptedException {
    // because 'synchronized' word used on method,
    // here monitor is the whole class, i.e. 'this'
    if (tasks.isEmpty()) {
        wait(); // method is called on the class itself, as it's the monitor object
    }
    doTasks();
}

or:

private final List<Task> tasks = new ArraList<>();

private void waitForTasks() throws InterruptedException {
    synchronized (tasks) { // monitor object is set to 'tasks' object
        if (tasks.isEmpty()) {
            tasks.wait();  // method is called on the monitor
        }
        doTasks();
    }
}

If you would like to get more information on monitor concept in Java, you can this nice article on the topic.

In this tutorial, we will learn IllegalMonitorStateException and when it is thrown with examples. We will also see how we can prevent our code from throwing this exception along with some of the best practices to follow in multithreaded applications.

  1. 1. Java IllegalMonitorStateException class
  2. 2. What causes IllegalMonitorStateException
  3. 3. Resolving IllegalMonitorStateException
  4. 4. Best Practices
  5. 5. Conclusion

IllegalMonitorStateException class present in java.lang package and has been there since Java version 1.0. It extends RuntimeException class; hence, it’s an unchecked exception and needs not to be declared in a method’s or a constructor’s throws clause.

Constructors defined in this class:

  • IllegalMonitorStateException(): Creates an instance of the IllegalMonitorStateException class, setting null as its message.
  • IllegalMonitorStateException(String message): Creates an instance of the IllegalMonitorStateException class, using the specified message.

2. What causes IllegalMonitorStateException

For inter-thread communication (in which 2 threads communicate with each other), threads have to use wait(), notify() and notifyAll() methods. Thread class inherits these methods from the Object class.

A Thread should acquire the object’s lock to call these methods on that object. If a Thread tries to call wait(), notify() and notifyAll() methods on an object without acquiring that object’s lock or outside of the synchronized block, the program throws IllegalMonitorStateException.

Let’s now look at an example of how a Thread raises IllegalMonitorStateException. In this example, we are going to create a Waiting Thread and a Notifying Thread.

  • WaitingThread calls the wait() method and enters into a waiting state until some other Thread calls notify() method and notifies it.
  • NotifyingThread calls the notify() method and notifies the waiting Thread to start processing again.
public class IllegalMonitorStateExceptionDemo
{

    //This object is used for synchronization among threads.
    public final static Object obj = new Object();
    
    public static class WaitingThread extends Thread {

        @Override
        public void run() {
            try {
                   //Calling wait() method outside of synchronized area
                    obj.wait();    // Raises IllegalMonitorStateException
                 }
                catch (InterruptedException ex) {
                    System.out.println(Thread.currentThread().getName() + " gets Interrupted");
                }
        }
    }
     
    public static class NotifyingThread extends Thread {

        @Override
        public void run() {
          try {
                    // Thread sleep for 5 sec
                    Thread.sleep(5000);
                    // Calling notify() outside of synchronized area                 
                    obj.notify();         // Raises IllegalMonitorStateException
                }
                catch (InterruptedException ex) {
                    System.err.println(Thread.currentThread().getName() + " gets Interrupted");
                }
        }
    }
}

Try running both threads to verify.

public static void main(String[] args) {
    WaitingThread waitingThread = new WaitingThread();
    NotifyingThread notifyingThread  = new NotifyingThread();

    waitingThread.start();
    notifyingThread.start();
}

We will get the IllegalMonitorStateException in the console.

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException: current thread is not owner
	at java.base/java.lang.Object.wait(Native Method)
	at java.base/java.lang.Object.wait(Object.java:338)
	at com.howtodoinjava.concurrency.IllegalMonitorStateExceptionDemo $WaitingThread.run(IllegalMonitorStateExceptionDemo.java:23)

Exception in thread "Thread-1" java.lang.IllegalMonitorStateException: current thread is not owner
	at java.base/java.lang.Object.notify(Native Method)
	at com.howtodoinjava.concurrency.IllegalMonitorStateExceptionDemo $NotifyingThread.run(IllegalMonitorStateExceptionDemo.java:39)

3. Resolving IllegalMonitorStateException

IllegalMonitorStateException resolves when a Thread calls wait(), notify() and notifyAll() methods on an object after acquiring that object’s lock means it should call these methods inside synchronized block only.

In the above example, if both Waiting & Notifying Threads call wait() and notify() in synchronized block then we won’t get IllegalMonitorStateException in our code.

So the correct way of calling these methods without this exception is as below,

  public static class WaitingThread extends Thread {

        @Override
        public void run() {
            try {
                    //Obtain lock using the synchronized keyword
                    synchronized(obj){
                        
                       //Calling wait() inside synchronized block
                        obj.wait();
                    }
                  }
                catch (InterruptedException ex) {
                    System.err.println(Thread.currentThread().getName() + " gets Interrupted");
                }
        }
  }

public static class NotifyingThread extends Thread {

        @Override
        public void run() {
          try {
                    Thread.sleep(5000);

                    //Obtain lock first
                     synchronized(obj){  
                        //Calling notify() inside synchronized block
                        obj.notify();
                     }
                }
                catch (InterruptedException ex) {
                    System.err.println(Thread.currentThread().getName() + " gets Interrupted");
                }
        }
}

Now if we run the program, it completes successfully.

4. Best Practices

  • Since Java version 1.5, we have java.util.concurrent package which contains various new concurrency classes and frameworks that make our work easy while working in a multithreaded environment.
  • For inter-thread communication, instead of using the old way of using wait() and notify() method, we can make use of BlockingQueue instead present in java.util.concurrent package.
  • BlockingQueue Interface represents a queue that is thread-safe to put into and take elements from while 2 Threads are communicating with each other, which in turn avoids any IllegalMonitorStateException as well.
  • Lock Interface and ReentrantLock class provide more control over the concurrency as compared with synchronized block. Using it, a Thread can try for a lock without waiting, eliminating the chances of a deadlock situation.
  • We can use other classes like CountDownLatch, CyclicBarrier, Exchanger, Phaser, SynchronousQueue in order to work with multiple threads in a multithreaded application.

5. Conclusion

In this article, we learned about IllegalMonitorStateException, what are the causes for this and how to prevent it in our code. We have also seen some of the best practices for using new concurrency classes that can help in avoiding the IllegalMonitorStateException.

Happy Learning !!

Sourcecode on Github

Почему current thread is not owner? Мьютекс захвачен !
Задачу решил, но не так как в правильном решении.
Что такое mail.wait mail.notify почему не просто notify?

synchronized (mail) {
    String name = Thread.currentThread().getName();
    try {
    while (mail.getText() == null) {
            wait();
    }
    long endTime = System.currentTimeMillis();
        System.out.format("%s MailServer received: [%s] in %d ms after start", name, mail.getText(), (endTime - startTime));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

An IllegalMonitorStateException is a runtime exception in Java that occurs in multithreaded applications. It indicates that the calling thread has attempted to wait on an object’s monitor, or attempted to notify other threads waiting on an object’s monitor, without owning the specified monitor.

Since the IllegalMonitorStateException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes IllegalMonitorStateException

When building multithreaded applications in Java, if a monitor needs to be synchronized on, the IllegalMonitorStateException is thrown to indicate a thread attempted to wait or to notify other threads waiting on that monitor, without owning it.

Therefore, this exception occurs if one of the wait(), notify() or notifyAll() methods of the Object class are called outside a synchronized block or method.

IllegalMonitorStateException Example

Here’s an example of an IllegalMonitorStateException, thrown when the wait() method is called outside a synchronized block:

class MyRunnable implements Runnable {
    public void run() {
        try {
            this.wait(100); // calling wait() without outside synchronized block
            System.out.println("Thread in runnable state");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class IllegalMonitorStateExceptionExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }
}

Since a thread must own a lock on the object’s monitor before calling the wait() method, calling it outside a synchronized block throws an IllegalMonitorStateException. Running the above code throws the exception:

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException: current thread is not owner
    at java.base/java.lang.Object.wait(Native Method)
    at java.base/java.lang.Object.wait(Object.java:321)
    at MyRunnable.run(IllegalMonitorStateExceptionExample.java:4)
    at java.base/java.lang.Thread.run(Thread.java:832)

How to Resolve IllegalMonitorStateException

The IllegalMonitorStateException can be resolved by calling the wait(), notify() and notifyAll() methods after acquiring an object lock, i.e. within a synchronized block or method.

The call to the wait() method in the earlier example can be placed inside a synchronized block to resolve the exception:

class MyRunnable implements Runnable {
    public void run() {
        synchronized (this) {
            try {
                this.wait(100);
                System.out.println("Thread in runnable state");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class IllegalMonitorStateExceptionExample {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }
}

Calling the wait() method within a synchronized block helps acquire a lock on the object monitor, which fixes the issue. Running the above code produces the correct output as expected:

Thread in runnable state

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

The illegalmonitorstateexception error is caused if the thread tries to call the methods on an object without acquiring the object’s lock. Methods are used for inter-thread communication.Illegalmonitorstateexception

You will learn the causes of the error in detail and how to solve them with the help of an expert’s advice. Keep reading to gain a better understanding.

Contents

  • Why Do I Get Illegalmonitorstateexception?
    • – Wait() Method
    • – Notify() And Notifyall() Methods
    • – Unlock() Method
    • – Newcondition Method()
  • How Do I Fix Illegalmonitorstateexception?
    • – Call Wait() From Synchronized Blocks or the Synchronized Method
    • – Call Notify() And Notifyall() From Synchronized Blocks
    • – Call Lock() Before You Call Unlock()
    • – Check if the Lock Is Held When Methods Are Called
  • FAQs
    • 1. Why Do I See Illegalmonitorstateexception: Current Thread Is Not Owner
    • 2. What Is java.lang.illegalmonitorstateexception Selenium?
    • 3. What Is The Function of Object Monitor in Java?
  • Conclusion

Why Do I Get Illegalmonitorstateexception?

You get Illegalmonitorstateexception when the thread tries to call the methods like wait(), notify(), notifyAll(), unlock(), and the NewCondition() method. In the case of the wait() method, if you do not call it from the synchronized blocks, then you will encounter this error in your program.

For two threads to communicate with each other or inter-thread communication, threads must use the methods. The thread class inherits these methods from the object class. Hence, a thread needs to acquire the object’s lock to call the given methods on that object. Let’s discuss what those methods are and how you will face the illegalmonitorstateexception error in java with the help of code examples.

– Wait() Method

If the method called wait() has been called by the thread but not from synchronized blocks or the synchronized method, then at runtime, you will face the error that says illegalmonitorstateexception. The code example has been given below to help you properly understand the illegalmonitorstateexception wait error.

class MyRunnable implements Runnable {

public void run() {

System.out.println(“MyRunnable,in run() method”);

try {

this.wait(1000); // calling wait() without acquiring object lock

// throws IllegalMonitorStateException

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(“Thread in runnable state after 1000 millisecs”);

}

}

public class IllegalMonitorStateExceptionExampleUsingWait {

public static void main(String[] args) {

MyRunnable myRunnable=new MyRunnable();

Thread thread1=new Thread(myRunnable,”Thread-1″);

thread1.start();

}

}

You will encounter the error below if you attempt to execute the code above.

MyRunnable,in run() method

Exception in thread “Thread-1” java.lang.IllegalMonitorStateException

at java.lang.Object.wait(Native Method)

at MyRunnable.run(IllegalMonitorStateExceptionExampleUsingWait.java:5)

at java.lang.Thread.run(Unknown Source)

– Notify() And Notifyall() Methods

You might face the error if the notify() or notifyAll() methods are not called from the synchronized block or synchronized method. If that is the problem with your code, then this is exactly why you are facing the error that says illegalmonitorstateexception.Illegalmonitorstate exception Causes

– Unlock() Method

If the current thread is not holding the lock, and it calls the unlock() methods, then you will be faced with the error that says illegalmonitorstateexception. The example code is given below to help you understand the illegalmonitorstateexception lock error better.

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class IllegalMonitorStateExceptionExampleUsingLock {

public static void main(String[] args) {

final Lock lock = new ReentrantLock();

new Thread(new Runnable() {

public void run() {

System.out.println(“Thread-1 is Waiting to acquire lock”);

//lock.lock();

lock.unlock(); // It will throw IllegalMonitorStateException

}

}, “Thread-1”) {

}.start();

}

}

In the case of such a code given above, you will face the error illegalmonitorstateexception. Let us take a look at the output of that code.

Exception in thread “Thread-1” Thread-1 is Waiting to acquire lock

java.lang.IllegalMonitorStateException

at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Source)

at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown Source)

at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source)

at IllegalMonitorStateExceptionExampleUsingLock$1.run(AvoidIllegalMonitorStateExceptionExampleUsingLock.java:14)

at java.lang.Thread.run(Unknown Source)

– Newcondition Method()

The ReEntrantLock’s method, named as newCondition method, can also throw the error illegalmonitorstateexception. The method returns a condition instance to be used with the Lock instance. Using the condition instances are same as using the notify(), notifyAll(), and wait() methods.

If the lock is not held when any condition waiting or signaling methods are called, you might face the illegalmonitorstateexception reentrantlock error.

How Do I Fix Illegalmonitorstateexception?

To fix the illegalmonitorstateexception error, you need to call wait() from synchronized blocks or the synchronized method, call notify() and notifyall() from synchronized blocks or the synchronized method, call lock () before you call Unlock(), and check if the lock Is held when methods are called.

We will now discuss all the solutions to the causes mentioned in the previous section. Keep reading to understand the solutions with the help of code examples.

– Call Wait() From Synchronized Blocks or the Synchronized Method

The only way you can solve the error problem is before you try calling the wait() method; you need to make sure that the thread should own lock on the object’s monitor. It means that the method wait() must be called from synchronized blocks or the synchronized method. That will resolve the error problem for you. Take a look at the code example given below to understand it better.

class MyRunnable implements Runnable {

public void run() {

synchronized (this) {

System.out.println(“MyRunnable,in run() method”);

try {

this.wait(1000); // calling wait() by acquiring object lock doesn’t

// throws IllegalMonitorStateException

System.out

.println(“Thread in runnable state after 1000 millisecs”);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

public class AvoidIllegalMonitorStateExceptionExampleUsingWait {

public static void main(String[] args) {

MyRunnable myRunnable=new MyRunnable();

Thread thread1=new Thread(myRunnable,”Thread-1″);

thread1.start();

}

}

You can see in the example given above that the error was resolved by calling the wait() from the synchronized block. You can compare the code in the problem and the solution to understand better. The output of the resolved code looks like the following.

MyRunnable,in run() method

Thread in runnable state after 1000 millisecs.

– Call Notify() And Notifyall() From Synchronized Blocks

Just like the wait() method, It is essential that before you call the notify() or notifyAll() methods, the thread must own the lock on the object’s monitor. Hence, you must always call the notify() and notifyAll() from synchronized blocks or the synchronized method. That will help you resolve the error in case you forgot to do as stated.Illegalmonitorstate exception Fixes

– Call Lock() Before You Call Unlock()

To resolve the error problem in the code example, prior to calling the unlock method (), you must first call the lock method () on the current thread. By doing that, your error illegalmonitorstateexception will be resolved. Let us look at the code to see how the error is resolved by calling the lock () method before the unlock() method.

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class AvoidIllegalMonitorStateExceptionExampleUsingLock {

public static void main(String[] args) {

final Lock lock = new ReentrantLock();

new Thread(new Runnable() {

public void run() {

System.out.println(“Thread-1 is Waiting to acquire lock”);

lock.lock();

System.out.println(“Thread-1 has acquired lock.”);

lock.unlock();

System.out.println(“Thread-1 has released lock.”);

}

}, “Thread-1”) {

}.start();

Note that the code has been changed slightly by calling the lock () method before the unlock() method. Now take a look at the output.

Thread-1 is Waiting to acquire lock

Thread-1 has acquired lock.

Thread-1 is about to release lock.

You can see that the error illegalmonitorstateexception unlock has been resolved successfully in the output.

– Check if the Lock Is Held When Methods Are Called

If you want to resolve the illegalmonitorstateexception thrown by the newCondition() method, you need to check if the lock is held when the condition waiting or signaling methods are called. Make sure that the above condition is fulfilled. If it is, you will not face this annoying error again.

FAQs

1. Why Do I See Illegalmonitorstateexception: Current Thread Is Not Owner

You see Illegalmonitorstateexception: Current Thread Is Not Owner when you try to wait on the web element. The method wait(n) causes the thread to wait for the n number of seconds, so it is important to ensure that another thread is not using the web element.

If you want to ensure that the web element object is accessed only one thread at a time, you need to enclose WebElement.wai() in a synchronized block.

2. What Is java.lang.illegalmonitorstateexception Selenium?

The java.lang.illegalmonitorstateexception error is thrown as an indication that a thread attempted to wait on the object’s monitor or notify the other threads waiting on the object’s monitor without owning the monitor specified. The open-source Selenium tool offers a single interface that may help you create test scripts.

3. What Is The Function of Object Monitor in Java?

The function of object monitor in Java is to control the concurrent access of a method in an object. If any concurrent threads call a method simultaneously, then only one thread can execute this method. The monitor object does not have its thread of control compared to the active object.

Conclusion

All the possible causes of the error have been discussed, along with their possible solutions. Let us now summarize the article into essential points for you to remember.

  • The illegalmonitorstateexception is a common java error. You will see this error if the thread tries to call the methods on an object without acquiring the object’s lock.
  • A thread needs to acquire the object’s lock to call the methods on that object.
  • For two threads to communicate with each other or inter-thread communication, threads must use the methods called notify(), notifyAll(), and wait().
  • A monitor object pattern is used to manage concurrent access to a method in an object.
  • If some concurrent threads call a method simultaneously, then only one thread can execute this method.

In this article, you have learned all the details about the reasons for the error illegalmonitorstateexception. You can always refer to this article in case you face the same error again or have any questions regarding the topic.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Как найти где подсос воздуха в машине
  • Как найти американских друзей в снэпчате
  • Как найти буфер обмена на телефоне андроид
  • Как найти клад на горе
  • Как найти друзей в телеграмме без номера