Reputation: 164
This is similar to my previous question as I am still unclear with synchronized keyword.
This time I'll make it very short .
private int count = 0;
synchronized void increment() {
count++;
}
count is an instance variable which is shared among 2 threads.
If Thread t1 and t2 tries to increment count and OS gives t1 a chance to increment count first :-
t1 takes the lock and atomically increments count, time taken to increment count is 1 min(consider) including time taken to get the lock .
But what about thread t2, It is has to wait until lock is released. After release of lock, t2 now increments count atomically which also takes 1 min .
So synchronization gives correctness but it also takes time to perform.Threads are meant for doing work in less amount of time so why to use synchronization in threads what's the use of it.
Is my understanding correct ?
Upvotes: 0
Views: 180
Reputation: 522581
To add to @Bathsheba's answer, in a situation where multiple Threads are sharing and accessing the same resource which is not an atomic variable, you need to ensure that only one Thread accesses the resource at a given time. Consider modifying your example above to the following:
private int count = 0;
synchronized void increment() {
count = count + 1;
}
If you don't make the increment()
method synchronized
, then you run the risk of the count
variable having an inconsistent state. Specifically, your two Threads could interleave (meaning they are both running at the time) and an increment operation by one Thread could be overwritten by another Thread.
Read here for more about synchronization: https://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html
Upvotes: 0
Reputation: 692121
A fast program is useless if it's incorrect.
Suppose your class is the one handling deposits of money on your account.
Suppose three of your customers ask the bank to deposit 1000 dollars to your account. And suppose the bank doesn't synchronize the deposit operation.
Since it's not synchronized, you might have a race condition:
The result: instead of having $3000 on your account, you only have $1000. But that went 2 milliseconds faster than with synchronization.
Do you prefer that situation, or would you prefer the operation to take 2 additional milliseconds, but have $3000 on your account?
Upvotes: 1
Reputation: 4371
Yes, there is performance penalty in using synchronization. Concurrency here is to guarantee the integrity of shared variable read and write. In your case, without synchronization, t1 and t2 may read count with the same values (says 1), so when both threads exit the values of count is 2 even though you should expect it to be 3 (because it is increased twice)
Upvotes: 2
Reputation: 13713
Not every thread must do a synchronized job (otherwise we lose the point of using threads).
An efficient scenario is where threads do independent jobs (e.g. draw graphical elements on one thread while playing a background music on another)
Upvotes: 1