Search code examples
ruby-on-railsrubymutexsynchronize

When I use ruby Mutex, but data still repeat


My code like this:

class MessagesController < ApplicationController
@@m = Mutex.new
def index
 @@m.synchronize do
   Message.transaction do
     m = Message.find_by_msg_id(params[:msg_id])
     if m.nil?
       mess = Message.new(:msg_id => params[:msg_id], ......)
       mess.save!
       ......
     end
   end
 end
end
end

Now the question is messages in the database still have the same msg_id. Please help me...


Solution

  • It all depends on how you run your server - rails runs as a single threaded app with most servers. There are servers (like passenger) which run the server as multi process, which means that concurrency is achieved by running more than one service. On greater scale - instances might be running on a cluster (different machines).

    In all those cases, creating a Mutex will not achieve what you are looking for. The scope of the Mutex you created is within the same process.

    To make sure you don't have the same msg_id in the db, you must make the validation in the db (like using a unique column, use stored procedures, etc.)