What if one library is not multithreaded?

I need a multi-threaded application, however one library that I use does not support multi-threading (I don’t know how it is correctly synchronized?).

What are my options?

As far as I know, there is nothing between threads and processes (Runtime.exec) in java (there is no abstraction in jvm to have something like an isolated "Java process").

How do you handle this?

EDIT

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

+4
source share
5 answers

You can make sure that the library in question is used from only one thread at a time. If it contains instanceable classes, one possibility is to keep them in threaded local storage .

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

These approaches can also be combined, for example. you can wrap the library in a class (in this case it will be Facade ), which in itself is not thread safe, but whose instances you access from one thread at a time.

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

+11
source

I would create a Facade and not use the library directly. Then the facade should synchronize the connection / calls with the library.

Sort of:

External Call External Call External Call | | | ---------------------------------- Wrapper | Library 

Update:

The façade may not be the right design pattern, as it is used to hide functionality. The wrapper should be used as a design pattern.

+6
source

Alo depends on the size of the library and what you use it for. The first thing to do is evaluate where concurrency problems can occur. Just because you use a library in more than one thread does not mean that it cannot be used in multiple threads. Look for elements in the API that specifically say, “This is not thread safe,” and if you use this part of the API, you will need to synchronize it yourself. The simplest solution is to create a wrapper class that synchronizes all methods. For example, look at the source from collection utilities (e.g. Collections.synchronizedList, ect.).

+3
source

I would write a thin shell where all relevant methods are synchronized and which I will use everywhere in my code instead of using library classes and methods directly. First, I would evaluate for which parts of the library this is really necessary.

Sometimes an alternative may be to use separate instances of library objects for each stream. But in this case, instances cannot be shared between threads.

+2
source

See how a similar problem is solved in the collection API. By default, all collections are not thread safe.

But when you need a thread safe collection, you just get it with

 Collections.synchronizedCollection(unsafeCollection) 

The implementation is hidden from the user and is not part of the API. You can go the same way.

+2
source

Source: https://habr.com/ru/post/1304876/


All Articles