# Mutex

**URL:** <https://rubytalk.org/t/mutex/58326>\
**Category:** ruby-talk\
**Created:** [28 April 2010 11:39 UTC](https://rubytalk.org/t/mutex/58326 "2010-04-28T11:39:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Oliver\_Cat](https://avatars.discourse-cdn.com/v4/letter/o/a9adbd/32.png) [@Oliver\_Cat](https://rubytalk.org/u/Oliver_Cat)\
**Post date:** [28 April 2010 11:39 UTC](https://rubytalk.org/t/mutex/58326/1 "2010-04-28T11:39:16Z")

</div>

Hi all,  
I've been reading the RailsDispatch blog, and have been looking at this  
code.

class BlacklistConstraint  
&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;@ips = Blacklist.retrieve\_ips  
&nbsp;&nbsp;&nbsp;&nbsp;@mutex = Mutex.new  
&nbsp;&nbsp;&nbsp;&nbsp;@last\_update = Time.now  
&nbsp;&nbsp;end

&nbsp;&nbsp;def matches?(request)  
&nbsp;&nbsp;&nbsp;&nbsp;@mutex.synchronize do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (Time.now - @last\_update) \> 3600  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@ips = Blacklist.retrieve\_ips  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@last\_update = Time.now  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;!@ips.include?(request.remote\_ip)  
&nbsp;&nbsp;end  
end

What interests me is the 'matches?' method, specifically the  
mutex.synchronize block. I'm wondering what is the benefit of this code,  
and how it works?

Is it so other attempts to call Blacklist.retrieve\_ips are blocked, and  
if so, should the mutex be implemented in the Blacklist class?

thanks for reading.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [28 April 2010 14:06 UTC](https://rubytalk.org/t/mutex/58326/2 "2010-04-28T14:06:41Z")

</div>

Oliver Cat wrote:

> What interests me is the 'matches?' method, specifically the  
> mutex.synchronize block. I'm wondering what is the benefit of this code,  
> and how it works?
> 
> Is it so other attempts to call Blacklist.retrieve\_ips are blocked, and  
> if so, should the mutex be implemented in the Blacklist class?

Only one instance of the code inside @mutex.synchronize { ... } can be  
executing at any one time ("mutex" = "mutual exclusion")

Without this mutex, it would be possible that two threads which called  
BlacklistConstraint#matches? concurrently, when the cache is more than 1  
hour old, could end up calling Blacklist.retrieve\_ips concurrently.

This might not be catastrophic if Blacklist.retrieve\_ips were  
thread-safe, but it would be wasteful. (Presumably  
Blacklist.retrieve\_ips is an expensive operation, given that it is being  
cached)

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
