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

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 method lock on object, or method?

If you declare the method as synchronized (as you’re doing by typing public synchronized void addA()) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway. If you want to synchronize only on one variable at a time, so two threads won’t block … 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

Synchronizing on String objects in Java

Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings: final String firstkey = “Data-” + email; final String key = firstkey.intern(); Two Strings with the same value are otherwise not necessarily the same object. Note that this may introduce … 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