• Java thread safety with wait/notify.
    Mar 31, 2010

    Something I realized today with Java thread wait/notify mechanism was that when thread A calls wait() on object O and thread B calls notify, thread A does not immediately continue executing, because thread B may still hold the lock, so regardless of calling notify, thread A will have to wait for the lock. So here is example :

    thread A:

    syncronized(obj) {
        while(conditionToWaitFor)
            obj.wait();
    }

    thread B:

    syncronized(obj) {
        conditionToWaitFor = false;
        obj.notify();
        // THREAD STOPS HERE
    
        /*
        Even if thread will stop here, thread A will not continue executing until this synchronized block is over,
        because this code block holds the lock.
        */
    }
    Read more...
  • Why to write test code.
    Mar 24, 2010

    In today's world of test framework availability, we often feel very lazy to write unit test cases. Frameworks like JUnit exist for long time, but very few people actually make full use of it. I am not going to cover technical aspects of JUnit or any similar framework now, but I am shortly going to write about the reasons why test code is necessary from my experience.

    These are few reasons we refuse to write test code:

    1. This code is straightforward.

      I am sure it is. So write a test case and make a happy face to see 100% success. Besides the code behind it may fail at sometime later in your development, so writing a test case now will save your time in future.

    2. It works!

      Yes, it does, congrats on doing good job. What about after lets say a week? Somebody changes something, and then they blame it on you, are you in the mood to manually test everything again? I am not, so I am going to write a test case.

    3. Its too much of work to write a test code.

      This is the main one, and I have say following to this: I would prefer to sweat for 2 hours than to bleed for 1. No matter how perfect code you write, at some point it will fail. In that situation the test case is the savior, it will save you from maybe hours of frustration from trying to find what is wrong. The worst is it may even not be you, so preserve your nerves. Scientist are still not sure whether nerve cells do regenerate or not. Besides you are not protected from failures from happening again, so invest into test code once, and prevent yourself from frustration, its like health insurance.

    Read more...
  • Starting JPDA in Tomcat 6 in Ubuntu
    Mar 17, 2010

    I needed to debug a tomcat application, and in order to use Eclipse remote debugger I had to start JPDA from tomcat6 from Ubuntu. The default startup script does not have a jpda start parameter, so we have to add one ourselves.

    Tomcat source installation does provide a jpda start parameter with catalina.sh script, but for some reason it does not work in Ubuntu. Here is a blog article that describes remote debugging of Tomcat from Eclipse : http://java.sys-con.com/node/44918

    So back go Ubuntu, I found a following solution for jpda start in this thread from Ubuntu forums : http://ubuntuforums.org/showthread.php?t=1021386

    What you have to do is add following lines into /etc/init.d/tomcat6 :

    if [ "$2" = "jpda" ]
    then
        JPDA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
    fi
    CATALINA_OPTS="$JPDA_OPTS"

    And edit the line

    $DAEMON -user "$TOMCAT6_USER" -cp "$JSVC_CLASSPATH" \
    
                        -outfile SYSLOG -errfile SYSLOG \
    
                        -pidfile "$CATALINA_PID" $JAVA_OPTS "$BOOTSTRAP_CLASS"

    to become

    $DAEMON -user "$TOMCAT6_USER" -cp "$JSVC_CLASSPATH" \
    
                        -outfile SYSLOG -errfile SYSLOG \ 
                        $CATALINA_OPTS \                    
                        -pidfile "$CATALINA_PID" $JAVA_OPTS "$BOOTSTRAP_CLASS"

    Here is the full description: http://ubuntuforums.org/showpost.php?p=7259987&postcount=3

    Read more...
  • Performance Tip : Make Comparators Singleton
    Mar 12, 2010

    In Effective Java 2nd Edition, Joshua Bloch mentions that Comparator objects should be always Singleton in order to avoid unnecessary Object creation (Item 21, Use functions objects to represent strategies). It gave me a thought that not only Comparators should be made singleton, but all function objects.

    If the object contains only functions and has no internal state, there is simply no need to have different instances of that. So, this code:

    Collections.sort(stringList, new ReverseStringOrder());

    should rather be

    Collections.sort(stringList, ReverseStringOrder.getInstance());

    And ReverseStringOrder must respectively implement Singleton pattern with getInstance method returning the Singleton instance.

    Read more...
  • Java Object Design Tip : Make setter return the instance of an object instead of void
    Mar 7, 2010

    We are all taught in the first classes of object-oriented programming to have all instance variables private and assign getters and setters for them. The traditional way of doing this is having getters not to take any parameter and have the return type as the type of the instance variable which it fetches, and setter having void as return type and parameter of type of the instance variable. The improved way of this is having setters to return the instance of the object on which it is being invoked, adding benefits I mention below. In many situations we end up having to set many properties on a given object, so our code ends up in something like this:

    obj.setProperty1(prop1);
    obj.setProperty2(prop2); 

    and so on.

    While it may not be noticable in short methods, when there are many properties to set, and especially when those properties are short-named, it is better to have them in one line to improve the readability and make code more compact.

    obj.setProperty1(prop1).setProperty2(prop2);

    To achieve this we need to make setters in following way:

    public class Obj {
        int property1;
        int property2;
        Obj setProperty1(int property1) {
            this.property1 = property1;
            return this;
        }
    }
    
    Obj setProperty2(int property2) {
        this.property2 = property2; 
           return this;
        }
    }

    While adding an additional benefit, there are also no disadvantages, we can still use these setters in an old-fashioned way by calling them and not using their return value.

    Read more...
  • My tips on passing Sun Certified Programmer for Java 2 Platform Standard Edition 6.0 (SCJP6 310-065)
    Feb 23, 2010

    Woohoo! Today I passed SCJP 6 exam from Sun! Now it will take four to six week for me to get the official certificate and all the paperwork, and after that I will probably go for SCJD, Sun Certified Java Developer.

    Now that I passed the exam, I would like to share some practices that helped me for preparing. All of these are result of my personal experience and by no means a scientific research.

    • The book I used to study was the legendary book by Katherine Sierra and Bert Bates, available from amazon. This book contains all the materials you need for the exam, and even more than that. The mock questions they contain are actually a lot harder than the ones in real exam, but it is still good in a way that it toughens you up. I was surprised to see than in real exam for multiple choice answers they tell you how many you have to select, in the mock questions in the book they don't.

    • Code, code, code! I will say it again, code! Whatever question arises in your head, try to immediately figure it out by writing a small piece of program that would help you to see what is going on and understand it. Leave no darkness in your mind about how things work in Java. Also try to use java compiler from console, not IDE like Eclipse, because sometimes they have I/O problems of mixing outputs. (I saw that when I had print statements in finally block, and sometimes in Eclipse they were appearing after exception, but in console print statement inside finally executed always before the method threw an exception. I guess standard error and standard output streams are somehow not separated properly.)

    • Sierra book advises you to first skim over the easy questions and answer them before. DO NOT DO THAT! The questions in this exam are known to be VERY tricky, so a lot of questions which may seem easy to you at a first glance can contain very nasty tricks. Go through every question in order, and never underestimate the hardness of the question. In fact there are some questions that which will be very easy, but those few do not worth taking the risk of missing tricky questions. As one old saying says, if you underestimate your enemy, you will loose, if you overestimate your enemy, you will win only once, and then loose. To win him all the time you need to exactly know him. You are going to give this exam only once, so you will not loose anything if you overestimate its difficulty ;)

    • Use public transportation to get to your exam location. No matter how experienced driver you are, driving takes attention, thus it may impair your concentration and focus before the exam. It also depends on availability of public transportation, I was lucky to have my testing center only 500m away from a train station. But if this would not be the case for me, I would probably go out half an hour earlier than I needed to, in order to have some time to relax and concentrate later. I also took my time to revise my notes in the train.

    • Take water! 3 hours of active thinking is not a little, and brain really works better when it is hydrated. I drank around a liter of water during the exam, and I could think sharply for 2 hours straight. In mock exams I was doing before, I was getting tired after 10-15 questions. What I would like to suggest is that verify that you will be able to use bathroom in the exam (most places should not have a problem, but verification will not hurt), because you will really need it. I would also suggest not to take any food, especially the 'energetic' ones. Digestion is known to be one of the most energy-consuming processes in human body, together with brain activity, so any energetic food takes time to give effect. The time you don't really have during the exam.

    Read more...
  • How I removed Blogger NavBar.
    Feb 17, 2010

    Google says NavBar is useful, but using it for a long time I did not find any use for it. Clicking next blog from my blog, I kept getting art blogs in Spanish, Portuguese or one of Scandinavian languages. So I thought its time to get rid of it.

    • Sign in to Blogger.
    • On the Blogger Dashboard, click on the Layout link of the blog that you want to disable its NavBar. You can also click Customize on NavBar while visiting your blog

    • Under the Layout tab, click on Edit HTML tab to view the template‚Äôs HTML code.

    • Search for the following line of code:

      ]]>

      Before the line, add in the following line of code:

      #navbar { display: none; }

      or:

      #navbar-iframe { display: none !important; }

    • Click on SAVE TEMPLATE to make the change effective.

    Source

    I have added both #navbar { display: none; } and #navbar-iframe { display: none !important; } just in case of different browsers.

    Read more...

subscribe via RSS