You should be aware that your implementation of FooCounter not thread safe. If multiple threads call the get , set and inc methods at the same time, there is no guarantee that the count will be accurate. To implement the correct parallel counter, you must use one of the following utilities:
- Operator
synchronized (Scala synchronized statement is similar to one in Java )- atomic variables
- STM (e.g. ScalaSTM )
- perhaps you can use the accra Akka, which is the counter, but note that this is not the easiest application of the actors.
Other Scala concurrency utilities, such as futures and promises, parallel collections, or reactive extensions, are not suitable for implementing a parallel counter and have different uses.
You should be aware that Scala reuses the Java concurrency framework in some cases. For example, Scala does not provide its own atomic variables, since Java classes already do the job. Instead, Scala aims to provide higher level abstractions of concurrency, such as subjects, STMs, and asynchronous event streams.
Benchmarking
ScalaMeter is a good choice to evaluate the uptime and effectiveness of your implementation. The online documentation on the website contains detailed examples of how to benchmark.
Documentation and concurrency libraries
While Akka is the most popular and most well-documented Scala concurrency utility, there are many other high-quality implementations, some of which are more suitable for different tasks:
I think Scala Learning Parallel Programming might be a good book for you. It contains detailed documentation on the various concurrency styles in Scala, as well as instructions on when to use them. Chapters 5 and 9 also deal with benchmarking. In particular, the scalable parallel counter utility in chapter 9 of the book is described, optimized, and executed.
Disclaimer: I am the author.
source share