# Mutex

**URL:** <https://www.ruby-forum.com/t/mutex/187731>\
**Category:** Ruby\
**Created:** [April 28, 2010, 1:39pm UTC](https://www.ruby-forum.com/t/mutex/187731 "2010-04-28T13:39:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![olicat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/a8b319/32.png) [@olicat](https://www.ruby-forum.com/u/olicat)\
**Post date:** [April 28, 2010, 1:39pm UTC](https://www.ruby-forum.com/t/mutex/187731/1 "2010-04-28T13:39:13Z")

</div>

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

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

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

```
!@ips.include?(request.remote_ip)

```

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.

---

<div class="post-metadata">

**Author:** ![olicat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/a8b319/32.png) [@olicat](https://www.ruby-forum.com/u/olicat)\
**Post date:** [April 28, 2010, 4:06pm UTC](https://www.ruby-forum.com/t/mutex/187731/2 "2010-04-28T16:06:39Z")

</div>

Oliver C. 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)
