Skip to content

Move close operation out of synchronized block #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 9 additions & 5 deletions src/main/scala/resource/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -105,22 +105,26 @@ package object resource {
val resource = new Resource[A] {

override def close(r: A): Unit = {
lock.synchronized {
val newValue = lock.synchronized {
sharedReference match {
case Some((oldReferenceCount, sc)) =>
if (r != sc) {
throw new IllegalArgumentException
}
if (oldReferenceCount == 1) {
implicitly[Resource[A]].close(sc)
sharedReference = None
val newValue = if (oldReferenceCount == 1) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shadow newValue

None
} else {
sharedReference = Some((oldReferenceCount - 1, sc))
Some((oldReferenceCount - 1, sc))
}
sharedReference = newValue
newValue
case None =>
throw new IllegalStateException
}
}
if (newValue.isEmpty) {
implicitly[Resource[A]].close(r)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be called multiple times, which I think is unsafe, concurrency-wise

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But it will never be called multiple times for the same r instance

}
}
}

Expand Down