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 ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.