-->

Using threadsafe initialization in a JRuby gem

2019-08-14 04:51发布

问题:

Wanting to be sure we're using the correct synchronization (and no more than necessary) when writing threadsafe code in JRuby; specifically, in a Puma instantiated Rails app.

UPDATE: Extensively re-edited this question, to be very clear and use latest code we are implementing. This code uses the atomic gem written by @headius (Charles Nutter) for JRuby, but not sure it is totally necessary, or in which ways it's necessary, for what we're trying to do here.

Here's what we've got, is this overkill (meaning, are we over/uber-engineering this), or perhaps incorrect?

ourgem.rb:

require 'atomic'  # gem from @headius

SUPPORTED_SERVICES = %w(serviceABC anotherSvc andSoOnSvc).freeze

module Foo

  def self.included(cls)
    cls.extend(ClassMethods)
    cls.send :__setup
  end

  module ClassMethods
    def get(service_name, method_name, *args)
      __cached_client(service_name).send(method_name.to_sym, *args)
      # we also capture exceptions here, but leaving those out for brevity
    end

    private

    def __client(service_name)
      # obtain and return a client handle for the given service_name
      # we definitely want to cache the value returned from this method
      # **AND**
      # it is a requirement that this method ONLY be called *once PER service_name*.
    end

    def __cached_client(service_name)
      @@_clients.value[service_name]
    end

    def __setup
      @@_clients = Atomic.new({})
      @@_clients.update do |current_service|
        SUPPORTED_SERVICES.inject(Atomic.new({}).value) do |memo, service_name|
          if current_services[service_name]
            current_services[service_name]
          else
            memo.merge({service_name => __client(service_name)})
          end
        end
      end
    end
  end
end

client.rb:

require 'ourgem'

class GetStuffFromServiceABC
  include Foo

  def self.get_some_stuff
    result = get('serviceABC', 'method_bar', 'arg1', 'arg2', 'arg3')
    puts result
  end
end

Summary of the above: we have @@_clients (a mutable class variable holding a Hash of clients) which we only want to populate ONCE for all available services, which are keyed on service_name.

Since the hash is in a class variable (and hence threadsafe?), are we guaranteed that the call to __client will not get run more than once per service name (even if Puma is instantiating multiple threads with this class to service all the requests from different users)? If the class variable is threadsafe (in that way), then perhaps the Atomic.new({}) is unnecessary?

Also, should we be using an Atomic.new(ThreadSafe::Hash) instead? Or again, is that not necessary?

If not (meaning: you think we do need the Atomic.news at least, and perhaps also the ThreadSafe::Hash), then why couldn't a second (or third, etc.) thread interrupt between the Atomic.new(nil) and the @@_clients.update do ... meaning the Atomic.news from EACH thread will EACH create two (separate) objects?

Thanks for any thread-safety advice, we don't see any questions on SO that directly address this issue.

回答1:

Just a friendly piece of advice, before I attempt to tackle the issues you raise here:

This question, and the accompanying code, strongly suggests that you don't (yet) have a solid grasp of the issues involved in writing multi-threaded code. I encourage you to think twice before deciding to write a multi-threaded app for production use. Why do you actually want to use Puma? Is it for performance? Will your app handle many long-running, I/O-bound requests (like uploading/downloading large files) at the same time? Or (like many apps) will it primarily handle short, CPU-bound requests?

If the answer is "short/CPU-bound", then you have little to gain from using Puma. Multiple single-threaded server processes would be better. Memory consumption will be higher, but you will keep your sanity. Writing correct multi-threaded code is devilishly hard, and even experts make mistakes. If your business success, job security, etc. depends on that multi-threaded code working and working right, you are going to cause yourself a lot of unnecessary pain and mental anguish.

That aside, let me try to unravel some of the issues raised in your question. There is so much to say that it's hard to know where to start. You may want to pour yourself a cold or hot beverage of your choice before sitting down to read this treatise:

When you talk about writing "thread-safe" code, you need to be clear about what you mean. In most cases, "thread-safe" code means code which doesn't concurrently modify mutable data in a way which could cause data corruption. (What a mouthful!) That could mean that the code doesn't allow concurrent modification of mutable data at all (using locks), or that it does allow concurrent modification, but makes sure that it doesn't corrupt data (probably using atomic operations and a touch of black magic).

Note that when your threads are only reading data, not modifying it, or when working with shared stateless objects, there is no question of "thread safety".

Another definition of "thread-safe", which probably applies better to your situation, has to do with operations which affect the outside world (basically I/O). You may want some operations to only happen once, or to happen in a specific order. If the code which performs those operations runs on multiple threads, they could happen more times than desired, or in a different order than desired, unless you do something to prevent that.

It appears that your __setup method is only called when ourgem.rb is first loaded. As far as I know, even if multiple threads require the same file at the same time, MRI will only ever let a single thread load the file. I don't know whether JRuby is the same. But in any case, if your source files are being loaded more than once, that is symptomatic of a deeper problem. They should only be loaded once, on a single thread. If your app handles requests on multiple threads, those threads should be started up after the application has loaded, not before. This is the only sane way to do things.

Assuming that everything is sane, ourgem.rb will be loaded using a single thread. That means __setup will only ever be called by a single thread. In that case, there is no question of thread safety at all to worry about (as far as initialization of your "client cache" goes).

Even if __setup was to be called concurrently by multiple threads, your atomic code won't do what you think it does. First of all, you use Atomic.new({}).value. This wraps a Hash in an atomic reference, then unwraps it so you just get back the Hash. It's a no-op. You could just write {} instead.

Second, your Atomic#update call will not prevent the initialization code from running more than once. To understand this, you need to know what Atomic actually does.

Let me pull out the old, tired "increment a shared counter" example. Imagine the following code is running on 2 threads:

 i += 1

We all know what can go wrong here. You may end up with the following sequence of events:

  1. Thread A reads i and increments it.
  2. Thread B reads i and increments it.
  3. Thread A writes its incremented value back to i.
  4. Thread B writes its incremented value back to i.

So we lose an update, right? But what if we store the counter value in an atomic reference, and use Atomic#update? Then it would be like this:

  1. Thread A reads i and increments it.
  2. Thread B reads i and increments it.
  3. Thread A tries to write its incremented value back to i, and succeeds.
  4. Thread B tries to write its incremented value back to i, and fails, because the value has already changed.
  5. Thread B reads i again and increments it.
  6. Thread B tries to write its incremented value back to i again, and succeeds this time.

Do you get the idea? Atomic never stops 2 threads from running the same code at the same time. What it does do, is force some threads to retry the #update block when necessary, to avoid lost updates.

If your goal is to ensure that your initialization code will only ever run once, using Atomic is a very inappropriate choice. If anything, it could make it run more times, rather than less (due to retries).

So, that is that. But if you're still with me here, I am actually more concerned about whether your "client" objects are themselves thread-safe. Do they have any mutable state? Since you are caching them, it seems that initializing them must be slow. Be that as it may, if you use locks to make them thread-safe, you may not be gaining anything from caching and sharing them between threads. Your "multi-threaded" server may be reduced to what is effectively an unnecessarily complicated, single-threaded server.

If the client objects have no mutable state, good for you. You can be "free and easy" and share them between threads with no problems. If they do have mutable state, but initializing them is slow, then I would recommend caching one object per thread, so they are never shared. Thread[] is your friend there.