Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a resource in java?why we have to close it after it is used?

What is the meaning of the word "resource" in java? Why we have to close it after usage,even though garbage collector runs in jvm ? Why we have to write resource cleanup code in finally block?

like image 601
Muthyala Naresh Avatar asked Nov 28 '22 07:11

Muthyala Naresh


1 Answers

A resource is something that has a limited ammount, such as DB connections and file descriptors. The GC frees memory, but you still have to release resources such as DB connections, open files, etc..., to allow other threads to use them.

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

like image 194
Eran Avatar answered Dec 15 '22 15:12

Eran