Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions lib/future-resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,18 @@
# p fr.resource
#
class FutureResource

NULL = Object.new
private_constant :NULL

##
# Create a new FutureResource.
#
def initialize(blocker = nil)
@resource_lock = Monitor.new
@resource_value_blocker = blocker || @resource_lock.new_cond
@terminated = false
@resource = NULL
end

##
Expand All @@ -35,7 +40,7 @@ def initialize(blocker = nil)
# @return [Boolean]
#
def set_yet?
!!@resource_lock.synchronize { defined? @resource }
@resource_lock.synchronize { ! @resource.equal?(NULL) }
end

##
Expand All @@ -44,7 +49,7 @@ def set_yet?
# @return [Boolean]
#
def terminated?
!!@resource_lock.synchronize { @terminated }
@resource_lock.synchronize { @terminated }
end

##
Expand All @@ -61,12 +66,11 @@ def terminated?
# @return [Object]
#
def resource(timeout = nil)
Timeout::timeout timeout do
@resource_lock.synchronize do
@resource_value_blocker.wait unless set_yet? or terminated?
raise Terminated if terminated?
@resource
end
@resource_lock.synchronize do
@resource_value_blocker.wait(timeout) unless set_yet? || terminated?
raise Terminated if terminated?
raise Timeout.new(timeout.to_s) if @resource.equal?(NULL)
@resource
end
end

Expand Down Expand Up @@ -116,6 +120,8 @@ def initialize
end
end

Timeout = ::Timeout::Error

private

def set_or_terminate
Expand Down
12 changes: 9 additions & 3 deletions spec/future-resource_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
it { should be_set_yet }
it { should_not be_terminated }

its(:resource) { should === :foo }
it "should have resource set" do
expect(subject.resource).to be :foo
end

it "should raise ResourceAlreadySetException when setting value that is already set" do
expect {
Expand Down Expand Up @@ -65,7 +67,11 @@
sleep 1
subject.resource = :foo
end
subject.resource.should === :foo
expect(subject.resource).to be :foo
end

it "should raise on timeout" do
expect { subject.resource(0.5) }.to raise_error FutureResource::Timeout
end

it "should allow an alternative condition to be provided" do
Expand All @@ -74,6 +80,6 @@
sleep 1
subject.resource = :foo
end
subject.resource.should === :foo
expect(subject.resource).to be :foo
end
end