O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Execute Around Method Pattern

Java programmers are familiar with the synchronized block. When we enter a synchronized block, it obtains a monitor (lock) on the given object. That monitor is automatically released when we leave the block. The release happens even if the code within the block throws an unhandled exception. That kind of deterministic behavior is nice to have in a number of other situations far beyond that specific example.

Thanks to function values, you can implement those constructs in Scala quite easily. Let’s look at an example.

We have a class named Resource that needs to start some transaction automatically and end the transaction deterministically as soon as we’re done using the object. We can rely on the constructor to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required