Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid possible redundant database initialization from multiple threads #56

Merged
merged 2 commits into from
Aug 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions lib/mini_mime.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ def binary?
end

class Db
LOCK = Mutex.new
@db = nil

def self.db
@db || LOCK.synchronize { @db ||= new }
Comment on lines +54 to +57

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
@db = nil
def self.db
@db || LOCK.synchronize { @db ||= new }
def self.db
@db ||= LOCK.synchronize { @db ||= new }

If you want to avoid the warning on older rubies. But both works I guess.

Copy link
Contributor Author

@ikaronen-relex ikaronen-relex Aug 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean a different warning than the "instance variable not initialized" one? The @db = nil line above ought to avoid that one, or at least it did when I tested this on ruby 2.6.10p210.

(The double ||= would indeed work too, but I'd rather avoid that since it makes the already somewhat complicated idiom even more confusing for the unfamiliar reader.)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I meant alternative solution to that same warning.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am ok with the implementation, its a bit of hair splitting going one way vs the other.

end

def self.lookup_by_filename(filename)
extension = File.extname(filename)
return if extension.empty?
Expand All @@ -58,14 +65,11 @@ def self.lookup_by_filename(filename)
end

def self.lookup_by_extension(extension)
@db ||= new
@db.lookup_by_extension(extension) ||
@db.lookup_by_extension(extension.downcase)
db.lookup_by_extension(extension) || db.lookup_by_extension(extension.downcase)
end

def self.lookup_by_content_type(content_type)
@db ||= new
@db.lookup_by_content_type(content_type)
db.lookup_by_content_type(content_type)
end

class Cache
Expand Down