Forum: JRuby How to Find File Objects in JRuby?

486ca04f06d968004643ce5b47376ded?d=identicon&s=25 Keith B. (keith_b)
on 2014-03-21 23:04
(Received via mailing list)
I'd like to be able to introspect into the Ruby VM to find any open file
objects.

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
handle.

Thanks,
Keith
D0b0965afa66f2cabf76a8128b39e7c6?d=identicon&s=25 Chris Seaton (Guest)
on 2014-03-21 23:37
(Received via mailing list)
Are you aware you can enable ObjectSpace? You use the -X+O flag. This
will
reduce performance as JRuby cannot currently ask the JVM to enumerate
live
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
aware
of one, beyond maybe you could monkey patch File#initialize to store a
list
of them yourself. You'd need a way to remove dead file objects.

Chris
486ca04f06d968004643ce5b47376ded?d=identicon&s=25 Keith B. (keith_b)
on 2014-03-22 00:29
(Received via mailing list)
Chris -

Thanks for responding.  I'd like to find a solution that I could use in
a
gem that people could use without having a requirement to set a global
flag
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
for
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 File.open monkey patch idea is interesting.

Thanks again,
Keith
D0b0965afa66f2cabf76a8128b39e7c6?d=identicon&s=25 Chris Seaton (Guest)
on 2014-03-22 00:46
(Received via mailing list)
You can tell if it's enabled via

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

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

Chris
This topic is locked and can not be replied to.