Junior — Middle
What criteria must be met when creating classes used for resource initialization?
sobes.tech AI
Answer from AI
When creating classes for resource initialization in Java, it is important to adhere to the following criteria:
- Proper resource management: the class should guarantee the allocation and release of resources (e.g., file descriptors, database connections).
- Implementation of the
AutoCloseableorCloseableinterface: so that the try-with-resources construct can be used for automatic resource closing. - Exception handling: proper handling of errors during resource initialization and release to prevent leaks.
- Idempotency of close(): the
close()method should be safe to call multiple times without errors.
Example of a resource management class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceHandler implements AutoCloseable {
private BufferedReader reader;
public ResourceHandler(String filePath) throws IOException {
reader = new BufferedReader(new FileReader(filePath));
}
public String readLine() throws IOException {
return reader.readLine();
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
}
}
}
This approach ensures reliable and safe resource usage.