IllegalMoniterStateException - java

I get an illegalMoniterStateException whenever I call wait() and notify() or notifyAll(). The javadoc says that I should be getting that exception if my 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."
However, here is an example of the code where I call those methods above.
//note that doSomething will be called by a thread from another class, not this one
public void doSomething(){
while(objectsCurrentlyDoingSomething() >= thisClass'sCapacity){
synchronized(objectLock){ //objectLock is created at top of class like this:
wait(2000); //private static final Object objectLock = new Object();
}
}
//rest of code
}
Then later on I release one threads hold on that lock by saying that if object finishes, decreases number of objects currently using and notify().
....object finished......
synchronized(objectLock){
notify();
}

You need to call wait, and notify on objectLock.
e.g.
objectLock.wait()
It you just call wait() you are calling it on this.

As noted by z5h, your calls to wait() and notify() should be made on the objectLock object:
//note that doSomething will be called by a thread from another class, not this one
public void doSomething(){
while(objectsCurrentlyDoingSomething() >= thisClass'sCapacity){
synchronized(objectLock){ //objectLock is created at top of class like this:
objectLock.wait(2000); //private static final Object objectLock = new Object();
}
}
//rest of code
}
and
....object finished......
synchronized(objectLock){
objectLock.notify();
}

Related

How to kill a Thread in the queue that is waiting to execute a method in Java

I have a common method in the main class that is going to be executes by the main thread and also another thread on some condition. The code structure looks like this
class Main {
public static void main(){
...some code
if(..on some condition)
methodA()
}
public void methodA(){
synchronized(this){
..some code
}
}
}
class AnotherThread implements Runnable{
public AnotherThread(){
Main obj = new Main();
}
#Override
public void run(){
if(..on some condition)
obj.methodA()
}
}
This methodA() is synchronized as mentioned in the code. Let us assume that the condition in both the threads evaluates to true and the methodA() is called on the same time. In this case whichever thread that comes first will execute the methodA() first. But the other thread in the waiting state waiting to execute the method. But I want to kill that thread and limit my execution to just one time (i.e. whichever thread comes first must alone execute the method and not the other).
Is this possible. If so how can it be done.
Thanks in advance
Your code won't work, because you are using this (object level lock) in synchronized block and both the threads are using separate object so both will run without waiting.
You can have class level lock and use that in synchronized block like below:
private static final Object LOCK = new Object();
public void methodA(){
synchronized(LOCK){
..some code
}
}
Or use same object in both the thread.
You can't kill the thread, what you can do is have one semaphore (or any variable) and one condition inside your synchronized block. Check if semaphore is set then return else execute the code and set the semaphore before exiting the method.
private static boolean condition = false;// you can you semaphore too class level variable
public void methodA(){
synchronized(LOCK){
if(condition){ return;}// returning if already executed
..some code
// Set condition to true so then again it should not run
condition = true;
}
}
you can't kill the thread in the queue but you can blocked the queue by using poison pill
you can use singleThreadExecutorPool to perform the task, it will allow to execute the thread in sequentially.

notifyAll() throws IllegalMonitorStateException

I am designing two threads: one has to get the name of players, and the second thread has to wait for the name being set in order to continue, but notify() all in the first thread is throwing the IllegalMonitorStateException error.
private NameFecth nameFetch;
private UseName useName;
private Object nameSetLock;
public static void method{
nameSetLock = new Object()
nameFetch = new NameFetch(nameSetLock);
useName = new UseName(nameSetLock);
Thread nameFetchThread = new Thread(nameFetch);
nameFetchThread.start();
Thread useNameThread = new Thread(useName);
useNameThread.start();
}
public class NameFetch implements Runnable{
/*variables and constructers*/
public void run(){
/*get name and set the variable somehow*/
synchronized(nameSetLock){
notifyAll();
}
}
}
public class UseName implements Runnable{
/*variables and constructers*/
public void run(){
while(!nameBeenSet){
synchronized(nameSetLock){
try{
wait();
}catch(InterruptedException e) {}
}
}
}
What have I done wrong?
You're calling wait and notify without synchronizing on the thing you're waiting on or notifying. As documented in Object.notifyAll:
Throws:
IllegalMonitorStateException - if the current thread is not the owner of this object's monitor.
So this:
synchronized(nameSetLock){
notifyAll();
}
should be:
synchronized(nameSetLock){
nameSetLock.notifyAll();
}
... and ditto for wait. Note that your current code wouldn't even compile as you're using syncronized rather than synchronized, which suggests that you didn't post your actual code. It's possible that in typing out the code you've actually changed the problem - in which case you should edit your question to be more representative.
It looks like your issue that you are using the lock incorectly. You synchronized block is on nameSetLock and you are calling your notifyall on your NameFetch object instance (which is the sayme a synchronized(this).
You should do
nameSetLock.wait when you want to use the lock and nameSetLock.notifyAll to notify.
From the JavaDoc of IllegalStateException
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.
You are trying to invoke the wait() and notifyAll() without having that object lock.
Please try what #Jon has suggested it will work.
This happens to me when I forgot to add the synchronized in the method call.

If I synchronized two methods on the same class, can they run simultaneously?

If I synchronized two methods on the same class, can they run simultaneously on the same object? For example:
class A {
public synchronized void methodA() {
//method A
}
public synchronized void methodB() {
// method B
}
}
I know that I can't run methodA() twice on same object in two different threads. same thing in methodB().
But can I run methodB() on different thread while methodA() is still running? (same object)
Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).
In the example methodA and methodB are instance methods (as opposed to static methods). Putting synchronized on an instance method means that the thread has to acquire the lock (the "intrinsic lock") on the object instance that the method is called on before the thread can start executing any code in that method.
If you have two different instance methods marked synchronized and different threads are calling those methods concurrently on the same object, those threads will be contending for the same lock. Once one thread gets the lock all other threads are shut out of all synchronized instance methods on that object.
In order for the two methods to run concurrently they would have to use different locks, like this:
class A {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void methodA() {
synchronized(lockA) {
//method A
}
}
public void methodB() {
synchronized(lockB) {
//method B
}
}
}
where the synchronized block syntax allows specifying a specific object that the executing thread needs to acquire the intrinsic lock on in order to enter the block.
The important thing to understand is that even though we are putting a "synchronized" keyword on individual methods, the core concept is the intrinsic lock behind the scenes.
Here is how the Java tutorial describes the relationship:
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
The purpose of locking is to protect shared data. You would use separate locks as shown in the example code above only if each lock protected different data members.
Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
In your case, the methods(instance) are of same class. So when ever a thread enters into java synchronized method or block it acquires a lock(the object on which the method is called). So other method cannot be called at the same time on the same object until the first method is completed and lock(on object) is released.
In your case you synchronized two method on the same instance of class. So, these two methods can't run simultaneously on different thread of the same instance of class A. But they can on different class A instances.
class A {
public synchronized void methodA() {
//method A
}
}
is the same as:
class A {
public void methodA() {
synchronized(this){
// code of method A
}
}
}
Think of your code as the below one:
class A {
public void methodA() {
synchronized(this){
//method A body
}
}
public void methodB() {
synchronized(this){
// method B body
}
}
So, synchronized on method level simply means synchronized(this).
if any thread runs a method of this class, it would obtain the lock before starting the execution and hold it until the execution of the method is finished.
But can I run methodB() on different thread while methodA() is still
running? (same object)
Indeed, it is not possible!
Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.
From oracle documentation link
Making methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads
This will answer your question: On same object, You can't call second synchronized method when first synchronized method execution is in progress.
Have a look at this documentation page to understand intrinsic locks and lock behavior.
Just to all clarity, It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because one is having object level lock and other class level lock.
The key idea with synchronizing which does not sink in easily is that it will have effect only if methods are called on the same object instance - it has already been highlighted in the answers and comments -
Below sample program is to clearly pinpoint the same -
public class Test {
public synchronized void methodA(String currentObjectName) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA in");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA out");
}
public synchronized void methodB(String currentObjectName) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB in");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB out");
}
public static void main(String[] args){
Test object1 = new Test();
Test object2 = new Test();
//passing object instances to the runnable to make calls later
TestRunner runner = new TestRunner(object1,object2);
// you need to start atleast two threads to properly see the behaviour
Thread thread1 = new Thread(runner);
thread1.start();
Thread thread2 = new Thread(runner);
thread2.start();
}
}
class TestRunner implements Runnable {
Test object1;
Test object2;
public TestRunner(Test h1,Test h2) {
this.object1 = h1;
this.object2 = h2;
}
#Override
public void run() {
synchronizedEffectiveAsMethodsCalledOnSameObject(object1);
//noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(object1,object2);
}
// this method calls the method A and B with same object instance object1 hence simultaneous NOT possible
private void synchronizedEffectiveAsMethodsCalledOnSameObject(Test object1) {
try {
object1.methodA("object1");
object1.methodB("object1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// this method calls the method A and B with different object instances object1 and object2 hence simultaneous IS possible
private void noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(Test object1,Test object2) {
try {
object1.methodA("object1");
object2.methodB("object2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Notice the difference in output of how simultaneous access is allowed as expected if methods are called on different object instances.
Ouput with noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects() commented -the output is in order methodA in > methodA Out .. methodB in > methodB Out
and Ouput with synchronizedEffectiveAsMethodsCalledOnSameObject() commented -
the output shows simultaneous access of methodA by Thread1 and Thread0 in highlighted section -
Increasing the number of threads will make it even more noticeable.
You are synchronizing it on object not on class. So they cant run simultaneously on the same object
No it is not possible, if it were possible then both method could be updating same variable simultaneously which could easily corrupt the data.
Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock.
So if you want to run simultaneously, create two objects and then try to run by using of those object reference.
Two different Threads executing a common synchronized method on the single object, since the object is same, when one thread uses it with synchronized method, it will have to verify the lock, if the lock is enabled, this thread will go to wait state, if lock is disabled then it can access the object, while it will access it will enable the lock and will release the lock
only when it's execution is complete.
when the another threads arrives, it will verify the lock, since it is enabled it will wait till the first thread completes his execution and releases the lock put on the object, once the lock is released the second thread will gain access to the object and it will enable the lock until it's execution.
so the execution will not be not concurrent, both threads will execute one by one, when both the threads use the synchronized method on different objects, they will run concurrently.

synchronized object not locked by thread before notifyAll()

I want to have a boolean to notify some sections of the system that a specific service started.
For some strange reason I'm getting the error java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll().
What is strange is that the notifyAll() is inside a synchronized block that takes control over the object that I call notifyAll() on.
My class starts like this:
public class MyService {
public static Boolean notifier = Boolean.valueOf(false);
#Override
public void start() {
synchronized (MyService.notifier) {
MyService.notifier = Boolean.valueOf(true);
MyService.notifier.notifyAll();
}
}
#Override
public void stop() {
synchronized (MyService.notifier) {
MyService.notifier = Boolean.valueOf(false);
MyService.notifier.notifyAll();
}
}
...
}
I'm working on an android application. I don't think it should affect anything, but I'm complementing the question with that comment in case that affects the way that java works.
Why am I getting the exception if the object is locked inside a synchronized block?
The line
MyService.notifier = Boolean.valueOf(true);
swaps out the object you're locking on, it overwrites the variable with a reference to a new object. So the object you acquired the lock on upon entering the block is not the same one that you're calling notifyAll on. All notifyAll knows is it hasn't acquired the lock on the object it's being called on, which is the new object created after the synchronize block was entered.
All the threads need to be using the same lock. Like Ian Roberts said, the lock belongs to the object. If you overwrite the object you have a new lock.

Why is this thread allowing another one to access its synchronized method?

I have the following codes. I expected one thread to execute its synchronized method completely and then allow another one to access the same method. However, this is not the case.
public class Threads {
/**
* #param args
*/
public static void main(String[] args) {
//Thread Th = new Threads();
Thread th = new Thread (new thread1 ());
th.start();
Thread th1 = new Thread (new thread1 ());
th1.start();
}
}
class thread1 implements Runnable{
String name = "vimal";
public void run() {
System.out.println("Runnable "+this.name);
setNAme("Manish");
}
public synchronized void setNAme(String name){
try {
System.out.println("Thread "+Thread.currentThread().getName());
wait(1000);
this.name = name;
System.out.println("Name "+this.name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have one output as
Runnable vimal
Thread Thread-0
Runnable vimal
Thread Thread-1
Name Manish
Name Manish
What is the use of synchronized here and how do I make my method to run completely before another accesses it?
synchronized has no effect here because you are not synchronizing on the same object in both cases. When applied to an instance method, the synchronized keyword causes the method to be synchronized on this. So in each case you are synchronizing on the instance of thread1, and there are two of those.
The more interesting test would be when you run the same instance of thread1 in two threads simultaneously. In that case, calling wait(1000) is a very bad thing to do because (as documented) it releases the lock on this. You want to use Thread.sleep(1000) instead in your code.
If you need to have two instances of thread1, you need to synchronize on some shared object, possibly like this:
private static final Object lockObject = new Object();
public void setName(String newName) {
synchronized(lockObject) {
doSetName(newName);
}
}
You will have to remove the call to wait(1000). It looks like what you actually want is a call to Thread.sleep(1000), if you simply want to pause the current thread, this does not release ownership of any monitors.
From the javadoc for Object.wait().
This method causes the current thread (call it T) to place itself in
the wait set for this object and then to relinquish any and all
synchronization claims on this object. Thread T becomes disabled for
thread scheduling purposes and lies dormant until one of four things
happens:
Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be
awakened.
Some other thread invokes the notifyAll method for this object.
Some other thread interrupts thread T.
The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into
consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and
re-enabled for thread scheduling. It then competes in the usual manner
with other threads for the right to synchronize on the object; once it
has gained control of the object, all its synchronization claims on
the object are restored to the status quo ante - that is, to the
situation as of the time that the wait method was invoked. Thread T
then returns from the invocation of the wait method. Thus, on return
from the wait method, the synchronization state of the object and of
thread T is exactly as it was when the wait method was invoked.
UPDATE: As has been mentioned in other answers, you are not synchronizing on the same object. Once you do, you will still suffer the same output, due to the issue I have mentioned. You will need to fix both for your desired results.
The output is correct, you are creating to independent threads that do not share any data. Thus both threads start with first string, and after some time, the string is changed and printed.
You're creating 2 thread1 objects. They each have their own setNAme method. Synchronized methods only synchronize on the object, not the class. Unless the method is static.
You have two Threads here with independent name variables and independent monitors, so each Thread is only accessing its own members. If you want to have the threads interact with each other you'll have to implement such an interaction.
you are creating two separate thread1 objects and running them. Each thread has it's own copy of the name variable as well as the setName function. Make them both static and you will see the effects of synchronization.
You are locking on two different instance of the objects where you dont need any synchronization at all. You need to synchronize only if you are working on a shared data. I think you meant to write a test like the below.
If you test this, you will realize that the second thread will wait until the first thread is completed with the synchronized method. Then take out the synchronized word and you will see both threads are executing at the same time.
public class SynchronizeTest {
public static void main(String[] args) {
Data data = new Data();
Thread task1 = new Thread(new UpdateTask(data));
task1.start();
Thread task2 = new Thread(new UpdateTask(data));
task2.start();
}
}
class UpdateTask implements Runnable {
private Data data;
public UpdateTask(Data data) {
this.data = data;
}
public void run() {
try {
data.updateData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Data {
public synchronized void updateData() throws InterruptedException {
for (int i = 0; i < 5; i++) {
Thread.sleep(5000);
System.out.println(i);
}
}
}

Categories