Is it wise to use unsafe – Hidden secret of Java

I have been visiting quite a few sites and going through few forums, when I stumbled upon an article talking about the hidden weapon of Java, not made publicly known due to some reasons. But it is claimed that many of the Java internals and third party softwares do use this API to gain monstrous power.
While we have learned from academic days that heap space is home for Java objects, it is a place where the objects come to life and die. JVM with its GC algorithm makes the kill and creates space for new objects. While in the process of moving objects from various places (eden, young generator etc), it sometimes may bring down the application performance to its knees and can prove costly affair.
Whlie GC has been seen as life savior for people who dont want to worry about memory management, it also imposed restriction in terms of no control over deciding fate of the object as when it will get garbage collected. While this may not sound so serious problem as people end up allocating higher heap space for JVM (without realising the fact that it is actually hampering performance), some felt it bit uncomfortable (geeks from C, C++ playing with memory functions).

sun.misc.Unsafe was something that forced to raise my eyebrows and felt like is it something unusual. So far by the definition and the various articles, it gives you the power not limited by the standard Java options and complete control over memory management of the objects created using this API. The functionality is similar to C, C++ where in you allocate memory for object and decide at logical place to clean it up.
While this may seem to be of great help, you should also consider following
1. Unsafe API is not recommended as it may be removed in future (not sure when this will happen, some claim lot of Java API use this internally).
2. You may need to test the implementation on various platforms your self.
3. Should be coded carefully or it will end up in memory leak.

After all, with great power comes great responsibility. Till then, happy coding.

By Carbon Rider

Hi this is Yogesh, welcome to my world. Being passionate about learning new technologies and building frameworks, I end up spending most of my time in front of computer. But over last few months, I realised apart from being good coder and designer (Yes I am) I have something hidden in me. And thats called ART.

Leave a Reply