Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do if one library is not multi-threaded?

I would like to multi-thread an application, however one library i'm using is not multi-thread capable (i don't know what's the right word ? synchronized ?).

What are my options ?

As far as i know there's nothing in between threads and processes (Runtime.exec) in java (no abstraction in the jvm to have something like an isolated "java process").

How would you deal with that ?

EDIT

Thanks for all the answer, once again, one level of indirection does the trick.

like image 997
LB40 Avatar asked Nov 28 '22 11:11

LB40


1 Answers

You can ensure that the library in question is used only from a single thread at a time. If it contains instantiatable classes, one possibility is to hold these in thread local storage.

Or you can build a thread-safe wrapper around it.

These approaches could also be combined, e.g. you can wrap the library in a class (it would be a Facade in this case), which is not thread safe in itself, but whose instances you access from a single thread at a time.

Update: as @Wim pointed out, if the library manages global state, you must have a thread safe wrapper to ensure that changes are made visible between threads.

like image 197
Péter Török Avatar answered Dec 04 '22 02:12

Péter Török