Matt Greencroft has his say

Matt's Blog

Java Advanced Tools - Errata for Thread Safety

04-Jul-2017 in Errata Core Java Threading

In Chapter 20 of the Java Advanced Topics course (the video on Synchronization and Thread Safety), at about 20 mins 15 seconds, I explain that you tend to use the synchronized keyword with the smallest possible code block. I demonstrate this with the following code:

Unfortunately, for the example we have been looking at, this wouldn’t be thread safe! It would be possible, if a thread was interrupted after the synchronized block, but before the return statement, for 2 threads to be given the same number.

Thank you to one of our customers who pointed this out today – the synchronized keyword needs to be around the minimum part of the code that should not be interrupted. In this example it would need to be the entire method.

Listen via:

About Matt

I'm a Java developer and trainer for Virtual Pair Programmers, where I present video based training courses on Java, Spring and associated frameworks. I'm currently working on a few different web projects.

Be notified of new posts