Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The class OpenedFile in the following non-compliant code example opens a file during deserialization.  Operating systems typically impose a limit on the number of open file handles per process; this limit typically is not large (e.g., 1024).  Consequently, deserializing a list of OpenedFile objects can consume all file handles available to the process and consequently cause the program to malfunction if it attempts to open another file before the deserialized OpenedFile objects get garbage-collected.

Code Block
bgColor#FFcccc
languagejava
import java.io.*;

class OpenedFile implements Serializable {
  public String filename;
  public BufferedReader reader;

  public OpenedFile(String _filename) {
    filename = _filename;
    init();
  }
  private void init() {
    try {
      reader = new BufferedReader(new FileReader(filename));
    } catch (FileNotFoundException e) { }
  }
    
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeUTF(filename);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    filename = in.readUTF();
    init();
  }
} 

...