refactor a bit to add more thread safety
fix jruby