2

Is there any point in closing resources such as sockets, files, and database connections if the JVM is going to shut down immediately afterwards? The OS isn't going to somehow keep sockets and database connections open, is it?

(I've written a simple TCP server-client application like the one in the official tutorial, but because I'm targeting Java 6 I can't use try-with-resources like the tutorial does. Also, not all APIs implement AutoCloseable.)

DavidS
  • 5,022
  • 2
  • 28
  • 55
  • 6
    As a general good practice, you should always close resources that open - IMHO – MadProgrammer Aug 27 '15 at 00:34
  • @MadProgrammer I agree, but as I stared at my 16 line program, I felt the urge to delete the 4 lines responsible for closing the resources, and I wondered if there was any harm. – DavidS Aug 27 '15 at 00:37
  • Are you targeting a specific OS (or specific subset of OSes), or are you asking if there is *any* OS that might keep these resources open? (And similarly, are you targeting a specific DBMS?) – ruakh Aug 27 '15 at 00:39
  • Not knowing exactly the process in which the JVM terminates myself, I would, generally, tide up myself, but that's me – MadProgrammer Aug 27 '15 at 00:39
  • @ruakh I'm running my simple TCP server-client on Windows 7, SunOS 5.10, and some version of Redhat. I open a file for logging, but I mentioned database connections only because I thought it might be related. – DavidS Aug 27 '15 at 00:42
  • 1
    Some operating systems may reset connections instead of closing them gracefully with FINs if you don't close them yourself and exit the process. You don't want to allow that. – user207421 Aug 27 '15 at 00:42
  • Reading the comments and answers here and on the marked duplicate, it seems the general consensus is that it's "sort of" important to close resources before the JVM shuts down. Abandoned resources may be recovered immediately or eventually, and the exact behaviour may vary depending on the resource and OS. Thanks for your time, everyone. – DavidS Aug 27 '15 at 00:52

0 Answers0