How to Find File Objects in JRuby?

I’d like to be able to introspect into the Ruby VM to find any open file

In MRI Ruby I can use ObjectSpace, e.g.:

files= ObjectSpace.each_object(File).to_a

…and could find a given filespec by:

ObjectSpace.each_object(File).select { |f| /input.txt/ === f.path }

Since ObjectSpace is disabled in JRuby, is there another way I could
accomplish this? The file may be opened by a gem over which I have no
control, so I can’t change the place where it’s open to hold on to the


Are you aware you can enable ObjectSpace? You use the -X+O flag. This
reduce performance as JRuby cannot currently ask the JVM to enumerate
objects, so we need to manually maintain a set of live objects.

Or are you aware of -X+O and asking for a workaround? Sorry, I’m not
of one, beyond maybe you could monkey patch File#initialize to store a
of them yourself. You’d need a way to remove dead file objects.


Chris -

Thanks for responding. I’d like to find a solution that I could use in
gem that people could use without having a requirement to set a global
like that. I guess though that I could document this issue, support the
file closing only if ObjectSpace is enabled, and let the users decide
themselves which way to go.

Is there some flag I can query at runtime to see if ObjectSpace is
enabled? I guess I could always look to see if the constant itself is
defined and points to a Module.

The monkey patch idea is interesting.

Thanks again,

You can tell if it’s enabled via

require ‘java’
enabled = org.jruby.util.cli.Options::OBJECTSPACE_ENABLED.load

Monkey patching is probably the best idea if this is really
you need to do.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs