There are many articles and blog posts about this topic but rarely are they complete. I’ll cover finalizers, Finalizer Guardian idiom, Dispose Pattern, PhantomReference and Cleanable.
Category: Java
About Java – the technology, not the island.
LockOnce
Run code only once!
Project hosted on github: https://github.com/claudemartin/LockOnce
It’s just one single utility class to make sure code is run only once. And then there’s another one for easy “Lazy Initialization”.
I once wrote this for Java 7 but now it needs Java 8. It makes much more sense to use this with Lambdas. It’s a bit like the lazy keyword of Scala.
// declaration of lazy field: final Supplier<Foo> lazy = Lazy.of(() -> ...); // Access to the data: Foo foo = lazy.get();
You can also register a “destructor”. This solves the problem that such fields (they are usually static final
) are never GCd and finalizers are utterly useless. In the same way you can have resources (they just have to implement AutoClose
) closed on shutdown.
Java Cleanup
## WARNING:
There already is sun.misc.Cleaner
. And Java 9 should even have java.util.Cleaner
or something like that. I simply didn’t know. So it’s better to wait for Java 9 or use sun.misc.Cleaner
.
If you are still interested:
Project home:
http://claude-martin.ch/java-cleanup/
I have a blog post about Finalizers and PhantomReferences:
Object.finalize()
EnumBitSet
I did this because EnumSet
is in fact a bit set (if it’s not a JumboEnumSet
) but it can’t be used as such. I ended up writing a complete library for domain bit sets.
Project website: http://claude-martin.ch/enumbitset/
Project home @ GitHub: https://github.com/claudemartin/enum-bit-set
Misnomer: The class named Class
So there’s a class named Class. But it represents interfaces, annotations and enums too. What’s up with that?
Continue reading “Misnomer: The class named Class”
Misnomer: List Interface
Some think “List” is a misnomer. I don’t even mind so much. I think List is ok.
I just put this here because there already is an entry in the FAQ:
PS: Vector
is strange, though. It is synchronized and it really should be SynchronizedList
. But it is defacto deprecated. So who cares?
Misnomer: RuntimeException
So a RuntimeException
is thrown at runtime, right?
Continue reading “Misnomer: RuntimeException”
Misnomer: NullPointerException
Java does not have pointers. Variables are of primitive or reference type. So it uses references. Then why is there a NullPointerException?
Misnomer: final keyword
The final keyword creates a lot of confusion in the Java world. I’ll try to clear things up a bit. Continue reading “Misnomer: final keyword”