Coming from a C++ background, I am a huge fan of the RAII pattern. I have used it extensively to handle memory management and lock management along with other use cases.
With Java 1.7 I see that i can use the try-with-resources pattern to create a RAII pattern.
I created a sample application using RAII and it works, but I see compiler warnings from java.
Sample Application
try(MyResource myVar = new MyResource(..))
{
//I am not using myVar here
}
I get the following errors
warning: [try] auto-closeable resource node is never referenced in body of corresponding try statement
I understand the warning, it is implying that I should have used the variable inside the try block, which I don't really need to do all the time.
Looking at this I am assuming that Java doesn't really have true support for RAII and I might have misused the feature which was only for Resource Management and not exactly a RAII equivalent in C++.
Couple of questions:
- Is my understanding correct?
- How risky is it to ignore these warnings?
- How do I ignore these warnings through ant?
- Is there a simple way for me to overcome this?
for 4 i am thinking of splitting the constructor call into a simpler constructor and a instance method like this
try(MyResource myVar = new Resource())
{
myvar.Initialize()
....
}
Which solves the compiler problems but takes the essence out of the RAII like design.
Resource
has no meaningful methods (besidesclose()
) and just causes side effects on construction? As a Java guy, that seems like an antipattern. Can you explain what the resource does? – Farika