colly icon indicating copy to clipboard operation
colly copied to clipboard

Safely unlock Collector Mutex in defer clause

Open maciej opened this issue 4 years ago • 0 comments

Using defers to unlock mutexes is safer. If the code holding the mutex ever panics (eg. a bug is introduced) defer will guarantee that it gets unlock and Collector will not stay in an invalid state.

Since Go 1.14 there is no reason not to use defer: https://twitter.com/janiszt/status/1215601972281253888

Previously performance might have been a concern. It no longer will be

Citing Effective Go:

Defer

Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file.

maciej avatar Jan 29 '20 19:01 maciej