java thread blocking - java

Can non synchronized methods called from synchronized methods allow a thread to block?
public synchronized void foo(){
someStuff();
someMoreStuff();
bar();
}
public void bar(){
//... does some things
}
If a thread is executing foo() is there anyway to ensure that bar() will be called before the thread sleeps?
TIA

A thread can always be pre-empted (there's no way of preventing that in Java) but no other thread will be able to acquire the lock on the same object before foo returns.
Note that a thread "losing the CPU" isn't what's normally meant by "blocking" - normally a call is deemed to block if it needs to wait for something else to occur. For example:
Reading from a stream blocks until there is some data available (or the end of the stream is reached)
Acquiring a lock blocks until the lock is available
These are very different from just running out of time slice.

Are you asking if there's a way to insure that the Java VM doesn't take the CPU and let another thread execute? You could set the Thread priority to high, but this still wouldn't provide a guarantee at all.
No other thread will be able to call your "foo" method while you don't have the CPU, though. Similarly, synchronizing "bar" would prevent it from being called until your call to "foo" had completed (as you own the lock for the entire period of the "foo" method).

The question seems to be if other threads can freely invoke bar() while one thread holds the lock on an object during the execution of foo(). And specifically, if two or more threads can be running bar() at the same time.
And the answer is that any thread can run bar() at any time, so yes, there can be more than one thread running bar() at any single point in time.

Related

Why it is not possible to build binary semaphore with if statement inside in Java

I have a small question that makes me a little confused.
This is my code:
public synchronized void P() {
while(!_state) {
this.wait();
}
_state = false;
}
This method is responsible for taking semaphore.
Why it is not possible to build binary semaphore with if statement instead of while loop?
The oracle docs says:
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.
So exactly only one thread should be inside the P() method -> so only one thread should be blocked on wait() method. Rest of threads should be blocked on P() method level. But when I am replacing while() for if() it does not work properly
Why it is not possible to build binary semaphore with if statement instead of while loop?
For a deep answer, you should work through Oracle's Guarded Blocks tutorial.
The shorter answer is, there's a couple of reasons why _state could be false when the wait() call returns:
Multiple consumers: It generally is safer to wake sleepers with notifyAll() instead of notify(), and if you write a program in which two or more threads could call the P() function, you probably only want one of them to be allowed to proceed when some other thread calls the V() function. So, if they all "wake up", you'll want just one to set _state=false; and you'll want the others to go back to sleep.
The same object is getting notifyAll() calls for more than one reason. It's not good practice, but it happens, especially in projects where many developers contribute to the code. In that case, you don't wan the P() call to return if the object was notified for the wrong reason. You want it to go back and continue waiting.
The documentation for o.wait() says that it is allowed to return even when object o has not been notified at all. This is known as "spurious wakeup." It happens rarely, and only in some operating systems, but they allow it because it enables a more efficient implementation of wait() and notify().
synchronized method is equivalent to synchronized(this) block.
Only 1 thread is allowed to enter synchronized block. By entering it, thread aquires lock. When you wait inside sync block, you release the lock (object monitor) and park current thread. At this moment, another thread is allowed to enter that block. Execution will continue when other thread will invoke notify or notifyAll on the same object that wait was invoked. Notified thread will "exit wait state" when given sync block's lock will be released.
To sum up - wait does not work like you expect, it does not block execution, only puts waiting thread to sleep, allowing other threads to aquire sync lock.
So you cannot do what you want to achieve, because wait works differently then you expect. What you want to use here, is ReentrantLock. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

Why, before calling the wait method of an object, should a thread own the monitor of exactly the same object?

I am learning about cooperation between concurrent tasks and I have got that question and a possible answer to it. I would like to make sure I understand it correctly.
So to call a.wait() it is first required to synchronize on the object a or to be more precise a thread must become the owner of the a's monitor. As far as I understand, the only reason why a.wait() should be called in a synchronized context (together with a.notify()/a.notifyAll()) is to avoid a race condition/The Lost Wake-Up Problem. But theoretically, it is possible to avoid the race condition calling a.wait(),a.notify()/a.notifyAll() by synchronizing on some other object, like this:
Thread #1:
synchronized(b) {
…
a.wait(); // here a thread owns only one monitor: the monitor of the object stored in the variable b, where a != b
…
}
Thread #2:
synchronized(b) {
…
a.notify(); // the same here
…
}
The expected behavior is: the thread #1 acquires the monitor of b, enters the critical section, invokes a.wait(), then waits on a and releases the monitor of b. Afterwards the thread #2 acquires the monitor of b, enters the critical section, invokes a.notify() (the thread #1 gets notified), exits the critical section and releases the monitor of b, then the thread #1 acquires the monitor of b again and continues running. Thus, only one critical section synchronized on b can run at a time and no race condition can occur. You may ask, “but how would wait() know that the object b is used in this case to avoid the race condition and thus its monitor must be released?”. Well, that way it wouldn’t know. But maybe the wait method could take an object as an argument to know which object’s monitor to release, for example, a.wait(b), to wait on a and release the monitor of b. But there is no such an option: a.wait() causes a thread to wait on a and releases the monitor of exactly the same a. Period. The invocation of the wait and notify methods in the code above results in IllegalMonitorStateException.
According to this information from the Wikipedia article, the functionality of the wait, notify/notifyAll methods is built into every object's monitor where it is integrated into the functionality of the synchronization mechanism at the level of every individual object. But still it doesn't explain why it was done this way in the first place.
My answer to the question: before calling the wait method of an object, a thread should own the monitor of exactly the same object because to avoid a race condition this object is always not only a viable option but the best one.
Let’s see if there are any situations where it could be undesirable to synchronize on an object before invoking its wait, notify/notifyAll methods (plus some relevant logic). Synchronizing on the object would block it for other threads which could be undesirable if the object has some other synchronized methods (and/or there are some critical sections synchronized on the object) having nothing to do with the waiting logic. In that case it is always possible to refactor the corresponding class(es) so that the wait and notify/notifyAll methods operate on one object, while other synchronized methods/blocks operate on another one(s). For example, one of possible solutions could be creating a dedicated object specifically for a waiting logic (to wait and synchronize on) like in the example below:
public class A {
private Object lock = new Object(); // an object to synchronize and wait on for some waiting logic
private boolean isReady = false;
public void mOne() throws InterruptedException {
synchronized(lock) { // it blocks the instance of the Object class stored in the variable named lock
while(!isReady) {
lock.wait();
}
}
}
public void mTwo() {
synchronized(lock) { // the same here
isReady = true;
lock.notify();
}
}
synchronized public void mThree() { // it blocks an instance of A
// here is some logic having nothing to do with the above waiting and
// mThree() can run concurrently with mOne() and mTwo()
}
}
So there is no need to synchronize on some voluntary object to avoid a certain race condition regarding calling wait, notify/notifyAll methods. If it was allowed it would only cause unnecessary confusion.
Is it correct? Or maybe I am missing something here. I would like to make sure I don't miss anything important.
Oracle documentation: wait, notify, notifyAll

Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method?

In Java using the synchronized keyword all within a single object and thread.
Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method, without the final synchronized method blocking for the first synchronized method to be completed?
With a single object and a single thread, there's no problem.
Your only thread is able to acquire all the locks, and due to re-entrancy, it can acquire them several times.
Even if we add another thread, it'll work (with one object). One thread will acquire the first lock, blocking the second thread, and execution continues normally.
With multiple threads and multiple objects, the answer is "it depends on how the code is written".
Your code can always call a method whether it is synchronized or not. A better question is, what will happen when your code calls it.
A synchronized method that looks like this:
synchronized void foobar() {
doSomething();
}
Actually is just a short-hand way of writing this:
void foobar() {
synchronized(this) {
doSomething();
}
}
So any question about calling a synchronized method really is a question about executing a synchronized block. There are three things that could happen when your code enters synchronized(this) {...}.
1) If the this object is not locked, then it will be locked in the name of the calling thread, the thread will execute the statements in the block, and then it will unlock the lock when it's done.
2) If the this object already has been locked by the calling thread, then the thread will simply execute the statements in the block.
3) If the this object is locked by some other thread, then the calling thread will wait until the other thread unlocks it, and then it will proceed as in case (1).
The only way you can get into trouble is if your code attempts to lock two different locks. Then, if your design is not well thought out, two or more threads could deadlock, which is something you can read about elsewhere.
If a class has both synchronized and non-synchronized methods, multiple
threads can still access the class's non-synchronized methods.If you have
methods that don't access the data you're trying to protect, then you don't
need to synchronize them. Synchronization can cause a hit in some cases (or
even deadlock if used incorrectly)

Why to use wait method on strings or other objects?

I have following piece of code:
synchronized void myMethod() {
String s="aaa";
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The code throws exception ...
I have seen codes using wait method on threads which is self explainable and logical..
why would one use wait method on an object like string instead of using it on main thread?
what is its use?
are there any practical implementations like this?
Thanks in advance
Your sample code won't work because the method is synchronizing on the instance that myMethod is called on, while the wait is called on the string. It will cause an IllegalMonitorStateException. You have to call wait and notify on the same object that you're locking on. The threads that get notified are the ones waiting on the lock that notify is called on.
Locking on a string object is a bad idea, don't do it. You don't want to lock on things where you can't reason about who can acquire them because anybody could acquire them. Some other code elsewhere in the application could be locking on the same string value, and you'd have the potential for strange interactions, deadlocking because the other code was taking your lock, or have the other code notifying you. Do you want to have to think about how strings are pooled when debugging some multithreading behavior?
You can limit who can acquire your lock by defining your own lock and making it private, like this:
private final Object LOCK = new Object();
so only threads calling the methods of the object you're controlling access to can acquire the lock:
public void myMethod() {
synchronized(LOCK) {
...
}
}
That way you know exactly what can acquire the lock, it's not available to every thread in the application. The lock can be acquired by anything that can get a reference to that object, so keep the reference private.
The way your example uses wait without a loop with a condition variable is very suspect. A thread can exit from a call to wait without having been notified. Even if a thread is notified, that doesn't give it any special priority with the scheduler. Another thread can barge in and do something, possibly something affecting the state that the notification was alerting the waiting thread to, between the time the thread is notified and the time that the thread can reacquire the lock it gave up when it started waiting. For both reasons there needs to be a loop where the thread retests a condition when it wakes from waiting.
Also if by "codes using wait method on threads" you mean code where a Thread object is used as a lock, that's another thing to avoid doing, see the API documentation for Thread#join:
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.
You first need to be synchronized on the Object before calling wait. This is where you are getting the exception from.
void test() {
String s = "AAA";
synchronized( s ) {
s.wait();
}
}
The same thing must be done when you call notify, but in this case it is a very very bad idea because if a thread enters this method it will never return. Although considering it is a String literal you may be able to get away with it by using the same literal in another method in the same class, but don't count on it.
wait() method is implemented in Object, and String extends object so it can be used.
why someone use it? ask him. its not a programming question.
something i can think of:
he could be using "lock1".wait() in one class and "lock1".notify() in other, it will be something like global lock object
because literals are interned by
the compiler and thus refer to the same object
but its VERY VERY BAD PRACTICE
This is an example of synchronization with no affect.
First of all, it is unlikely you will need to synchronize on String, it is immutable after all, therefore, you don't need it to perform anything asynchronously.
Second, you are likely to be synchronizing on the incorrect object anyways, no correctly written program would use String as a synchronization lock.
Third and finally, s is a local variable. In fact, it holds exactly the same pattern that JCIP specifically tells you not to use if you inline it:
synchronized (new Object()) {
// ...
}
This is synchronization without effect, as it does not guarantee the purpose of the synchronized keyword: serialized access, lock and release semantics that require that only one thread execute the synchronized block at any given time.
Because of this, each thread will have their own lock - not good.

How does two threads not able to execute method at the same time. Internally what happens in the code.

I have a method which is synchronized defined in some class.
We know that if we create a method as synchronized, then only one thread is able to execute the task at a time.
What is happening inside this method ?
How does other thread not able to execute the same task to run same method.
As per my knowledge, join is applied on that particular thread. But how does the second thread in the pipeline knows about the task has been done by first thread.
Tell me if i am right.
In the Java language, each Object has what is called a Monitor, which basically is a lock.
This lock is what powers Object methods such as wait / signal / signalAll that are available on every objects.
When using the synchronized keyword, what happens behind the scenes is that the compiler writes code that acquires the monitor (the lock) and releases it when invocation is complete.
If the method is static, the Monitor that is accessed is that of the Class object.
You can read more about this keyword here :
http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
One thread (first) acquires a lock on the object, and another thread waits for getting lock of that object.
Once task is done, first thread sends notification to waiting threads using notify() and notifyAll() methods.
We know that if we create a method as synchronized, then only one thread is able to execute the task at a time.
Not True! Two or more threads can enter the same synchronized block at the same time. And, that's not just in theory: It often happens in well-designed programs.
Here's what two or more threads can not do: Two or more threads can not synchronize on the same object at the same time. If you want to insure that only one thread at a time can enter a particular method (but why?†) then you need to write the method so that all calls to it will synchronize on the same object. That's easy to do if it's a static method because this:
class Foobar {
synchronized MyType baz() { ... }
}
means the same as this:
class Foobar {
MyType baz () {
synchronized (Foobar.class) { ... }
}
}
All calls to a static synchronized method synchronize on the class object that owns the method.
[what prevents two threads from synchronizing on the same object at the same time]?
The operating system. Any JVM that you would want to use for real work uses native threads to implement Java threads. A native thread is a thread that is created and managed by calls to the operating system. In particular, it's a part of the operating system known as the scheduler. I am not going to go into the details of how an operating system scheduler works---there's whole books written about that topic---but its job is to decide which threads get to run, when, and on what processor.
A typical scheduler uses queues to keep track of all of the threads that are not actually running. One special queue, the run queue, holds threads that are ready to run, but waiting for a CPU to run on. A thread on the run queue is called runnable. A thread on any other queue is blocked (i.e., not allowed to run) until something happens that causes the scheduler to put it back on the run queue.
The operating system object corresponding to a Java monitor (See #TheLostMind's answer) often is called a mutex or a lock. For each mutex, there is a queue of threads that are blocked, waiting to enter it. A native thread enters a mutex by calling the operating system. That gives the operating system the opportunity to pause the thread and add it to the mutex's queue if some other thread is already in the mutex. When a thread leaves a mutex, that's a system call too; and it gives the scheduler the opportunity to pick one thread off the mutex's queue, and put it back on the run queue.
Like I said, the details of how the scheduler does those things go way too deep to talk about here. Google is your friend.
† Don't worry about which threads can enter which method at the same time. Worry instead about which threads touch which data. The purpose of synchronization is to allow one thread to temporarily put your data into a state that you don't want other threads to see.
What is happening inside this method ?
When you say a (instance level) method is synchronized, A thread must first get a lock on the Object (i.e, first hold the monitor of that object) to access it. As long as one thread holds the lock / monitor, other threads cannot access it. because they cannot get a lock on the object (it is like door to the object).
How does other thread not able to execute the same task to run same method.
Because as long as one thread still holds the monitor, other threads wait. i.e, they cannot access the monitor themselves.So, they are blocked and will wait in the waiting set / queue for that object.
join is applied on that particular thread. But how does the second thread in the pipeline knows about the task has been done by first thread.
Join() ensures that the thread that calls join() on another thread, waits until the second thread completes its execution.
Note : A happens before relationship is established between the 2 threads when join is called. So that Whatever happens before a call to join or a return from join are always visible to other thread.
Edit :
Assume ThreadA and ThreadB are two threads running concurrently.
ThreadA
{
run(){
//some statements;
x=10; // assume x to be some shared variable
ThreadB.join();
// here ThreadA sees the value of "x" as 20. The same applies to synchronized blocks.
// Suppose ThreadA is executing in a Synchronized block of Object A, then after ThreadA //exits the synchronized block, then other threads will "always" see the changes made by //ThreadA
// some other statements
}
}
ThreadB{
run(){
//some statements
x=20;
}
check : Happens Before

Categories

Resources