Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronized keyword- Does it lock two objects?

Say I have two hash maps hashMap1 and hashMap2, and a multithreaded concurrent Java program. If I place a synchronized block

synchronized(hashMap1) {
hashMap1.put(5, "Hello");
hashMap2.put(10, "Hi");
}

Since only one thread at once can access hashMap1, will only one thread be able to access hashMap2? I am essentially asking if hashMap2 will be protected from multiple threads accessing it at once, just like hashMap1 is.

Thanks!

like image 635
BostonMan Avatar asked Mar 22 '26 15:03

BostonMan


1 Answers

No, synchronized doesn't "lock objects". What your block of code does is require a thread to take the lock on hashMap1 before it can enter the block. hashMap1 itself is not "locked" in any way, except that its monitor is being acquired. (Maybe it's clearer to call it a monitor than a lock.) The monitor is something that all objects have, in itself it doesn't do anything to control access to the object it belongs to. If hashMap2 is accessed elsewhere this sychronized block doesn't do anything to prevent that.

The purpose of the synchronized block is to require the thread to acquire the monitor. All places where you want that resource to be protected from concurrent access need to require taking that same lock. It's the code blocks protected with synchronized telling when the lock object needs to be used that control access.

The choice of monitor can be kept separate from the actual objects being protected from concurrent access. You can have a dedicated lock object and use that, there's no requirement that you have to use the lock on the things you are protecting. (The only advantage is it might help in organization, if there is only one thing you are accessing it may be convenient to use that thing's monitor.) Using a dedicated lock may be clearer:

public class Foo {
    private final Object LOCK = new Object();

    private Map hashMap1 = new HashMap();
    private Map hashMap2 = new HashMap();

    public void doStuff() {
        synchronized(LOCK) {
            ... // do stuff with hashMap1 and hashMap2
        }
    }
}

Keeping access to the lock private to the object means the object can limit who can acquire the lock (unlike with synchronized(this)). Also don't use things like Strings or Booleans that can be interned, cached, or otherwise accessed from other parts of the program.

like image 111
Nathan Hughes Avatar answered Mar 24 '26 04:03

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!