简体   繁体   中英

Where do i put the synchronization

Lets say i have a method who deals with a shared variable. Due to the complexity of the method a part of it needs to be encapsulated to another method.

So we have something like this:

private void methodA()
{
    //do something...
    //do something else...

    synchronized(shared_variable)
    {
        //do something...
        methodB(shared_variable);
        //.....
        //.....
    } 
}

now what i'd like to know is if i should synchronize the shared_variable in methodB or not. Actually i know that it is not necessary but this code somehow smells badly.

Any solution how to do things properly in such kind of situations?

PS

The reason i am asking is because later in the developement process methodB may be called outside of methodA. So if i do not put symchronization on shared_variable in methodB it wont be thread safe. But when i call methodB from methodA i have locked the shared_variable twice so it looks a litte strange to me.

By declaring synchronized(shared_variable) , you actually declare a monitor on shared_variable , that means that whenever a thread enters the synchronized block, it acquires a lock on the given object. Theoretically, no other thread will be able to achieve the monitor, until it is released by the initial thread, which happens when it completes the execution of the synchronized block (which includes the execution of methodB ).

If you do it that way, while in the scope of synchronized other threads will wait for it to exit the scope. The way it works; Without synch if one thread tries to access shared_variable and its being used by another thread, the one that is trying to access it can basically pass it without seeing the update. So if you synch it, you are not allowing the accessing thread to read it until the thread changing it has finished. Although, the thread that changes it can sometimes actually change it faster than the thread reading it allowing for no speed loss at all.

So if that is what you need then do it that way. Otherwise if you don't need the shared_variable to be accurate, you can sacrifice that for more speed. And not synchronize it.

Edit: If you synchronize the same object within a synchronize block of the same object again it is fine because the object that is locked is already inside the lock. It will just pass through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM