-4

i know this may get a down vote this is bothering me a lot

i have already read all posts on .close() method like

explain the close() method in Java in Layman's terms

Why do I need to call a close() or shutdown() method?

the usage of close() method(Java Beginner)

i have these questions which may seem too trivial

1.what does the word 'resource' exactly mean (is it the file or the 'FileWriter' object or some other thing)(try to explain as broadly as possible)

lets consider following code

import java.io.*;
public class characterstreams
{
    public static void main(String []args) throws Exception
    {
        File f=new File("thischaracter.txt");
        FileWriter fw=new FileWriter(f);
        char[] ch={'a','c','d'};
        fw.write('a');
        fw.write(ch);
        fw.write("aaaa aaaaa aaaaaaa");
        fw.flush();
        FileReader fr=new FileReader(f);
        int r=fr.read();
        System.out.println(r);
        char[] gh=new char[30];
        System.out.println(fr.read(gh));
    }
}

after compiling and executing it

G:/>java characterstreams

lets say resource is FileWriter below (since i have yet to get the meaning of resources)

JVM starts and opens up so-called resources and then execution completes and after which JVM get shuts down after execution

2.it unlocks the resource that it has opened since it's not running right (correct me if i am wrong)

G:/>

at this point JVM is not running

3.before shuting down , garbage collector is called right ?(correct me if am wrong) so FileWriter objects get destroyed then why are we supposed to close all the resources that we have opened up

and

4.again i read that 'resources get leaked' what does this supposed to mean..?

Community
  • 1
  • 1
manifold
  • 437
  • 6
  • 23
  • 1
    You are thinking about a small, self-contained example. There are countless cases where that would not apply. What if part of your program stays in memory indefinitely (e.g. daemon threads)? Or if it leaves the impacted file system resource in an inconsistent state due to your application terminating "incorrectly"? Etc. Etc. – Mena May 24 '16 at 09:18
  • @Mena what does resource exactly mean...i have risked down vote so try and explain me... – manifold May 24 '16 at 09:25
  • A resource is provided by the OS (disks access, sockets ...) – mvera May 24 '16 at 09:53

1 Answers1

3

resource means anything which is needed by the JVM and/or operating system to provide you with the functionality you request.

Taken your example. If you open a FileWriter the operating system in general (depends on the operating system, file system, etc.) will do (assuming you want to write a file to a disc, like HDD/SDD)

  1. create a directory entry for the requested filename
  2. create a data structure to maintain the writing process to the file
  3. allocate disc space if you actually write data to the file

(note: this is not an exhaustive list)

The point will be done for any file you open for writing. If you don't close the resource all this remains in the memory and is still maintained by the operating system.

Assume your application is running over a long time and is constantly opening files. The number of open file the operating system allows you to keep open is limited (the concrete number depends on the operating system, quota settings, ...). If the resources are exhausted something will behave unexpected or fail.

Find below a small demonstration on Linux.

public static void main(String[] args) throws IOException {
    List<OutputStream> files = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        files.add(Files.newOutputStream(Paths.get("/tmp/demo." + i), 
                StandardOpenOption.CREATE));
    }
}

The code open one-thousend file for writing.

Assume your limit of open files is 1024

ulimit -n
1024

you run the snippet and it will generate 1000 files /tmp/demo.*.

If your limit of open files is only 100 the code will fail

ulimit -n 100
java.nio.file.FileSystemException: /tmp/demo.94: Too many open files

(it fails before as the JVM itself has some open files)

To prevent such problems (lack of resources) you should close files which you don't need any longer to write to. If you don't do it in Java(close()) the operating system also doesn't know if the memory etc. can be freed and used for another request.

SubOptimal
  • 22,518
  • 3
  • 53
  • 69