If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method

If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method The answer depends on the context. If you are in a synchronized method for an object, then calls by other threads to other methods of the same object instance that are also synchronized are locked. However calls by other … Read more

Should you synchronize the run method? Why or why not?

Synchronizing the run() method of a Runnable is completely pointless unless you want to share the Runnable among multiple threads and you want to sequentialize the execution of those threads. Which is basically a contradiction in terms. There is in theory another much more complicated scenario in which you might want to synchronize the run() … Read more

Java Multithreading concept and join() method

You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances. However, you can use join() to wait for a thread to complete its work. For example, in your case ob1.t.join(); This statement will not return until thread t has finished running. Try … Read more

What is the difference between a synchronized method and synchronized block in Java? [duplicate]

A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks uses the expression as a lock. So the following two methods are equivalent from locking prospective: synchronized void mymethod() { … } void mymethod() { synchronized (this) { … } … Read more

What is the difference between synchronized on lockObject and using this as the lock?

Personally I almost never lock on “this”. I usually lock on a privately held reference which I know that no other code is going to lock on. If you lock on “this” then any other code which knows about your object might choose to lock on it. While it’s unlikely to happen, it certainly could … Read more

Is ConcurrentHashMap totally safe?

The get() method is thread-safe, and the other users gave you useful answers regarding this particular issue. However, although ConcurrentHashMap is a thread-safe drop-in replacement for HashMap, it is important to realize that if you are doing multiple operations you may have to change your code significantly. For example, take this code: if (!map.containsKey(key)) return … Read more

Java Synchronized Block for .class

The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block. With synchronized(this) the block is guarded by the instance. For every instance only one thread may enter the block. synchronized(X.class) is used to … Read more