|
Revision 15788, 1.1 kB
(checked in by daisuke, 5 years ago)
|
|
refactor where the lock mechanism is
|
-
Property svn:keywords set to
Id
|
| Line | |
|---|
| 1 | # $Id$ |
|---|
| 2 | |
|---|
| 3 | package Data::Valve::BucketStore::WithKeyedMutex; |
|---|
| 4 | use Moose::Role; |
|---|
| 5 | use Moose::Util::TypeConstraints; |
|---|
| 6 | |
|---|
| 7 | use KeyedMutex; |
|---|
| 8 | |
|---|
| 9 | class_type 'KeyedMutex'; |
|---|
| 10 | |
|---|
| 11 | coerce 'KeyedMutex' |
|---|
| 12 | => from 'HashRef' |
|---|
| 13 | => via { |
|---|
| 14 | my $h = $_; |
|---|
| 15 | KeyedMutex->new($h->{args}); |
|---|
| 16 | } |
|---|
| 17 | ; |
|---|
| 18 | |
|---|
| 19 | has 'mutex' => ( |
|---|
| 20 | is => 'rw', |
|---|
| 21 | isa => 'KeyedMutex', |
|---|
| 22 | coerce => 1, |
|---|
| 23 | ); |
|---|
| 24 | |
|---|
| 25 | no Moose; |
|---|
| 26 | |
|---|
| 27 | sub 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 | |
|---|
| 43 | sub 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 | |
|---|
| 57 | 1; |
|---|