What is a resource in java? Why should we close it after using it?

What is the meaning of the word "resource" in java? Why should we close it after use, although the garbage collector works in jvm? Why should we write resource cleanup code in a finally block?

+4
java garbage-collection
source share
4 answers

A resource is something that has a limited number, for example, database connections and file descriptors. GC frees up memory, but you still have to allocate resources, such as DB connections, open files, etc., so that other threads can use them.

By the way, it is better to free resources immediately after using them, and not just in the finalize method, which can take a long time until it is called by GC.

+10
source share

A database connection, a stream, a file descriptor, a socket are all finite resources.

The operating system you are running on allows so many threads - 1 MB of overhead per thread. You are limited by available RAM. The same goes for file descriptors and sockets.

Database connections are interesting because they are connected to the client and server. If the gc client is connected, what tells the server to close the connection? If you fail to complete the lock at the end of the blocks, you will soon find out that connections with heavy load will work on your database server.

Finishing is not the right way. Do not depend on the virtual machine to call it. Write a close() method and call it in the finally block when your method executes with the resource. Close in the narrowest volume.

+7
source share

Say you have a file, you can write to it and not close the resource, and in the end it will be closed by GC. The problem is that while the file is open, you cannot delete it on Windows, but on Linux you can delete it, but it does not free up space. If you want to delete a file, you do not want to wait until the GC runs, perhaps in a few hours.

+5
source share

What does the word β€œresource” mean in Java?

A typical Java application manipulates several types of resources, such as files, streams, sockets, and database connections.

Why should we write resource cleanup code in a finally block?

An Oracle article introduces Java 7's answer to the problem of automatic resource management .

  1. Such resources must be handled with great care , because they acquire system resources for their operations. Thus, you need to make sure that they are freed even in case of errors .

  2. Indeed, mismanagement of resources is a common source of crashes in production applications, and regular traps are database connections, and file descriptors remain open after an exception occurs elsewhere in the code.

  3. This leads to the fact that application servers often restart when resources are exhausted, since operating systems and server applications usually have an upper limit on resources .

Using Java 7 Trial Resource Statement

+2
source share

All Articles