叶予清晨

叶予清晨

hhh

Java Resource Management

Java Resources#

  1. Memory resources: Memory space occupied by objects, arrays, etc.
  2. Physical resources: File handles, database connections, network connections, etc.
  3. Differences between memory and physical resources
  • Memory resources are automatically managed by JVM, while physical resources need to be manually managed.
  • When an object is no longer referenced, memory resources are automatically reclaimed, while physical resources remain occupied.
  • Example: Memory resources: Reading a book in the reading area and leaving after finishing; Physical resources: Borrowing a book requires returning it actively; if not returned, it will continue to occupy the book.

Basic Principles of Java Memory Management#

  1. Heap memory: Stores object instances.
  2. Stack memory: Stores primitive data types and object references.

How try-with-resources Works in Java Physical Resource Management#

This is a feature introduced in Java 7.
Any class that implements the AutoCloseable interface can be used.
The compiler automatically converts it into code with finally.

// When we write code like this:
try (FileInputStream file = new FileInputStream("test.txt")) {
    // Use the file
}

// The compiler automatically converts it to code like this:
FileInputStream file = new FileInputStream("test.txt");
try {
    // Use the file
} finally {
    if (file != null) {
        file.close();
    }
}

Methods for Managing Physical Resources in Java#

  1. Traditional method (not recommended)
FileInputStream file = null;
try {
    file = new FileInputStream("test.txt");
    // Use the file
} catch (Exception e) {
    // Handle exception
} finally {
    if (file != null) {
        file.close(); // Manually close the resource
    }
}
  1. Modern method (recommended)
try (FileInputStream file = new FileInputStream("test.txt")) {
    // Use the file
} catch (Exception e) {
    // Handle exception
} // Automatically close the resource
  1. Complete summary of Java resource management:

Core principles:
Use try-with-resources to automatically manage resources.
Correctly handle checked exceptions.
Follow the "last in, first out" order for resource closure.

Resource types:
Common resources that need management:

  • InputStream/OutputStream (file operations)
  • Connection/Statement/ResultSet (database operations)   
  • Socket (network connections)
  • Channel (NIO operations)

Standard template:

try (Resource1 r1 = new Resource1();    
     Resource2 r2 = new Resource2()) {
    // Use the resources
} catch (Exception e) {
    // Exception handling
}

Ways to Manage Java Resources:#

  1. File system resources:
  • Using the File class
    File file = new File("test.txt");

  • Using the Path interface (Java 7+)
    Path path = Paths.get("test.txt");

  1. Network resources:
  • Using the URL class
    URL url = new URL("https://example.com");
    URLConnection conn = url.openConnection(); 

  • Using Socket
    Socket socket = new Socket("localhost", 8080);

  1. Classpath resources:
  • Using ClassLoader
    InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties");

  • Using Class
    InputStream is = MyClass.class.getResourceAsStream("/config.properties");

  1. Database resources:
  • Using JDBC
    Connection conn = DriverManager.getConnection(url, username, password); 
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.