root/lang/perl/Data-Valve/trunk/lib/Data/Valve/BucketStore/WithKeyedMutex.pm @ 15788

Revision 15788, 1.1 kB (checked in by daisuke, 6 years ago)

refactor where the lock mechanism is

  • Property svn:keywords set to Id
Line 
1# $Id$
2
3package Data::Valve::BucketStore::WithKeyedMutex;
4use Moose::Role;
5use Moose::Util::TypeConstraints;
6
7use KeyedMutex;
8
9class_type 'KeyedMutex';
10
11coerce 'KeyedMutex'
12    => from 'HashRef'
13        => via {
14            my $h = $_;
15            KeyedMutex->new($h->{args});
16        }
17;
18
19has 'mutex' => (
20    is => 'rw',
21    isa => 'KeyedMutex',
22    coerce => 1,
23);
24
25no Moose;
26
27sub BUILD {
28    my $self = shift;
29
30    # if no keyedmutex was provided explicitly, we attempt to create one
31    # however, if the creation of this object fails, well, we can go
32    # without it in degraded mode
33    if ( ! $self->mutex ) {
34        my $mutex = eval {KeyedMutex->new };
35        if ($mutex) {
36            $self->mutex($mutex);
37        } else {
38            warn $@;
39        }
40    }
41}
42
43sub lock {
44    my ($self, $key) = @_;
45
46    my $mutex = $self->mutex;
47    return 1 unless $mutex;
48    my $rv = eval { $mutex->lock($key, 1) };
49    # if in case an error has been reported, we should ditch the mutex,
50    # cause it will keep giving errors (or worse yet, crash)
51    if ($@) {
52        $self->mutex(undef);
53    }
54    return $rv;
55}
56
571;
Note: See TracBrowser for help on using the browser.