How does the synchronize functionality work in java?
Asked Answered
R

7

15

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?

Robynroc answered 5/7, 2011 at 14:31 Comment(0)
N
18

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.

Nernst answered 5/7, 2011 at 14:42 Comment(0)
S
5

The main problem(s) we meet with a multithreaded code is sharing data, and I agree with, the purpose of concurency parallizing process and it happens "ofently" that during parallalized processing that threads need accessing for read/write on shared data.

The java synchronized keyword permits the following:

It tells the JVM to put a lock on the monitor of the object or the piece of the synchronized code, which gives it exclusive access to that part of code or object.

Here's an example of a Singleton:

public class Singleton {
    private Singleton INSTANCE;

    private Singleton() {
    }

    public Singleton getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
}

This Singleton is not thread safe, if a thread is trying to get an instance while another is also trying to do the same (race condition) it may happen that before that the thread number one finishes the creation of the instance the second has already had access to the getInstance() method and created his own instance of the Singleton which means that at a T time we should have two instances of the Singleton (called multiton at that time).

To solve this problem we have to synchronize the creational behaviour of the singleton, this may be done by the keyword synchronized above the if statement on the INSTANCE itself:

public class Singleton {
    private Singleton INSTANCE;

    private Singleton() {
    }

    public Singleton getInstance() {
        synchronized (Singleton.class) {
            if (null == INSTANCE) {
                synchronized(Singleton.class) {
                   Singleton inst = new Singleton();
                   INSTANCE = inst;   
                }
            }
        }
        return INSTANCE;
    }
}

The result is when the first thread asks the Singleton instance and during creation time, the JVM will put a lock on the monitor of the INSTANCE denying any access to the INSTANCE until thread one finished its request.

There are diffrent ways to achieve that as well, the book cited before is an excellent source of learning, javadoc also.

Sillsby answered 5/7, 2011 at 15:5 Comment(0)
T
1

Synchronization isn't really that much easier in Java than in C. Syntactically it's easier, because all you need to do for a mutex is declare a method as synchronized or use

synchronized(someObject)
{
   someCode();
}

Whereas in C/C++, you have to use operating-system-specific functions to use a mutex, or you have to use the Boost library.

But the pitfalls about deadlock are all basically the same as in any language.

Tableware answered 5/7, 2011 at 14:39 Comment(2)
Thank you! But what does exactly the synchronized keyword, it is a mutex? And on differents platform, since the threads can be different does it will also be different?Robynroc
It's a mutex. A re-entrant mutex.Ecosystem
H
1

Short answers:

  1. synchronized methods and lock blocks use a monitor that locks the semaphore of the locked object for the duration of the method or block.

  2. The Java language itself does not prevent deadlocks. That's up to you as the programmer to insure that objects are locked/unlocked in the correct order to prevent contention.

Hyaloplasm answered 5/7, 2011 at 15:50 Comment(0)
C
0

You also have to take care of deadlocks in Java. The easiest way to get a deadlock is to make one thread run a block synchronized on A, and then another block synchronized on B, while another thread executes a block synchronized on B, and then a block synchronized on A.

Read the Java tutorial about concurrency. And if you want to keep learning, read Java concurrency in practice.

Cenozoic answered 5/7, 2011 at 14:38 Comment(0)
D
0

Did you try google (Java Deadlock)? First result is this: http://download.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

There you can see that with synchronized deadlocks still occur, since synchronization is not designed to prevent those in the first place.

Driscoll answered 5/7, 2011 at 14:39 Comment(2)
Well the point of my question isn't just about deadlock. I know what are deadlock and I know most of the well-known problem (philosopher dinner, etc.) It is also about internal functionnality of the synchronized keyword. I want to know more details about how it work.Robynroc
@Robynroc Did you have a look at the Oracle docs on synchronization then? It's just a chapter before the deadlock part I linked. The reponse was primarily tailored to this question: When we synchronize, how does it avoid putting thread in deadlock situation? - It doesn't.Driscoll
H
0

I see some issue with Singleton above. I think that class will never be created. Please consider below code.

public class Singleton {
     private static Singleton INSTANCE;
     private Singleton() {     }
     public static Singleton getInstance() {
         synchronized (Singleton.class) {
             if (null == INSTANCE) {
                 synchronized(Singleton.class) {
                    Singleton inst = new Singleton();
                    INSTANCE = inst;
                    }
             }
         }
         return INSTANCE;
     }
 } 
Hildegard answered 26/4, 2012 at 13:32 Comment(1)
Why would the class not be created ever?Outandout

© 2022 - 2024 — McMap. All rights reserved.