Happens-before relationships with volatile fields and synchronized blocks in Java – and their impact on non-volatile variables?

Yes, it is guaranteed that thread 2 will print “done” . Of course, that is if the write to b in Thread 1 actually happens before the read from b in Thread 2, rather than happening at the same time, or earlier! The heart of the reasoning here is the happens-before relationship. Multithreaded program executions … Read more

Synchronization of non-final field

First of all, I encourage you to really try hard to deal with concurrency issues on a higher level of abstraction, i.e. solving it using classes from java.util.concurrent such as ExecutorServices, Callables, Futures etc. That being said, there’s nothing wrong with synchronizing on a non-final field per se. You just need to keep in mind … Read more

Is HttpSession thread safe, are set/get Attribute thread safe operations?

Servlet 2.5 spec: Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a threadsafe manner. The Developer has the responsibility for threadsafe access to the attribute objects themselves. This … Read more

Java synchronized static methods: lock on object or class

Just to add a little detail to Oscar’s (pleasingly succinct!) answer, the relevant section on the Java Language Specification is 8.4.3.6, ‘synchronized Methods’: A synchronized method acquires a monitor (ยง17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method’s class is used. For an instance method, … Read more

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Can anyone tell me the advantage of the synchronized method over the synchronized block with an example? Thanks. There is not a clear advantage of using synchronized method over the block. Perhaps the only one ( but I wouldn’t call it an advantage ) is you don’t need to include the object reference this. Method: … Read more