Is the Rule of 5 (for constructors and destructors) outdated, if smart pointers can take care of resource management?

The full name of the rule is the rule of 3/5/0. It doesn’t say “Always provide all five”. It says that you have to either provide the three, the five, or none of them. Indeed, more often than not the smartest move is to not provide any of the five. But you can’t do that … Read more

Where to close java PreparedStatements and ResultSets?

In Java 7, you should not close them explicitly, but use automatic resource management to ensure that resources are closed and exceptions are handled appropriately. Exception handling works like this: Exception in try | Exception in close | Result —————–+——————–+—————————————- No | No | Continue normally No | Yes | Throw the close() exception Yes … Read more

Are Locks AutoCloseable?

I was looking into doing this myself and did something like this: public class CloseableReentrantLock extends ReentrantLock implements AutoCloseable { public CloseableReentrantLock open() { this.lock(); return this; } @Override public void close() { this.unlock(); } } and then this as usage for the class: public class MyClass { private final CloseableReentrantLock lock = new CloseableReentrantLock(); … Read more

What Automatic Resource Management alternatives exist for Scala?

Chris Hansen’s blog entry ‘ARM Blocks in Scala: Revisited’ from 3/26/09 talks about about slide 21 of Martin Odersky’s FOSDEM presentation. This next block is taken straight from slide 21 (with permission): def using[T <: { def close() }] (resource: T) (block: T => Unit) { try { block(resource) } finally { if (resource != … Read more

Understanding the meaning of the term and the concept – RAII (Resource Acquisition is Initialization)

So why isn’t that called “using the stack to trigger cleanup” (UTSTTC:)? RAII is telling you what to do: Acquire your resource in a constructor! I would add: one resource, one constructor. UTSTTC is just one application of that, RAII is much more. Resource Management sucks. Here, resource is anything that needs cleanup after use. … Read more