Video in progress

How do you safely use a legacy library that isn't thread-safe (for example, a vendor SDK client) in a high-load service?

First I find out from the docs and the code whether the object is not thread-safe at all or only partly. Then I pick an option: a separate instance per call or per thread, a bounded pool of objects, or confining it to one thread. The last resort is a separate process.

📖 Answer

The choice depends on two things: how expensive the object is to create, and what state it keeps inside.

Approach When Cost
a new instance per call creation is cheap allocation, sometimes opening a connection
a ThreadLocal instance expensive, and the state belongs to the thread with virtual threads, one instance each, plus cleanup
a pool of objects expensive (connection, session) pool size = concurrency limit
confinement to one thread the state is global and order matters one thread is the throughput ceiling
a separate process native crashes or leaks IPC, deployment complexity

A pool is often the most practical option:

final class VendorClientPool {
    private final BlockingQueue<VendorClient> idle;

    VendorClientPool(int size, Supplier<VendorClient> factory) {
        idle = new ArrayBlockingQueue<>(size);
        for (int i = 0; i < size; i++) idle.add(factory.get());
    }

    <T> T withClient(Function<VendorClient, T> work) throws InterruptedException {
        VendorClient c = idle.poll(500, TimeUnit.MILLISECONDS);
        if (c == null) throw new ServiceBusyException();
        try {
            return work.apply(c);
        } finally {
            idle.offer(c);   // if a broken client must not go back, check for it here
        }
    }
}

This is also a bulkhead: no more than size requests go to the vendor at once. A ready-made option is Apache Commons Pool2, with validation, eviction and metrics.

Architecture-level rules:

  • an adapter layer: call the library through a single class only. The thread-safety decision sits in one place, and replacing the library later is easy;
  • "not thread-safe" is often not written down in the docs, so I check it myself with a stress test (many threads, verifying the result invariants);
  • if there's static global state inside, neither a pool nor ThreadLocal helps: only confinement to one thread or a separate process;
  • talk to the vendor: often a newer version has a thread-safe client, and migrating is cheaper than anything else.