views:

77

answers:

4

Design problem :

Using a non-thread-safe component (Collection, API, ...) in/with a multithread component ...

Example :

component1 : A multithread socket server who send messages ... to a message handler

component2 : A non-thread-safe message handler who process messages ... from a server

My solution :

Adding a thread-safe component ( buffer ) between the server and the message handler, the buffer will receive messages in multithread manner from the server and send them in the same order to the message handler in a single thread manner.

My question :

Is there a better solution ? an appropriate design pattern may be proxy or pipeline ?

+3  A: 

I personally like the "message queue" approach: works reliably, good de-coupling characteristics and is simple to implement.

jldupont
+3  A: 

One common approach is to simply guard the non-thread safe API with coarse grained locks or create a thin wrapper that takes care of the locking

nos
+5  A: 

One very nice option for this is to use a Producer/Consumer pattern.

In this case, the multithreaded sockets can act as multiple producers into a guarded buffer, and your non-threadsafe message handler can consume messages in its own thread, completely synchronously. This provides a very clean way to handle this type of scenario.

Reed Copsey
+1  A: 

Depending on what makes the Component2 not thread-safe ...

Creating instances of your component2 as needed :
Each instance is accessed only by one thread, so your system might behave correctly as a whole. You can analyze if it is ok...

KLE