Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Wednesday, June 19, 2013

Forcing Java virtual machine to run garbage collector

No, You cant force garbage collection.
Even using
 
System.gc(); 
You can just make a request for garbage collection but it depends on JVM to do it or not.
Also Garbage collector are smart enough to collect unused memory when required so instead of forcing garbage collection you should check if you are handling objects in a right way.
If you are handling objects in a wrong way (like keeping reference to unnecessary objects) there is hardly anything JVM can do to free the memory. 


From Doc 
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. 
Which means that garbage collector makes best possible effort but it is not guaranteed that it will free up the space every-time.  

Bug regarding System.gc() documentation 
The documentation for System.gc() is extremely misleading and fails to make reference to the recommended practise of never calling System.gc().
The choice of language leaves it unclear what the behaviour would be when System.gc() is called and what external factors will influence the behaviour.
 Few useful links to visit when you think you should force JVM to free up some memory
1. How does garbage collection work
2. System.gc() in Java
3. Why is it a bad practice to call System.gc?  


All says
1. You don't have control over Garbage Collection in Java even System.gc() dont guarantee it.
2. Also its bad practice as forcing it may have adverse effect on performance.
3. Revisit your design and let JVM do his work :)

ResourceBundle : Loading properties file from JAR

With ResourceBundle you can use properties file which are present in external JAR.
  
getBundle(String baseName,Locale locale)
Where baseName should be the base name of the resource bundle, a fully qualified class name. Which mean it should be fully qualified name of properties excluding .properties extension.

Suppose you have a JAR structure like displayed in following image


(I have renamed the msg.jar to msg.zip just to open it and show the file structure).
Here properties files are in package "com.msg" so baseName should be "com.msg.messages" like
  
getBundle("com.msg.messages", desiredLocale);
For more details : Java Doc Link

Saturday, May 18, 2013

Implementing singleton in Java

While implementing Singleton we have 2 options 
1. Lazy loding - Create object only when required
2. Early loading - Create object when class is loaded and don't care if it will be used ever

Lazy loading adds bit overhead(lots of to be honest) so use it only when you have a very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.Otherwise choosing early loading is a good choice.

Most simple way of implementing Singleton is 

public class Foo {

 // It will be our sole hero
 private static final Foo INSTANCE = new Foo();

 private Foo() {
  if (INSTANCE != null) {
   // SHOUT
   throw new IllegalStateException("Already instantiated");
  }
 }

 public static Foo getInstance() {
  return INSTANCE;
 }
}

Everything is good except its early loaded singleton. Lets try lazy loaded singleton

class Foo {

 // Our now_null_but_going_to_be sole hero
 private static Foo INSTANCE = null;

 private Foo() {
  if (INSTANCE != null) {
   // SHOUT
   throw new IllegalStateException("Already instantiated");
  }
 }

 public static Foo getInstance() {
  // Creating only when required.
  if (INSTANCE == null) {
   INSTANCE = new Foo();
  }
  return INSTANCE;
 }
}

So far so good but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.
So lets protect it from evil multi threading

class Foo {
 private static Foo INSTANCE = null;

 // TODO Add private shouting constructor
 public static Foo getInstance() {
  // No more tension of threads
  synchronized (Foo.class) {
   if (INSTANCE == null) {
    INSTANCE = new Foo();
   }
  }
  return INSTANCE;
 }
}
but it is not enough to protect out hero, Really!!! This is the best we can/should do to help our hero
class Foo {
 // Pay attention to volatile
 private static volatile Foo INSTANCE = null;

 // TODO Add private shouting constructor

 public static Foo getInstance() {
  if (INSTANCE == null) { // Check 1
   synchronized (Foo.class) {
    if (INSTANCE == null) { // Check 2
     INSTANCE = new Foo();
    }
   }
  }
  return INSTANCE;
 }
}

This is called "Double-Checked Locking idiom". It's easy to forget the volatile statement and difficult to understand why it is necessary. 

Now we are sure about evil thread but what about the cruel serialization? We have to make sure even while deserialiation no new object is created

class Foo implements Serializable {

 private static final long serialVersionUID = 1L;

 private static volatile Foo INSTANCE = null;

 // Rest of the things are same as above

 // No more fear of serialization
 @SuppressWarnings("unused")
 private Foo readResolve() {
  return INSTANCE;
 }
}
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.

Finally we have added enough protection  against threads and serialization but our code is looking bulky and ugly. Lets give our hero a make over

public final class Foo implements Serializable {

 private static final long serialVersionUID = 1L;

 // Wrapped in a inner static class so that loaded only when required
 private static class FooLoader {
  // And no more fear of threads
  private static final Foo INSTANCE = new Foo();
 }

 // TODO add private shouting construcor

 public static Foo getInstance() {
  return FooLoader.INSTANCE;
 }

 // Damn you serialization
 @SuppressWarnings("unused")
 private Foo readResolve() {
  return FooLoader.INSTANCE;
 }
}
Yes this is our very same hero :)  
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation and is it guaranteed to be thread safe.
And we have came so far, here is the best way to achieve everything we did is best possible way
public enum Foo {
       INSTANCE;
   }
Which internally will be treated as 
public class Foo {

    // It will be our sole hero
    private static final Foo INSTANCE = new Foo();
}
That's it no more fear of serialization, threads and ugly code.
   
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
-Joshua Bloch in "Effective Java"      

Now you might have realized why ENUMS are considered as best way to implement Singleton and thanks for your patience :)

Sunday, December 18, 2011

How to prepare for OCPJP 6?

                                            

  A heads up on the preparation for OCPJP

Recently (On 6th December 2011) I cleared OCPJP with 96%.Inspired with the score, thought of jotting down a roadmap with tips and experiences. Will be talking about what I did, what I would have done differently and how it would have helped me.

Following DO's and DONT's might help you to achieve a decent score.

1. Decide a timeline -
My very first advice: Decide a timeline or you will unnecessarily spend/waste lots of time in preparation.
I spent overall 3 months for preparation. Spent 2-3 hours on weekdays and maximum possible time on weekends. Depending on your prior Java experience and skills you may require more/less time.
Another tip that might work for most of you, if possible buy the exam voucher. It will push you to squeeze in time to your routine for preparation. Remember we all don’t work unless we have a deadline, the voucher would serve this purpose of a deadline.

2. Grab a good book -
You will find plenty of good books and many books which claim to be good. Prefer Kathy Siera and Bert Bates. It is fairly thorough and carries helpful tips. Moreover it’s an entertaining guide to OCPJP traversing through unnecessary but helpful jokes.
Most of the sites/blogs advise you for multiple books but I will highly recommend you to marry a single book. It will help you to avoid confusion.

3. Read, Spoil, Remember -
Go through K&B (or any other book you are comfortable with). Read, think, understand and try to remember it. In my opinion if you understand it well, you don't need to remember it.
While reading I used to spoil pages with different symbols/words like *, WTF, Awesome, Really! Etc  Etc.
Or sometimes used to fold pages which surprised me most. (Very first reason behind doing all this, I am too lazy to take notes.) This helped me put things into head quickly and saved ample time while revising it again.
One humble request: DONT ASSUME/skip anything while reading even if you have lots of experience with Java. Java is a tricky language with lots of pitfalls so go through each and every line.
REMEMBER: ASSUME = making ASS of U and ME.

4. CODE CODE and CODE -
while reading try tons of mad, messy, nonsense code. It is bound to help you a lot. Also prefer a normal text editor like notepad or notepad++ over any IDE. I know it's a painful thing but trust me it is worth to bear the pain. I initiated my start up with notepad++ and after getting enough confidence moved to Eclipse.

5. Dare to give mock tests-
Alright, once completed the book. I assume you to be familiar with the required concepts. Gear up now, give some mock tests. You will find many sites offering free mock tests. (Assuming you are good at Googling ).
I will suggest scjptest.com , found it reliable and good enough. Don't bother about the score, just note down questions/topics which troubled you and move on.

6. Do it again-
You went through the book and showed enough courage to face mock tests. Now you must be familiar with areas which surprised/troubled you, time to WORK ON IT. Read it again, ask Google, put it on forums and scream for help until you get over it. In my opinion this is the most important stage. I spent quite some time fighting with threads, collections, generics etc.

7. Spread the world -
Keep visiting Javaranch and Stackoverflow whenever you are free. Ask questions, try to help others.
REMEMBER: The best way to learn is to teach. I spent more time on Stackoverflow than Facebook and tweeting. Sorry for being biased but I am in love with Stackoverflow.
Discuss all stuff with your friends, colleagues, neighbors and strangers. These Discussions/arguments which I had with my colleagues, nurtured my knowledge.
Trust me, dive into it and you will enjoy swimming through the journey.

8. SHOWTIME:
Alright, here you are. If you have accomplished all of this: Congratulations :) Now register a date for the exam.
Just before the exam: relax, be confident and ensure a good sleep. (I slept for barely 4 hours and things went a little difficult)Most of all, keep your mind at its place.
IMPORTANT: Whichever question you face, don't panic, answer the easy ones at first, mark the tough ones and move on. Keep yourself calm and revisit marked questions.

9. What if I fail-
Go to step 1. Remember it doesn't matter how many times you were knocked down, what matters is how many times you got up again.

Hope this helps you all aspirants of OCPJP :) All the very best!
PS: Please bear with me for any wrong assumption. Best Wishes!!
and special thanks to Paji for reviewing and editing my first post :D

~Ajinkya.