synchronised block and synchronised methods of the same instance - java

I am a bit confused about synchronized-blocks in Java.
If one thread enters a synchronized-block of an instance of a class, can other threads use synchronized-methods of the same instance of the same class?
void myMain() {
synchronized(this) {
while(suspendFlag)
wait();
}
}
}
synchronized void mysuspend() {
suspendFlag = true;
}

synchronized void mysuspend(){
suspendFlag = true;
}
is equivalent to
void mysuspend(){
synchronized(this) {
suspendFlag = true;
}
}
So in your code it is not possible that one thread enters a synchronized block of an instance of a class and other threads use synchronized method mysuspend()

Yes, because they are independently callable.
A thread is not attached to a class or an instance of it. Each method of a class may be called independently from different threads.
What can limit this independence are synchronized methods. They are shortcuts for synchronized(this) {...} as method body.
Whenever a synchronized block is entered, the monitor on the associated instance is held.
A wait() frees the monitor on the surrounding synchronized block again, so other synchronized blocks can be executed.
There is a problem with your code: wait() will wait until a notify() on the monitor is called. But in your code neither a notify() is called, nor has the wait() a timeout.
Your while(suspendFlag) wait(); will then wait forever...

Related

my own blocking queue for producer consumer [duplicate]

I am using multi-threading in java for my program.
I have run thread successfully but when I am using Thread.wait(), it is throwing java.lang.IllegalMonitorStateException.
How can I make a thread wait until it will be notified?
You need to be in a synchronized block in order for Object.wait() to work.
Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.
EDIT
I assumed you meant Object.wait() as your exception is what happens when you try to gain access without holding the objects lock.
wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.
Although all Java objects have monitors, it is generally better to have a dedicated lock:
private final Object lock = new Object();
You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:
private static final class Lock { }
private final Object lock = new Lock();
In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).
synchronized (lock) {
while (!isWakeupNeeded()) {
lock.wait();
}
}
To notify:
synchronized (lock) {
makeWakeupNeeded();
lock.notifyAll();
}
It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.
I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...
Please read this definition of illegalMonitorException again and again...
IllegalMonitorException is 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.
This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....
1> wait on an object's monitor without owning the specified monitor.
2> notify other threads waiting on an object's monitor without owning the specified monitor.
Some might have got their answers... who all doesn't, then please check 2 statements....
synchronized (object)
object.wait()
If both object are same... then no illegalMonitorException can come.
Now again read the IllegalMonitorException definition and you wont forget it again...
Based on your comments it sounds like you are doing something like this:
Thread thread = new Thread(new Runnable(){
public void run() { // do stuff }});
thread.start();
...
thread.wait();
There are three problems.
As others have said, obj.wait() can only be called if the current thread holds the primitive lock / mutex for obj. If the current thread does not hold the lock, you get the exception you are seeing.
The thread.wait() call does not do what you seem to be expecting it to do. Specifically, thread.wait() does not cause the nominated thread to wait. Rather it causes the current thread to wait until some other thread calls thread.notify() or thread.notifyAll().
There is actually no safe way to force a Thread instance to pause if it doesn't want to. (The nearest that Java has to this is the deprecated Thread.suspend() method, but that method is inherently unsafe, as is explained in the Javadoc.)
If you want the newly started Thread to pause, the best way to do it is to create a CountdownLatch instance and have the thread call await() on the latch to pause itself. The main thread would then call countDown() on the latch to let the paused thread continue.
Orthogonal to the previous points, using a Thread object as a lock / mutex may cause problems. For example, the javadoc for Thread::join says:
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?
Are you calling Thread.wait() from within the thread, or outside it?
I ask this because according to the javadoc for IllegalMonitorStateException, it is:
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.
To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:
private static final class Lock { }
private final Object lock = new Lock();
#Test
public void testRun() {
ThreadWorker worker = new ThreadWorker();
System.out.println ("Starting worker");
worker.start();
System.out.println ("Worker started - telling it to wait");
try {
synchronized (lock) {
worker.wait();
}
} catch (InterruptedException e1) {
String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
System.out.println (msg);
e1.printStackTrace();
System.out.flush();
}
System.out.println ("Worker done waiting, we're now waiting for it by joining");
try {
worker.join();
} catch (InterruptedException ex) { }
}
In order to deal with the IllegalMonitorStateException, you must verify that all invocations of the wait, notify and notifyAll methods are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside synchronized blocks. The synchronization object that shall be invoked in the synchronized statement is the one whose monitor must be acquired.
Here is the simple example for to understand the concept of monitor
public class SimpleMonitorState {
public static void main(String args[]) throws InterruptedException {
SimpleMonitorState t = new SimpleMonitorState();
SimpleRunnable m = new SimpleRunnable(t);
Thread t1 = new Thread(m);
t1.start();
t.call();
}
public void call() throws InterruptedException {
synchronized (this) {
wait();
System.out.println("Single by Threads ");
}
}
}
class SimpleRunnable implements Runnable {
SimpleMonitorState t;
SimpleRunnable(SimpleMonitorState t) {
this.t = t;
}
#Override
public void run() {
try {
// Sleep
Thread.sleep(10000);
synchronized (this.t) {
this.t.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
You ask
How can I make a thread wait until it will be notified?
You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
Details for synchronization and waiting are already explained by Tom Hawtin.
java.lang.IllegalMonitorStateException means you are trying to wait on object on which you are not synchronized - it's illegal to do so.
Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:
synchronized (lock) {
makeWakeupNeeded();
lock.notifyAll();
}
Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();
Once I made it in those 2 places I got it working
I received a IllegalMonitorStateException while trying to wake up a thread in / from a different class / thread. In java 8 you can use the lock features of the new Concurrency API instead of synchronized functions.
I was already storing objects for asynchronous websocket transactions in a WeakHashMap. The solution in my case was to also store a lock object in a ConcurrentHashMap for synchronous replies. Note the condition.await (not .wait).
To handle the multi threading I used a Executors.newCachedThreadPool() to create a thread pool.
Those who are using Java 7.0 or below version can refer the code which I used here and it works.
public class WaitTest {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void waitHere(long waitTime) {
System.out.println("wait started...");
lock.lock();
try {
condition.await(waitTime, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
System.out.println("wait ends here...");
}
public static void main(String[] args) {
//Your Code
new WaitTest().waitHere(10);
//Your Code
}
}
For calling wait()/notify() on object, it needs to be inside synchronized block. So first you have to take lock on object then would be possible to call these function.
synchronized(obj)
{
obj.wait()
}
For detailed explanation:
https://dzone.com/articles/multithreading-java-and-interviewspart-2
wait(), notify() and notifyAll() methods should only be called in syncronized contexts.
For example, in a syncronized block:
syncronized (obj) {
obj.wait();
}
Or, in a syncronized method:
syncronized static void myMethod() {
wait();
}

Thread.sleep is blocking other thread also, working on other method, along with itself callled inside synchronized method

class Common
{
public synchronized void synchronizedMethod1()
{
System.out.println("synchronized Method1 called");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("synchronized Method1 done");
}
public synchronized void synchronizedMethod2()
{
System.out.println("synchronized Method2 called");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("synchronized Method2 done");
}
}
In the above class I have two synchronized methods which I am calling from run method of another class. Other class code is given below:
public class ThreadClass implements Runnable
{
private int id = 0;
private Common common;
public ThreadClass(int no, Common object)
{
common = object;
id = no;
}
public void run()
{
System.out.println("Running Thread " + Thread.currentThread().getName());
try
{
if (id == 11)
{
common.synchronizedMethod1();
}
else
{
common.synchronizedMethod2();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Common c = new Common();
ThreadClass tc = new ThreadClass(11, c);
ThreadClass tc1 = new ThreadClass(20, c);
Thread t1 = new Thread(tc, "Thread 1");
Thread t2 = new Thread(tc1, "Thread 2");
t1.start();
t2.start();
}
}
From main method I am starting two different threads. In run method I have given a condition to send both different threads to different synchronized methods. Output produced by the code is:
Running Thread Thread 2
Running Thread Thread 1
synchronized Method2 called
synchronized Method2 done
synchronized Method1 called
synchronized Method1 done
MY QUESTION FOR THE OUTPUT IS:
When thread 2 goes to synchronized Method2 it prints 3rd line of output and goes to sleep for 1 second. Now since thread 1 is not blocked by anything so it should execute and print 5th line of the output just after 3rd line of output and should go to sleep then but this is not happening instead when thread 2 goes to sleep it make's thread 1 also sleep then first thread 2 complete's its execution after which thread 1 completes its execution.
Such a behavior is not happening if I remove synchronized keyword from methods.
Can you please explain me the reason behind different way of processing the code with and without synchronized keywords.
Thanks in advance.
Such a behavior is not happening if I remove synchronized keyword from methods. Can you please explain me the reason behind different way of processing the code with and without synchronized keywords.
This is actually the entire purpose of the synchronized keyword. When you have several synchronized instance methods of the same class, only one may be executing at a time. You have written this:
class Common {
public synchronized void synchronizedMethod1(){}
public synchronized void synchronizedMethod2(){}
}
Because both methods are synchronized, only one may be executed at once. One of them can't start the other one is done.
How does this work? In short, you have a Common object and call a synchronized instance method of it. When you call synchronzedMethod1, that method will "lock" the Common object (called "acquiring the lock"). While that method has that lock on that Common object, if you try to call any other synchronized method on that same object, it will try to lock it and it will find that it's already locked. So any other attempt to lock the object will hang until they can do so. Once synchronizedMethod1 finishes, it will unlock the Common object (called "releasing the lock") and anybody can then try to lock it, such as synchronzedMethod2.
So in short, synchronized specifically makes it so you can't have two synchronized methods of the same class happening at once. This is useful because some problematic behavior can come from not doing this. As an example, ArrayList does not do this, so if one thread tries to add an object to an ArrayList while another tries to iterate over it, it might throw a ConcurrentModificationException and make everyone sad.
A sleeping thread does not release its locks, but you can replace your sleep(...) calls with wait(...). Keep in mind, though, that only the lock of the object having wait(...) called on it will be released, so you'd have to devise a different solution if you expected multiple locks to be released while waiting.
synchronising a method doesnt mean just the method itself synchronised
synchronized void x(){}
equals to:
void x(){
synchronised(this){}
}
Since both thread access same Common instance first thread will get the ownership of the Common object lock doesnt matter which synchronised method called and it will just release this lock after this method body completed its job.
If you would send two Common instance there would not be a problem since they are not static. Also you might be interested in ReentrantLock
First of all synchronized keyword is used to define mutual exclusion. Here mutual exclusion achieved by Monitor concept. One more thing is sleep does not release monitor. It just pause the execution of current thread for some time. Other threads which requires the monitor have to wait until the thread which acquired monitor release it.
There is two ways to use synchronized...
First one is using synchronized blocks.
synchronized(obj){...}
Here if any thread want to enter into synchronized block it have to get monitor of obj.
Second one is to using synchronized method.
synchronized void meth(){...}
Main difference between synchronised method & block is synchronised method use monitor of object it self & synchronised block can have monitor of any object.
Synchronized method can be defined using synchronized block as follows...
void meth(){
synchronized (this){
//method body
}
}
Now you can use the synchronised block to prevent the problem of blocking another method. Here you have to define synchronised block on different objects so both methods can execute concurrently but multiple threads can not execute same method concurrently.

What is the purpose of using synchronized (Thread.currentThread())?

Can any one please elaborate why the below code snippet gives IllegalMonitorStateException? I still can't able to find why and when this exception occurs and what is the purpose to lock on the current executing thread instead of object?
void waitForSignal() {
Object obj = new Object();
synchronized (Thread.currentThread()) {
obj.wait();
obj.notify();
}
}
In order to call wait on obj that method/code block should synchronised on obj
void waitForSignal() {
Object obj = new Object();
synchronized (obj) {
obj.wait();
obj.notify();
}
}
You are getting that exception because you need to acquire lock on obj before calling wait(), notify() or notifyAll() methods. These methods are designed to provide a mechanism to allow a thread to block until a specific condition is met.
The wait() method releases lock on the object, that mean you need to have acquired a lock before releasing it.
Whereas notify() and notifyAll() are to notify other threads which are waiting to acquire lock on the same object. It's like one thread is telling other threads : "Dudes, I don't need the object for now, you can go ahead and use it. Make sure you notify me once you are done.".
There are no real scenario where you would want to acquired lock on thread it self.
Here's a code block where you wait for thread to complete before executing a code block.
Thread t = new Thread() {
public void run() {
synchronized (Thread.currentThread()) {
System.out.println("Thread");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
};
t.start();
Thread.sleep(10);//sleep main thread
synchronized (t) {
System.out.println("Main Thread");
}
}
I have to sleep main thread becaue, Most of the time synchronized block acquires lock before the thread it self.
You can do the same with join()
synchronized (Thread.currentThread())
doesnt make any sense, a thread cant synchronize itself (that'd produce a deadlock), you will have to synchronize on the OBJECT YOU ARE WAITING FOR:
synchronized (obj)
Also : its always better to use semaphore for this kind of job
Generally speaking locking on the thread makes no sense except for blocking operations on the Thread object itself. For example Thread.join() wait()s on the Thread to finish. This means it uses a synchronised block with wait() to wait on the thread itself.

Synchronized blocks don't work when using member of unrelated class as lock object?

Pretty much all resources I've found on synchronized blocks use this or a member of the class as a lock object. I'm interested in finding out why I can't get synchronized blocks to work when the lock object is a (static) member of another class. Here's my code to illustrate the problem:
public class Test {
public static void main(String[] args) {
Thread thread1 = new FirstThread();
Thread thread2 = new SecondThread();
thread1.start();
thread2.start();
}
}
class FirstThread extends Thread {
#Override
public void run() {
synchronized (Lock.lock) {
System.out.println("First thread entered block");
try {
Lock.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("First thread exited block");
}
}
class SecondThread extends Thread {
#Override
public void run() {
try {
Thread.sleep(1000); //just making sure second thread enters synch block after first thread
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Lock.lock) {
System.out.println("Second thread entered block");
Lock.lock.notifyAll();
}
System.out.println("Second thread exited block");
}
}
class Lock {
public static Object lock = new Object();
}
My understanding is that the second thread should not be able to enter the synchronized block until the first thread exits, since they are synchronized on the same object. Thus I was expecting the program to hang (deadlock?) after "First thread entered block", since the second thread can't enter the block and the first thread will be stuck waiting for a notification. But instead I got the following output:
First thread entered block
Second thread entered block
Second thread exited block
First thread exited block
Clearly the second thread enters the synchronized block before the first thread has left it's block. Can someone explain what I'm missing?
I thought the purpose of synchronized blocks was to prevent exactly this. Is it because the lock object is a member of another class?
first thread Lock.lock.wait() relinquish the lock on the synchronized object so other thread can enter the critical path and wake up the waiters.
note that sleep(), instead, does not.
Difference between wait() and sleep()
Quote from the javadoc of Object.wait():
The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
If that was not the case, waiting would systematically cause a deadlock, since no thread would ever be able to enter the synchronized section needed to call notify() or notifyAll(), making wait and notify completely useless.
When you call lock.wait you "release ownership of this monitor". This allows thread 2 to enter the synchronized block.

Java threading notify() method

Consider there are two threads which are waiting to execute synchronized block. Now one get chance one is waiting in this case do I really need to call notify() ? I think as synchronized block execution completes other thread will release the lock ? what is the exact use of notify() method ?
Threading experts please explain ?
No, you wouldn't need to use notify() in that case. You are correct, the thread that had to wait to acquire the lock would automatically proceed after the lock was released.
The notify() method works in conjunction with the wait() method. When one thread invokes wait(), it may release the lock and begin waiting. One of the conditions that can end the wait is when another thread invokes notify(). Both wait() and notify() must be invoked on an instance on which the current thread is synchronized.
This can be used, for example, to create a channel between two threads, where one thread is consuming information produced by another. If the consumer runs out of information to process, it might wait() until the producer does a notify() that more data are available.
When a thread enter synchronized block and calls wait the lock acquired while entering the synchronized block is released and the thread waits for other thread to notify it in which case it will reacquire the lock and proceed.Lock is again released when the thread comes out of the synchronized block.
from the doc,
Wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation. A thread waits on an object's monitor by calling one
of the wait methods.
so if an object is waiting by calling a wait method. then you can awake them using notify.
Description
The java.lang.Object.notify() wakes up a single thread that is waiting
on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and
occurs at the discretion of the implementation. A thread waits on an
object's monitor by calling one of the wait methods.
For more information refer below links.
notify()
Documentation
Doc
I hope it will help you.
Like if you are using Multiple threads the method is synchronized which means it will share among all the threads but any thread will use it after the execution another thread.
and if there is any change is made by any thread then it will visible for all by using notify method below code is example for that:
class Detail {
public String name = "", sername = "";
Scanner sc;
public synchronized String getData() {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return name+""+sername;
}
public synchronized void show() {
try {
name = "hello";
sername = "hii";
Thread.sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
notify();
}
}
class Data1 extends Thread {
Detail detail;
public Data1(Detail detail1)
{
// super("1");
this.detail = detail1;
start();
}
public void run()
{
System.out.println("name is :"+detail.getData());
}
}
class Data2 extends Thread {
Detail detail2;
public Data2(Detail detail1)
{
//super("2");
this.detail2 = detail1;
start();
}
public void run()
{
detail2.show();
}
}
public class SyncDemo {
public static void main(String ar[])
{
Detail det = new Detail();
Data1 d1= new Data1(det);
Data2 d2= new Data2(det);
}
}

Categories