Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the synchronize functionality work in java?

Since I've started programming in Java I have been wondering this (about a year or two). In C, we must know the different method to correctly avoid deadlock between thread and thus there is much more choice between synchronization method.

So what about Java? When we synchronize, how does it avoid putting thread in deadlock situation? How does it work internally? Does the deadlock are avoided because we synchronized on higher level than in C ( or C++)? Any documentation about deadlock and synchronization in java?

like image 518
Zonata Avatar asked Jul 05 '11 14:07

Zonata


People also ask

How does the synchronization work?

When you sync a device with your computer, the syncing process results in both the device and the computer being updated with the most up-to-date files. Another example is when you sync iTunes with your iPhone or iPod, the music then exists on the computer and device.

How do you synchronize variables in Java?

Use the synchronized keyword. Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample . Thus, if any one thread is in newmsg() , no other thread will be able to get a lock on the instance of sample , even if it were trying to invoke getmsg() .

Can we synchronize two Java processes?

yes but if you start even 2 processes w/ 1.6GB you are already out of the Windows addressable space.

What is synchronization in Java How does it help to lock a resource?

Synchronization is required to prevent several threads from accessing a resource allowing only one thread at a time. Java's synchronized blocks, denoted by the synchronized keyword, allow you to handle several threads at once. In each case, a thread must acquire and release a lock on the method or block.


1 Answers

Under the hood it is using two opcodes monitorenter and monitorexit at the byte code level which acquire/release locks on an object reference at a JVM global level. I highly recommend you read How the Java virtual machine performs thread synchronization.

like image 148
Andrew White Avatar answered Oct 13 '22 01:10

Andrew White