Łukasz Rzeszotarski
Łukasz Rzeszotarski

Reputation: 6140

Multiple threads in application - design convention?

Assume that in java we have some object/ group of them (service object, controllers, etc.) which we are using in our single thread application. Let's call this object by "A".

After some time we are extending our thread model and want to use these objects also in other threads (for example listener thread, etc.).

Of course in such a case we have to be aware of synchronization issues and so on. But a developer who was till now using object "A" can not be aware our architecture change and if he will add something to class/ (object) "A" he possibly may not properly handle synchronization. Of course this developer should check all occurrences of class "A" in the code, but if he is not accustomed that this class is used in multi-thread environment he may not do it.

My question is... Is there any good pattern for that situation, which marks that class/ (object) "A" as "multi-thread usable". For example implementation of some interface only for 'information' purposes, etc.

Upvotes: 2

Views: 179

Answers (2)

Szymon Jednac
Szymon Jednac

Reputation: 3007

It should be possible to create a thread-safe version of "A", if this object is loosely coupled with all its clients.

An example directly from the JDK:

java.lang.Appendable - the interface
java.lang.StringBuilder - regular implementation
java.lang.StringBuffer - thread-safe implementation

The client doesn't have to know, if it's a thread-safe version, since it's using the object indirectly, through an interface:

void doSomething(Appendable a) {
   a.append(...);
}

From a practical standpoint, using inversion of control can significantly help. Use interfaces for business contract declaration and Spring (or any other dependency injection framework) for component injection (whether it's thread-safe or not depends on the configuration only).

Bottom line: you can prevent such problems with loose coupling and smart architecture design (separation of concerns etc.).

Upvotes: 1

Chris Cooper
Chris Cooper

Reputation: 5122

I usually put a comment in the JavaDoc at the top of the code, indicating that something is intended for multi-threaded use.

I often add unit tests too, so that the use is clear.

It is then up to other developers to read the documentation and unit tests, so that they are aware of the intended usage.

Upvotes: 2

Related Questions