Skip to content
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

Port the StripedHashtableSpec to Scala.js #2064

Merged
merged 1 commit into from
Jun 18, 2021
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2020-2021 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats.effect
package unsafe

import cats.syntax.parallel._

import scala.concurrent.{Future, Promise}
import scala.concurrent.duration._

class StripedHashtableSpec extends BaseSpec with Runners {

override def executionTimeout: FiniteDuration = 30.seconds

def hashtableRuntime(): IORuntime =
new IORuntime(
IORuntime.defaultComputeExecutionContext,
IORuntime.defaultComputeExecutionContext,
IORuntime.defaultScheduler,
() => (),
IORuntimeConfig()
)

"StripedHashtable" should {
"work correctly in the presence of many unsafeRuns" in real {
val iterations = 10000

object Boom extends RuntimeException("Boom!")

def io(n: Int): IO[Unit] =
(n % 3) match {
case 0 => IO.unit
case 1 => IO.canceled
case 2 => IO.raiseError[Unit](Boom)
}

Resource.make(IO(hashtableRuntime()))(rt => IO(rt.shutdown())).use { rt =>
IO(new CountDownLatch(iterations)).flatMap { counter =>
(0 until iterations)
.toList
.parTraverse { n => IO(io(n).unsafeRunAsync { _ => counter.countDown() }(rt)) }
.flatMap { _ => IO.fromFuture(IO.delay(counter.await())) }
.flatMap { _ =>
IO.blocking {
rt.fiberErrorCbs.synchronized {
rt.fiberErrorCbs.tables.forall(_.isEmpty) mustEqual true
}
}
}
}
}
}
}

/**
* This implementation only works on Scala.js as it relies on a single
* threaded execution model.
*/
private final class CountDownLatch(private var counter: Int) {
private val promise: Promise[Unit] = Promise()

def countDown(): Unit = {
counter -= 1
if (counter == 0) {
promise.success(())
}
}

def await(): Future[Unit] =
promise.future
}
}