This is the mail archive of the java-patches@gcc.gnu.org mailing list for the Java project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

FileDescriptor suggestion [Was: FYI: Patch: java nio file locking]


I looked at Sun's JavaDocs for FileDescriptor, and as far as I can
tell it isn't actually useful for much.  To implement streams we
should we use nio's FileChannel.  We just need File Descriptor for
backwards compatibility.  Here is (a sketch of) an implementation that
defers creating FileDescriptor objects until needed.  It doesn't even
use a field in other objects; it just maintains a global mapping
from FileChannelImpl to FileDescriptor.  The mapping is simple
linked list, with the most recently accessed items first.

There would be no native code for FileDescritor; all the
native code woudl be in FileChannelImpl.

Is this a reasonable approach?

public class FileInputStream
{
  FileChannelImpl channel;

  public FileInputStream (FileDescriptor fd)
    throws SecurityException
  {
    SecurityManager s = System.getSecurityManager();
    if (s != null)
      s.checkRead(fd);

    channel = fd.channel;
  }

  public FileDescriptor getFD ()
  {
    return FileDescriptor.get(channel);
  }
  ...
}

public class FileDescriptor
{
  private static FileDescriptor descriptors = null;
  public static final FileDescriptor in = get(FileChannelImpl.in);
  public static final FileDescriptor out = get(FileChannelImpl.out);
  public static final FileDescriptor err = get(FileChannelImpl.err);

  private FileDescriptor next;
  private FileChannelImpl channel;

  // This constructor is specified to create an invalid descriptor.
  public FileDescriptor ()
  {
    get(new FileChannelImpl());
  }

  static synchronized FileDescriptor get(FileChannelImpl channel)
  {
    FileDescriptor prev = null, cur = descriptors;
    while (cur != null)
      {
	if (cur.channel == channel)
	  {
	    if (prev != null)
	      {
		// Move to front.
		prev.next = cur.next;
		cur.next = descriptors;
		descriptors = cur;
	      }
	    return cur;
	  }
	prev = cur;
	cur = cur.next;
      }
    cur = new FileDescriptor();
    cur.channel = channel;
    cur.next = descriptors;
    descriptors = cur;
    return cur;
  }

  public void sync () throws SyncFailedException
  {
    channel.sync();
  }
  public boolean valid ()
  {
    return channel.valid();
  }
}

--
	--Per Bothner
per@bothner.com   http://per.bothner.com/


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]