matanox
matanox

Reputation: 13686

How to pool instances of a Java-legacy non-thread-safe object, for parallel computation

I am looking for patterns and api for managing with a Java object that is not thread safe, in the case that a parallel computation needs to use this object. This is applicable to database connections as well as other kinds of objects in my case (and in general).

The specific parallel scenario I am looking at is simply a Scala parallel collection that is being foreached, whereas within the foreach clause, the object needs to be used. Since the Java object at hand is mutable and not safe for concurrency, that is not supposed to work.

There is a nice suggestion here for that, in pure Java, and other ones also Java. I wonder if higher elegance can be accomplished in Scala.

Upvotes: 1

Views: 143

Answers (1)

Soumya Simanta
Soumya Simanta

Reputation: 11741

I have faced this problem and solved this using Actors.

Each actor has access to the mutable object and it can only be modified using messages. In my case the mutable objects were heavy and have significant creation cost. In order to minimize that I created a bunch of them in the start and placed them behind an Akka router (smallestMailbox worked the best for my case). I've not seen a Future based approach to solve this problem yet.

Upvotes: 2

Related Questions