Tag: Java

  • Java Tip #5: Use Apache Commons DateUtils when dealing with dates

    Tip #5 in my Java Tips series is again focussing around the Apache Commons framework. In the same manner the StringUtils simplifies many common operations on Strings (see also Java Tip #3), DateUtils ease some of the pain when working with Java Date objects.


    Advice

    Use Commons DateUtils to manipulate and calculate dates.

    Code-Example

    Before

    ...
    private static Date add(Date date, int field, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, amount);
        return cal.getTime();
    }
    ...
    public static Date getNextDay() {
        return add(getCurrentDay(), Calendar.DATE, 1);
    }
    ...

    After

    ...
    public static Date getNextDay() {
        return DateUtils.addDays(getCurrentDay(), 1);
    }
    ...

    Benefit

    Huge readability gain. By using DateUtils for calculating and manipulating Dates the code footprint gets smaller and easier to read. Furthermore by using explicit methods like addDays() it is clearer which part of a date is to be modified, compared to the partly ambiguous constants in the Calendar class. DateUtils also contains methods to round or truncate Dates to certain parts of the date, eg. truncate() by Calendar.HOUR sets minutes, seconds and miliseconds to zero.

    Remarks

    None.

  • Java Tip #4: Use implicit NULL checks on constants

    Tip #4 of the Java Tips series is just a quick tip to enhance the codes robustness.


    Advice

    When comparing constants, always compare the constant to the unknown value.

    Code-Example

    Before

    if(str != null && str.equals("XYZ")) { ... }
    if(value != null && value.equals(SomeEnum.ENUM_1)) { ... }

    After

    if("XYZ".equals(str)) { ... }
    if(SomeEnum.ENUM_1.equals(value)) { ... }

    Benefit

    Safety gain. Minor readability gain. The constant value can be compared to a null value without resulting in a NullPointerException. The check for null can be skipped because when the constant is compared to null the condition simply evaluates to a boolean false.

    Remarks

    None.

  • Java Tip #3: Use Apache Commons StringUtils for String checks

    The next tip in my series of Java Tips deals with the usage of Java frameworks. Some people still have a certain hatred against Java frameworks because many of them have been not easy to deal with in in their past. Nevertheless, while those have either disappeared or evolved in a more usable shape, there have always been some frameworks which were rock-solid and widely accepted as simple and extremely useful. One of those is the Lang package in the library collection of the Apache Commons. In my opinion this one is a must-have for almost every Java project or application. Use it. Period.


    Advice

    Use Commons StringUtils for checking Strings content for null, emptiness or blankness.

    Code-Example

    Before

    if(str != null && !str.equals("")) { ... }
    if(str != null && !str.trim().equals("")) { ... }
    if("".equals(str)) { ... }
    if(str == null || "".equals(str.trim())) { ... }

    After

    if(StringUtils.isNotEmpty(str)) { ... }
    if(StringUtils.isNotBlank(str)) { ... }
    if(StringUtils.isEmpty(str)) { ... }
    if(StringUtils.isBlank(str)) { ... }

    Benefit

    Huge readability gain. Safety gain, as StringUtils methods are null-safe. By using the provided utility methods from StringUtils the intent of a condition is much easier and faster to recognize. Furthermore, since all methods of StringUtils are able to correctly process null Strings, there is no danger of an unexpected NullPointerException anymore because of a forgotten null-check.

    Remarks

    None.

  • Java Tip #2: Use StringBuilder for String concatenation

    And on to the next in a series of Java Tips. While last time the performance gain was very tiny and only affected high-load scenarios, this tip may considerably speed up even simple applications where there is String-processing involved.


    Advice

    Use StringBuilder instead of + or += to concatenate Strings in non-linear cases (when concatenation not appears immediately one after another), ie. in loops.

    Code-Example

    Before

      String test = "";
      for(int i = 0; i < 50000; i++) {
         test += "abc";
      }

    After

      StringBuilder test = new StringBuilder();
      for(int i = 0; i < 50000; i++) {
         test.append("abc");
      }

    Benefit

    Huge performance gain! The unoptimized code forces Java to create new Strings and copy the contents around all the time (because Strings are immutable in Java). The optimized code avoids this creation/copying by using StringBuilder. While the Java compiler can optimize linear concatenations, ie.

    String test = "a" + "b" + "c"; 

    into using a StringBuilder internally, it is not clever enough to apply this optimization correctly if there is more logic than just concatenation involved. Even if the concatenation is the only operation inside some loop-logic, the Java compiler falls back into creating a whole lot of String (or to be more exact: StringBuilder) objects, copying them around like crazy and causing a huge performance impact in some cases. I confirmed this example for measurement of StringBuilder performance: concatenating 50000 times "abc" in a loop takes ~11000ms, using StringBuilder keeps the time spent at near 0ms. (I tried concatenating with 500000 iterations, but stopped the execution of the first loop after ~10 minutes running unfinished, so the impact is nonlinear. Second loop finished in 15ms with 500000, for the record.)

    Remarks

    It is not necessary to optimize code like

    String email = user + "@" + domain + ".com"; 

    as javac is clever enough for these cases and it would reduce readability considerably. But even with the simplest loops involved the conditions change. For example, internally the first loop gets compiled by javac into following bytecode

     13  new java.lang.StringBuilder [24]
     16  dup
     17  aload_1 [test]
     18  invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String [26]
     21  invokespecial java.lang.StringBuilder(java.lang.String) [32]
     24  ldc <String "abc"> [35]
     26  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [37]
     29  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [41]
     32  astore_1 [test]
     33  iinc 4 1 [i]
     36  iload 4 [i]
     38  ldc <Integer 50000> [45]
     40  if_icmplt 13

    where for each iteration of the loop(13-40) a new StringBuilder is instantiated and initialized with the result of the previous’ loop StringBuilders value before appending the constant String just once each time. The optimized code results in this bytecode

     81  new java.lang.StringBuilder [24]
     84  dup
     85  invokespecial java.lang.StringBuilder() [62]
     88  astore 4 [builder]
     90  iconst_0
     91  istore 5 [i]
     93  goto 107
     96  aload 4 [builder]
     98  ldc <String "abc"> [35]
    100  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [37]
    103  pop
    104  iinc 5 1 [i]
    107  iload 5 [i]
    109  ldc <Integer 50000> [45]
    111  if_icmplt 96

    in which the loop(96-111) just appends the constant String to the same StringBuilder each time which was created only once before the loop started. No copying around and creation of additional objects necessary, thus a huge performance-gain.

  • Java Tip #1: Use StringBuilder instead of StringBuffer

    As promised last time I’m presenting here the first in a series of Java Tips. To start easy I’ll begin with one of the simplest tip to implement.


    Advice

    Use StringBuilder instead of StringBuffer.

    Code-Example

    Before

      StringBuffer str = new StringBuffer();
      str.append("foo");
      String x = str.toString();

    After

      StringBuilder str = new StringBuilder();
      str.append("foo");
      String x = str.toString();

    Benefit

    Small performance gain. StringBuilder is a 1:1 drop-in replacement for the StringBuffer class. The difference is that the StringBuilder is not thread synchronized and therefore performs better on most implementations of Java. Even javac internally translates String x = "foo" + "bar"; into a StringBuilder operation (confirmed with Java 1.6.0_18). A small testcase

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 1000000; i++) {
            buffer.append("abc");
        }
        System.out.println("Time lapse using StringBuffer: " + (System.currentTimeMillis() - start) + " milliseconds");
    
        start = System.currentTimeMillis();
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < 1000000; i++) {
            builder.append("abc");
        }
        System.out.println("Time lapse using StringBuilder: " + (System.currentTimeMillis() - start) + " milliseconds");
    }

    using Java 1.6.0_18 shows that StringBuilder is roughly 100% faster than StringBuffer. Although on my machine this testcase keeps below 100ms for both with one million appends so this won’t be the magical solution for most of your performance issues.

    Remarks

    Even if this tip can be applied in 98% of all cases one has to be sure that the String is used afterwards and the StringBuilder instance does not get passed between several threads. Since StringBuilder is not thread-safe this would be the only case where StringBuffer should be used. And of course it’s not the silver performance bullet but just one slice in string-heavy applications.

  • Recovering slowly and preparing Java Tips

    Over the last ten (or so) days, just right for Easter, my health status went down again. I cought a small cold, not enough to keep me from working but bad enough so that I spent my non-work time in bed to recover faster. This helped somewhat in the way that it did not get worse anymore and today I’m not really feeling much of that issue anymore.

    But this recovering was paid expensive. My spine aces returned, most probably caused by the lying-in-bed and limited exercising because of my injured ankle. Currently it’s bad, not as bad as back in 2006, but still enough so that it causes me a constant pain in the lumbar spine. For now I just can fight this with pain killers but I know I need to get back to exercising as fast as possible to strengthen my muscles in this area again and get stabilized. Of course, I have to pay attention to the possible remainings of the cold and that I do nothing which could harm my wounded ankle.

    Totally unrelated to this, some time ago I began collecting the different improvements I make to our sourcecode at work. I did this because I recognized, that I often applied the same improvements over and over again to other people’s sourcecode and a lot of them are quite similar to each other. Most of this improvable code exists, because people just don’t know that similar functionality already exists in common frameworks and so algorithms and operations get reingeneered again and again.

    I plan to develop this collection so that each improvement has a before-after-example, a detailled explaination why this improvement is better, maybe a categorization into different areas (eg. Collections, Framework, Java5-Enhancement, etc.) and a difficulty-level. Maybe if this turns out well, I could also organize an internal training-event to spread this knowledge and raise the quality of our code just a tiny bit 🙂

    Nevertheless, I’m also thinking of publishing each tip here in the blog for free availability and open discussion, so stay tuned if you’re a Java developer, maybe there’s also something in for you.

  • Project Contours is now on track

    Yes, there has been silence for some time. Cause of that are the upcoming exams this weekend in lectures which awesomeness-level lies below that of a rotting potato.

    Nevertheless, there has been some progress. I finally decided a name and hoster for my project which I’ve been pondering now for almost two semesters at University. And with some traces of proudness I finally present you the

    Contours Framework

    To admit, the hardest part was really to find a proper name for it, which should hint a bit into the direction of the topic without colliding with other projects. Another earlier try was "Shapes" but there are already several projects around with that term in their name and which are probably more popular on search terms than my project will ever be.

    In more details, the project is about creating a framework which allows Java application developers to create a file-reader for arbitrary binary files which then allows easy access to the content data from the file. This is done by providing a custom file-description language in which the structure of the file can be laid out. Then this format description is taken by the Contours framework which produces all necessary Java code for a file reader for files of this structure. This reader can then be easily be integrated into the own Java application.

    I know, it’s not a very common problem this addresses and there are other preferable ways for most similar problems. But I needed something which makes it easy to follow changes in file formats without the need to regenerate and review large parts of existing Java code. Furthermore when I’m dealing with more than one or two different formats, the maintenance of several different readers written by different people gets unhandy quite fast. And finally one of the goals was to produce code which allows high processing speed. When I started my project, there was no framework around addressing all of these points (and there still is none). Nowadays there are some available (one of them being Preon) but none of them seems to fit the performance requirement. And I’ve gotten already quite far when I discovered those, so I chose to continue with it and if it’s just for learning purposes.

    Nevertheless, the page is up, some content already present (notably the architecture description of Contours) and all source committed to the Contours SVN source repository. Feel free to have a look at it and if you have any comments, comment here or raise an Issue (when I come around to enable and configure that part of the project properly).

  • Archive of outdated Sun/Java software

    Sun makes it not easy to get your hands on previous versions of their software, especially if it is somehow connected to the Java technology. Their frontpages only contain the links to the latest software and (if you’re lucky) tiny hints how to get to the previous version of eg. the JRE. But if you’re looking for example for the outdated JRE 1.2, y

    Thanks goes to a friend who gave me the link to the Java Technology Downloads Archive where a lot of previous editions for the different Java software components are available through a single page for download.

    This includes all versions of JRE, JDK, J2EE, several additional Java technologies and even the Java SE Tutorials.

    The only thing I’m currently missing are deprecated versions of the J2ME technologies, but I don’t know if there are older versions even existing of J2ME.

    The full list of downloadable items currently: Java Certification Program, J2EE IDE Toolkit, JavaBeans Activation Framework, JDBC, Java 2 Platform Enterprise Edition (J2EE), Java Platform Standard Edition (Java SE), Java Development Kit (JDK), Java Cryptography Extension, Java Authentication and Authorization Service, Java Secure Socket Extension, Java Foundation Classes (JFC), Swing, Java HotSpot Server VM, Java Internationalization and Localization Toolkit, Java Message Service, Java Plugin (+ Converter), Java Servlet, RMI over IIOP and the Java SE Tutorials.

  • Useful Eclipse plugins for Java development

    Last time I’ve been posting about how you can increase your java development speed by knowing and using common and handy keyboard shortcuts. This time I’ll be showing you some plugins which I have used over the time. For most of them I can say that they not so much speed up development but instead raise the quality of your sourcecode by giving you hints or adding certain aspects to testing.

    So let’s dive in.

    Subclipse and Subversive are with high probability the most-installed plugins for distributed development and source code versioning. As Eclipse still does not provide builtin functionality for this (because of some licensing issue), these plugins add the required connectors so that it becomes possible to synchronize your source with a SVN server. Both plugins provide everything needed for most of the SVN tasks and differ just in edge cases or the handling and UI details. I’m personally using Subversive for years now because it has a Checkout-Wizard with more functionality than Subclipse offers but that plugin also has evolved since I checked it the last time. I should give it a try again in the near future.

    The JD-Eclipse plugin is a decomplier addon for Eclipse which helps you out if you happen to stumble into Java bytecode eg. during debugging or when you follow references into external libraries. It reconstructs the Java source from the compiled code, so what you get is not the real sourcecode but something which resembles exactly the same function. Nevertheless it’s often interesting how the code behind the APIs works you’re using. Or, if you’re depending on other projects which are currently just closed in your workspace.

    Findbugs is a static source-code-analysis tool which checks your sourcecode for common mistakes optimization potential. It covers a very wide range of different bug types and each found bug or issue in your sourcecode has a small description added. Of course, since it’s a statical analysis this tool is unable to analyze the whole logic in your sourcecode and therefore may also generate false positives, so be sure to not blindly follow each suggestion. But it’s usefulness in general is undeniable.

    Also a static analysis is done by Checkstyle but this one focusses less on programming errors but more on the layout of the code and the correctness of the documentation. For example if your javadoc for a method is missing a new parameter which you just added, Checkstyle would highlight this mismatch for you. It has an extensive ruleset so don’t be surprised if it makes annotations all over your code if you check it for the first time.

    EclEmma and Coverlipse are two plugins which deal with identifying the runtime coverage of your code. They add measuring instruments which allow you to determine which parts of your code are reached by eg. unittests and which parts of your code are still untested and need additional attention. EclEmma is the simpler one of the two but also is faster to get started with. Coverlipse on the other side needs a bit more work to get started but allows deeper inspection and offers a wider range of statistics and visualizations of the covered and uncovered code.

    Another tool to aid with testing is Infinitest. It analyzes your JUnit tests and runs them silently in the background after each change in your sourcecode. It adds some intelligence so that only those tests are run which could be influenced by your changes. Furthermore errors in the tests are directly displayed as source-errors in your sourcecode. Of couse, this is only useful if your testcases can be executed fast and do not need an extended time to execute. The plugin has moved from the free Google-Code project to a commercial website but as far as I can see, the plugin itself is for now still available without cost.

    If you want to quickly set up a shared task repository for your small team without having to set up a full blown Bugzilla, maybe even with a touch of Scrum, Scrum Vision may be the tool for you. It connects the task management of Eclipse (Mylyn) with a Google spreadsheet which also can be shared with other instances of Eclipse for other developers. The IDE aligns with the Scrum methodology to support agile development. This alignment also propagates in the spreadsheet where you can display reports and have a virtual taskboard and also a Burndown Graph.

    If you’d like to close editor tabs the same way as you do in Firefox, by middle-clicking the tab, the Middle Click Closes Tab plugin (although last updated for Eclipse 3.3, it still works with Galileo) enhances your Eclipse with this feature.

    As for Mylyn, which is already completely integrated in Eclpse: Since my last post according Mylyn I collected some additional experience with Mylyn. I also connected it to a local instance of Bugzilla to play a bit around with its integration and how it deals with sharing files and context. But I also think that I should use it more again, as I’ve become a bit lazy with it and fallen back to the previous everything-on-the-screen overloaded development. The promised blog post which hasn’t been posted until now is still on my list for the future, when I know even more about Mylyn. But I already can suggest Mylyn as a tool to leverage the development effectivity by helping the developer to focus on the actual task at hand. If you’re curious, have a look at the excellent Mylyn 3.0 webcast to get started.

    That’s it for now. I hope, there is also something useful in this post which is helpful for your Java development with Eclipse.

  • Useful Eclipse keyboard shortcuts for Java development

    Since I’ve started developing Java in Eclipse I have realized that this is in no way different than with most other IDEs: the speed of development highly depends on the knowledge and intuitive usage of keyboard shortcuts.

    Occassionally I’m asked to slow down a bit so that one can follow my actions or to tell which shortcut I’ve just used. For this reason I’m making this small list of those shortcuts which I’m using pretty much all the time.

    I’ve tested these shortcuts specifically on Eclipse Galileo (3.5.1) and on Windows but most of them are also already present on earlier versions of Eclipse. As for other platforms I don’t really know if all of them (or even any one of it) are available (or at the same combination). Furthermore many of them should also be present when developing different programming languages than Java but I cannot confirm that. You just have to find out yourself. Just in case you do, please let me know in the comments 🙂

    So without further ado:

    Shortcut Function Description
    CTRL+SHIFT+R Open Resource brings up a dialog where you can quickly locate any file or resource in your workspace. Wildcards are supported in the search.
    CTRL+SHIFT+O Organize Imports cleans up the imports-block at the beginning of the file. Adds missing imports (if neccessary) and removes unused ones.
    CTRL+SHIFT+F Format applies proper formatting to the source code according to the style-settings in the *Java->Code Style->Formatter* preferences.
    ALT+UP/DOWN Shift moves the current line or selection up or down one line. Very useful for fast relocation of code, much faster than cut/paste if just moving a few lines.
    CTRL+ALT+UP/DOWN Duplicate duplicates the current line or selection above or below the current line/selection. Allows the fast population of cases in switch/case statements if they differ just marginally or similar situations like variable-initializer blocks. Beware, that this shortcut is often also overridden by some Intel display drivers. If this one does not work for you, try to turn off or change the hotkey assignment in your display driver helper application.
    CTRL+O Quick Outlne brings up a small dialog which allows to search and navigate the outline of the current file. Just start typing to narrow down the results. Supports wildcards. Pressing CTRL-O again toggles the display of inherited methods.
    CTRL+PGUP/PGDOWN Switch Tab changes to the next/previous editor-tab.
    ALT+SHIFT+L Extract Local Variable Creates a local variable from the currently selected expression. Types are automatically added. Try it on the code ‘new HashMap();’ to understand how this can speed up your development. Works on variables, static strings, methods with return values, etc.
    ALT+SHIFT+I Inline Variable opposite of local variable extractions. Replaces all occurences of the currently selected variable with its assigned value. Only works if the value of the variable is set exactly once.
    CTRL+ALT+H Call Hirarchy shows all calls/usages of the currently highligted variable/interface/class/method.
    F3 Open Declaration Jumps to the declaration of the currently highlighted variable/interface/class/method. Similar to holding down CTRL and clicking with the mouse on a variable/interface/class/method.
    CTRL+SHIFT+L Show Key Assist Displays a popup which displays currently assigned keyboard shortcuts. Very useful if you are looking for further shortcuts quickly. A shortcut for shortcuts 😉

    There are many more shortcuts available, including the marking and navigation shortcuts which you should know from Microsoft Word, but the above ones are the ones which became ingrained in me and are now speeding up my Java development enormously. Try to get used to them and use them whenever you can and you’ll realize that there will be fewer and shorter interruptions to your stream of thought and it also aids your concentration.

    If you want to go a tad further and let Eclipse tell you about possible shortcuts (or even force you to use one by cancelling all mouse-events which have a shortcut) you can install the MouseFeed Eclipse Plugin which does exactly this by displaying a small shortcut reminder each time you issue a shortcutted command with the mouse. Although it’s a plugin for Eclipse 3.3, it still works with Galileo.