Mutual exclusion - How synchronized works? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.
On synchronized without using wait(), Does a thread state set to BLOCKED?
Does a thread in BLOCKED & WAITING state consume CPU cycles?

As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.
I think you are misreading that answer. synchronized is certainly not implemented with the Java-level compareAndSwap call. It will be implemented in native code by the interpreter and JIT in your JVM. Under the covers it might use the compare-and-swap instruction, or it may use something else (atomic test-and-set and atomic exchange are also common - and some platforms don't even have a CAS primitive).
This is definitely not a "non-blocking algorithm" - by definition synchronized implements a type of critical section which implies blocking if a second thread tries to enter the critical section while another thread is inside it.
1) On synchronized without using wait(), Does a thread state set to BLOCKED?
Yes, if a thread is waiting to enter a synchronized section, its state is set to BLOCKED.
2) Does a thread in BLOCKED & WAITING state consume CPU cycles?
Generally no, at least not in an ongoing manner. There is a CPU cost associated with entering and exiting the state1, but once the thread is blocked it is generally held in a non-runnable state until it is awoken when the monitor becomes free, and doesn't use CPU resources during that time.
1 Which is exactly why good implementations will generally "spin" a bit before going to sleep, in case the critical section is short and the holding thread may soon exit - spinning in this case avoids the 1000+ cycle overhead of making the transition to sleep (which involves the OS, etc).

Related

How is java `wait()` waiting implemented? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm asking about the waiting process not the access ordering method is it in the simplest form an infinite loop with a conditional exit.
Whats the least resource consuming way to wait for a request thats what got me to ask this.
Object.wait() functionality is implemented with JVM_MonitorWait native method, as per ThreadReference javadoc:
/** Thread is waiting - Object.wait() or JVM_MonitorWait() was called */
public final int THREAD_STATUS_WAIT = 4;
The implementation of this method can be found in jvm.cpp and uses ObjectSynchronizer::wait:
JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
JVMWrapper("JVM_MonitorWait");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
JavaThreadInObjectWaitState jtiows(thread, ms != 0);
if (JvmtiExport::should_post_monitor_wait()) {
JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
// The current thread already owns the monitor and it has not yet
// been added to the wait queue so the current thread cannot be
// made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
// event handler cannot accidentally consume an unpark() meant for
// the ParkEvent associated with this ObjectMonitor.
}
ObjectSynchronizer::wait(obj, ms, CHECK);
JVM_END
ObjectSynchronizer::wait implementation is in synchronizer.cpp and delegates to ObjectMonitor::wait in objectMonitor.cpp.
If you continue to dig in you will eventually reach the native Java thread implementation which is platform dependent. On Linux this will be libpthread.so which will ultimately handle the thread status change.
is it in the simplest form an infinite loop with a conditional exit?
No it isn't. That is inefficient, and not how it is typically done.
The details are complicated and system dependent (see #Karol's answer for links to the code), but the general approach is as follows.
When the thread calls wait(), the method does the following:
Add the thread details to the mutex object's queue of "objects waiting".
Relinquish the thread's mutex lock.
"Park" the thread by telling the OS to put it to sleep.
The OS finds some other thread to schedule. If there is none, it causes the core to go into a low power "idle" loop or suspends it or something. (This is OS and hardware dependent.)
Then when another thread calls notify, the notify method does the following:
It removes a thread from the mutex queue.
It tells the OS that the (previously) waiting thread should be woken.
It returns from the notify() call and (hopefully) releases the mutex lock.
The OS does the following:
It finds a free processor to run the thread, and starts.
If no core is free, the OS adds the thread to the scheduler's queue of runnable threads.
When the thread starts, it first tries to reacquire the mutex lock ... which may cause it to be put back to sleep, if some other thread is still holding the lock.
Finally the wait call returns, and the thread will typically recheck the condition variable, and then release the lock.
The point is that there are (typically) no infinite loops that that consume CPU while a thread is waiting.
Whats the least resource consuming way to wait for a request that is what got me to ask this.
The least resource consuming way would be Object.wait and Object.notify ...
In synchronous programing, a monitor can be assumed like a box or more specifically a control box (to make any changes in an object) with a space of only one thread at any given instant. So, multiple threads can be prevented from writing one object at the same time and protecting the object from getting corrupted. In it, wait() method tells a thread, if any other thread is already sitting in the monitor and if so, tells the calling thread to WAIT for the other thread to come out. Or technically, tells the calling thread to SLEEP until notified.
It stops any further execution of code in the calling thread, unlike a infinite loop, in which the execution continues, but no code after the loop is executed until the loop breaks.

Lock.tryLock(): Thread performing different tasks? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to understand multi-threading in Java, using the
features which were added as part of java.util.concurrent.* . To begin with, there is concept of lock which a thread can try to acquire; if a thread can't acquire, it can do some other tasks.
This I have read in online materials as well in some books, but never ever seen anything they have implemented in real. How is this possible that if a thread can't acquire a lock it can execute other tasks; isn't a thread supposed to do a single "piece of work"? How can it have multiple logic execution based on if it can/can't acquire a lock?
Is there any real implementation which I can refer to see to understand, to reinforce the concepts; else it seems too abstract, how to implement in real life.
Any explanations?
It's difficult to find real life examples because normally you wouldn't design your software to use tryLock(). The example given in the javadoc is as follows:
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
But you wouldn't design your software like that, would you? What if the lock is never (or almost never) available, how will that affect your program? What if it's always available? You have a method that does one of two things depending on pure chance. That's not good design, it increases randomness and complexity.
Okay, so it's not something you decide to use because it's elegant. What is it good for?
Imagine you've inherited a legacy project designed by an insane programmer and it has severe issues with deadlocks. It has synchronized methods peppered all around and needs to be booted at least once every week because it locks up. First you convert all the synchronized methods to use Lock instead. Now you no longer block forever on synchronized, but can use tryLock(long, TimeUnit) to timeout and prevent deadlocks.
Now you've solved the reboot causing deadlocks, but it's still not optimal since you're spending time waiting. With additional refactoring you manage to reduce the locks, but unfortunately you can't do proper lock ordering just yet. Your end code looks like this, where inner locks are acquired with tryLock() or outerlock is released to prevent deadlock:
Lock outerLock = ...;
outerLock.lock(); // Here we block freely
try {
Lock innerLock = ...;
if (innerLock.tryLock()) { // Here we risk deadlock, we'd rather "fail-fast"
try {
doSomethingProtectedByLocks();
} finally {
innerLock.unlock();
}
} else {
throw new OperationFailedException(); // Signal the calling code to retry
}
} finally {
outerLock.unlock();
}
I think the problem is mainly with wording. The Javadoc talks about "actions" (like unlocking an outer lock) being performed based on whether the lock was acquired or not, but it's easy to read it as if the thread would have 2 separate responsibilities determined by the lock state.

How does synchronization work in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
is the following statement correct:
" There shouldn't be any thread interference between two synchronized methods in 2 different classes . So they can run concurrently without any problems."
Thanks for your time
That is way too vague. A few pointers:
"how does synchronization work in Java": There are a couple of mechanisms, the question seems to be about the synchronized keyword. This works by marking "critical sections" that must not be executed by more than one thread at the same time, and having the threads "lock" a monitor object while they are in that section (so that all other threads wait).
synchronized methods synchronize on the object instance (or class object in case of a static method). So methods in different classes do not synchronize with each-other that way. They will run concurrently.
you can use the synchronized keyword to synchronize blocks on any other monitor object. This way, methods in different classes can still be synchronized with each-other.
"can run concurrently without problems" is not guaranteed just by having some synchronization (or lack thereof). You need to see what mutable state these methods (directly or indirectly) try to access (and who else does the same) to see what kind of concurrency control is necessary.
You misunderstood the concept a little bit. Collisions happen when two (or more) threads simultaneously try to make a change on the same data or when one of them tries the read the data while the other thread is trying to change it.
When two thread tries to change the shared resource simultaneously, a race condition occurs. Check out this link to learn more about Race Condition.
In order to prevent this kind of problems, you need to guard the shared resource for simultaneous changes. Mutexes and semaphores are invented for this purpose: To lock the shared resource for the other threads, when one thread is currently making a change on it. For this purpose, Java uses the synchronized keyword. You can read more about Synchronized in Java using the link.
Note that, using the synchronized keyword will not eliminate all of the synchronization related issues, but it is a good starting point.

Why three "blocking" thread states in Java but only one in C#? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In Java, there are three distinct "blocking" thread states: BLOCKED, WAITING, and TIMED_WAITING. (the manual)
In C#, there is only one "blocking" state: WaitSleepJoin. (the manual)
Why? I can only guess Java's and C#'s respective implementations differ. I don't really see any practical reason why there should be three. Is there any? (I first learned C#'s lock block, Monitor.pulseAll() etc., and spent one and half gnarly hour debugging with Java today, because I assumed Java's synchronized block, Object#notifyAll(), etc. I know how they behave differently now, but I don't understand WHY.)
In java we use the WAITING and TIMED_WAITING on a synchronized object. If a thread is being in the WAITING state, another thread has to wake it up using notify()
TIMED_WAITING is the same as WAITING, but it will continue automatically when the specified time parameter is exceeded.
A thread is in BLOCKED state when the thread wants to run, but it can't run due another thread that is running on the same synchronized object.
So as we can see TIMED_WAITING is just the same as WAITING, but will stop waiting after a specified time.
But why did java seperate BLOCKED and WAITING? This is because they are different as mentioned above. BLOCKED means a thread is runnable but it cannot run, due another thread which is running. And the WAITING state is just waiting to be called for a notify()
Why C# has just one state is just a design decision. All java methods indicates that the thread is not in a runnable state, and C# just decided to combine these three states in a single variant: WaitSleepJoin

What do the terms synchronized and thread-safe mean? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've been watching a lot of videos on data structures, and these terms are always being mentioned: synchronized/not synchronized and thread-safe/not thread-safe.
Can someone explain to me in simple words what synchronized and thread-safe mean in Java? What is sync and what is thread?
A thread is an execution path of a program. A single threaded program will only have one thread and so this problem doesn't arise. Virtually all GUI programs have multiple execution path and hence threads - one for processing the display of the GUI and handing user input, others for actually performing the operations of the program. This is so that the UI is still responsive while the program is working.
In the simplest of terms threadsafe means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen. So, you add some extra code to prevent those bad things. For example, if two people were writing the same document at the same time, the second person to save will overwrite the work of the first person. To make it thread safe then, you have to force person 1 to wait for person 2 to complete their task before allowing person 1 to edit the document.
Synchronized means that in a multiple threaded environment, a Synchronizedobject does not let two threads access a method/block of code at the same time. This means that one thread can't be reading while another updates it.
The second thread will instead wait until the first is done. The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though, Synchronized has no benefit.
As per CIP:
A class is thread-safe if it behaves correctly when accessed from
multiple threads, regardless of the scheduling or interleaving of the
execution of those threads by the runtime environment, and with no
additional synchronization or other coordination on the part of the
calling code.
So thread safety is a desired behavior of the program in case it is accessed by multiple threads. Using the synchronized block is one way of achieving that behavior. You can also check the following:
What does 'synchronized' mean?
What does threadsafe mean?

Categories