简体   繁体   English

JRuby中的并发性

[英]Concurrency in JRuby

I'm working on a Sinatra-JRuby application and handling a situation where concurrent API calls are coming to the API layer and then subsequently handled by service and adapter layer. 我正在研究Sinatra-JRuby应用程序并处理并发API调用进入API层然后由服务和适配器层处理的情况。 I'm having a GlobalService module to share the common information, so that I can access this common information from any other layer. 我正在使用GlobalService模块来共享公共信息,以便我可以从任何其他层访问此公共信息。 This works just fine until concurrent calls come and reset the value of thw previous API. 这可以正常工作,直到并发调用到来并重置以前的API的值。 Though I've implemented Mutex to address this problem, but I've got a gut feeling that this is not the right approach to the problem. 虽然我已经实现了Mutex来解决这个问题,但我有一种直觉,认为这不是解决问题的正确方法。 Here is what I've implemented: 这是我实施的内容:

require 'thread'

module GlobalService
    @@mutex = Mutex.new

    def self.set_header(auth_subject, transaction_id)
        @@mutex.synchronize {  
            @auth_subject = auth_subject
            @transaction_id = transaction_id
        }
    end

    def self.get_header
        @@mutex.synchronize { 
            return @auth_subject, @transaction_id
        }
    end
end

Please let me know of any alternative solution to address this problem. 请让我知道解决此问题的任何替代解决方案。

Sharing memory will never really be thread safe, so you might do well to use a message passing strategy. 共享内存永远不会真正是线程安全的,所以你可能会使用消息传递策略。 My preference for this would be to create actors and have them communicate about state change. 我对此的偏好是创建演员并让他们就状态变化进行沟通。 Check out Concurrent Ruby's actors http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/Actor.html . 查看Concurrent Ruby的演员http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/Actor.html

You could do something like 你可以做点什么

require 'concurrent'

class GlobalService < Concurrent::Actor::Context

  def initialize(auth_subject, transaction_id)
    @auth_subject = auth_subject
    @transaction_id = transaction_id
  end

  def on_message(message)
    #some logic 
    @auth_subject = message.auth_subject
    @transaction_id = message.transaction_id
  end
end 

service = GlobalService.spawn(:first, "header...", id) etc... service = GlobalService.spawn(:first,“header ...”,id)等...

I've used this strategy in the past and it has worked out fairly well. 我过去曾经使用过这种策略,而且效果相当好。 You may also want to ask for help over at https://gitter.im/ruby-concurrency/concurrent-ruby Pitrch is usually very helpful! 您可能还想在https://gitter.im/ruby-concurrency/concurrent-ruby上寻求帮助.Pitrch通常非常有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM