View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.unix;
17  
18  import java.io.IOException;
19  
20  /**
21   * Native {@link FileDescriptor} implementation which allows to wrap an {@code int} and provide a
22   * {@link FileDescriptor} for it.
23   */
24  public class FileDescriptor {
25  
26      private final int fd;
27      private volatile boolean open = true;
28  
29      public FileDescriptor(int fd) {
30          if (fd < 0) {
31              throw new IllegalArgumentException("fd must be >= 0");
32          }
33          this.fd = fd;
34      }
35  
36      /**
37       * Return the int value of the filedescriptor.
38       */
39      public int intValue() {
40          return fd;
41      }
42  
43      /**
44       * Close the file descriptor.
45       */
46      public void close() throws IOException {
47          open = false;
48          close(fd);
49      }
50  
51      /**
52       * Returns {@code true} if the file descriptor is open.
53       */
54      public boolean isOpen() {
55          return open;
56      }
57  
58      @Override
59      public String toString() {
60          return "FileDescriptor{" +
61                  "fd=" + fd +
62                  '}';
63      }
64  
65      @Override
66      public boolean equals(Object o) {
67          if (this == o) {
68              return true;
69          }
70          if (!(o instanceof FileDescriptor)) {
71              return false;
72          }
73  
74          return fd == ((FileDescriptor) o).fd;
75      }
76  
77      @Override
78      public int hashCode() {
79          return fd;
80      }
81  
82      private static native int close(int fd);
83  }