Wednesday, August 22, 2018

Coding practice and conventions in Java

Anyone can write code a computer can understand, but professional developers write code *humans* can understand. Clean code is a reader-focused development style that produces software that's easy to write, read and maintain.



I have seen code written for the products which are serving more than 2 dozen clients with single database and 1 codebase. This is amazing. The reason they were successfully managed to do so was because of the coding standards they follow. The use of standard coding practice in your project makes life easy. 

If you set your standards very much in the beginning before you actually start coding for a product, it will become the rule for the fellow developers and makes life earsier for the new comers and the coders who have to decode you wrote in the beginning.

Having standards gives you the checkpoints to identify if a developer writing a quality code or not. 

https://amzn.to/2wKFA4y


Also code conventions are important to programmers for a number of reasons:


  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create

I will try to cover all possible and important part of java standards in following sections.

 Java Source files

    Beginning comments

    All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice:

    /*
     * Classname
     * 
     * Version information
     *
     * Date
     * 
     */
     * Copyright notice
    

    Package and Import statements

    The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:

    package java.awt;

    import java.awt.peer.CanvasPeer;

    Indentation

    Line length

    Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.

    Wrapping Lines

    When an expression will not fit on a single line, break it according to these general principles:
    1. Break after a comma.
    2. Break before an operator.
    3. Prefer higher-level breaks to lower-level breaks.
    4. Align the new line with the beginning of the expression at the same level on the previous line.
    5. If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.

    Examples:

    Here are some examples of breaking method calls:


    someMethod(longExpression1, longExpression2, longExpression3,
            longExpression4, longExpression5);

    var = someMethod1(longExpression1,
                    someMethod2(longExpression2,
                            longExpression3));


    Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

    longName1 = longName2 * (longName3 + longName4 - longName5)
               + 4 * longname6; // PREFER

    longName1 = longName2 * (longName3 + longName4
                           - longName5) + 4 * longname6; // AVOID 

    Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

    //CONVENTIONAL INDENTATION
    someMethod(int anArg, Object anotherArg, String yetAnotherArg,
               Object andStillAnother) {
        ...
    }

    //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
    private static synchronized horkingLongMethodName(int anArg,
            Object anotherArg, String yetAnotherArg,
            Object andStillAnother) {
        ...
    }

    Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

    //DON'T USE THIS INDENTATION
    if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) { //BAD WRAPS
        doSomethingAboutIt();            //MAKE THIS LINE EASY TO MISS

    //USE THIS INDENTATION INSTEAD
    if ((condition1 && condition2)
            || (condition3 && condition4)
            ||!(condition5 && condition6)) {
        doSomethingAboutIt();

    //OR USE THIS
    if ((condition1 && condition2) || (condition3 && condition4)
            ||!(condition5 && condition6)) {
        doSomethingAboutIt();
    }

    Here are three acceptable ways to format ternary expressions:

    alpha = (aLongBooleanExpression) ? beta : gamma;  

    alpha = (aLongBooleanExpression) ? beta
                                     : gamma;  

    alpha = (aLongBooleanExpression)
            ? beta 
            : gamma;

    Declarations

    Number Per Line

    One declaration per line is recommended since it encourages commenting. In other words,

      int level; // indentation level
      int size;  // size of table

    is preferred over

      int level, size;

    Do not put different types on the same line. Example:

      int foo,  fooarray[]; //WRONG!   

    The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs

    Initialization


    Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

    Placement

    Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

    Class and Interface Declarations

    When coding Java classes and interfaces, the following formatting rules should be followed:

    No space between a method name and the parenthesis "(" starting its parameter list
    Open brace "{" appears at the end of the same line as the declaration statement
    Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{"

    class Sample extends Object {
        int ivar1;
        int ivar2;

        Sample(int i, int j) {
            ivar1 = i;
            ivar2 = j;
        }

        int emptyMethod() {}

        ...
    }


    Methods are separated by a blank line


    Happy reading...

    Thursday, May 10, 2018

    How to find the missing number in a sorted array

    1. Problem Statement:

    You have given an integer array of size N. Array contains numbers from 1 to N-1 but a couple of numbers are missing in an array which also contains duplicates. Write a Java program to print the missing number from the sequence.

    For example, if given array is 
    {1, 1, 2, 3, 5, 5, 7, 9, 9, 9} then it has length 10 and contains a number from 1 to 9. In this case, missing numbers are 4, 6, and 8.




    2. Solution:
    When you see the question is to find missing number in array, you might think about our earlier solution of calculating sum of all the numbers and deducting it from expected sum to find the missing number, but unfortunately that will not work in this situation because more than one number is missing as well it contains duplicates.

    In this case, we need to use a different approach, something like a roll-call you would have seen in your school.

    The teacher has a register with names of all students, he goes through the list and mark absences on red. We can use the same approach to find all the missing numbers in the list.

    We can use an array as register and it's index as names of the numbers. We 
    loop through the given array and tick marking all the numbers which are present by storing one of their respective indices. For example, if the first number in given array is 5 (since the array is not sorted) then we store 1 on index 5 e.g. register[5] = 1

    Once we have gone through all the numbers is given, we can go through our register array and print all the indices where the value is zero. These are absentees or missing numbers.

    This solution is also safe from duplicates because if a number comes once or twice we just store 1 on the respective index.



    3. Code:

    Now that we know how to solve this problem of missing numbers in unsorted integer array with duplicates, it's time to turn this solution into a code and working Java program.


    /*
     * Java Program to find missing numbers in an integer
     * array with duplicates. Array may contains more
     * than one duplicates.
     *
     * input: {1, 1, 2, 3, 5, 5, 7, 9, 9, 9};
     * output: 4, 6, 8
     */
    public class Hello {

      public static void main(String[] args) {

        // given input
        int[] input = { 1, 1, 2, 3, 5, 5, 7, 9, 9, 9 };

        // let's create another array with same length
        // by default all index will contain zero
        // default value for int variable

        int[] register = new int[input.length];

        // now let's iterate over given array to
        // mark all present numbers in our register
        // array

        for (int i : input) {
          register[i] = 1;
        }

        // now, let's print all the absentees
        System.out.println("missing numbers in given array");

        for (int i = 1; i < register.length; i++) {
          if (register[i] == 0) {
            System.out.println(i);
          }
        }
      }

    }
    Output
    missing numbers in given array
    4
    6
    8


    This is the simplest Java program to solve this problem. You can see that we have hardcoded the input array but you can also modify the program to get input from the user by using Scanner class.

    The code is exactly same as a solution, we created another array by copying 
    length from original array and used it mark numbers which are present.

    Since array indices are also integer and they are in the range of input values we can leverage them to use both as data and metadata. Had the array contains a number which is not in the range of 1 to N-1 then we couldn't have used an array.


    4. Analysis
    Now, the time is to analyze our solution to find the CPU and Memory complexity using Big O notation. If you look at the code then you will find that we are creating another array with the same size which means it has memory or space complexity of O(n).

    This means if the array is too big i.e. contains all the numbers in the integer range then we would a lot more memory which may not be available and our program could throw 
    OutOfMemoryError in Java. This is even more possible because array needs a contiguous chunk of memory.

    So, if we can remove the additional array which is not really holding anything and find a way to just store missing number which is quite less than the all the number that we can improve this solution, something for you guys to think.

    For time complexity, you can see that we iterate through the whole array to mark all present number and then iterate again to another array of the same length to find absentees. This means time complexity of this solution is 
    O(n) + O(n) or O(2N) which is in Big O Notation still O(n).

    We can further improve this solution if we find a way to print absentees as we iterate through the given array. Again, something to think of you guys.

    That's all about this classic problem of finding missing numbers in given integer array. In this part, we have found a solution for finding multiple missing numbers in the unsorted array with duplicates. The time and space complexity of our solution is O(n).


    How about reading this fantastic book 

    Tuesday, May 8, 2018

    StringJoiner

    I recently came to know about a new feature of java 8 StringJoiner

    StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

    Simply put, it can be used for joining Strings making use of a delimiter, prefix, and suffix.

    This is a final class comes under Object class. It has following methods:


    StringJoiner  add(CharSequence newElement)

    Adds a copy of the given CharSequence value as the next element of the StringJoiner value.

    int length()

    Returns the length of the String representation of this StringJoiner.

    StringJoiner merge(StringJoiner other)

    Adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty.

    StringJoiner setEmptyValue(CharSequence emptyValue)

    Sets the sequence of characters to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty.


    How to use StringJoiner?

    1.  Join String by a delimiter
    2. StringJoiner sj = new StringJoiner(",");
              sj.add("aaa");
              sj.add("bbb");
      
              sj.add("ccc");
              String result = sj.toString(); //aaa,bbb,ccc
      
    3. Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix.
    StringJoiner sj = new StringJoiner("/", "prefix-", "-suffix");
            sj.add("2016");
            sj.add("02");
            sj.add("26");
            String result = sj.toString(); //prefix-2016/02/26-suffix
    


    Happy Reading!

    Sunday, October 29, 2017

    How to find max memory, free memory and total memory in Java

    As per Javadoc freeMemory is currently available memory which can be allocated to future objects and totalMemory is the total amount of memory in the Java virtual. Since we know that JVM expands heap whenever it needs so if we start our JVM with -Xms10m and -Xmx120m you should expect that initialfreeMemory and totalMemory should be same with starting heap size of JVM as Virtual machine has not been expanded yet and that's the case exactly. even value returned by Runtime.maxMemory() will be close to value of -Xmx though little less. In this article we will see how to get approximate value of inital and maximum heap size, free memory available in JVM and used memory or memory currently occupied by objects in heap.


    How to get free Memory in Java

    In order to get currently free Memory available for creating object use Runtime.getRuntime().freeMemory() method, this will return size in bytes, which you convert in Mega Bytes for better readability. we will see an example of getting initial heap and free memory in code example section. Calling Garbage collector by either System.gc() or Runtime.gc() may results in slightly higher free memory reclaimed by dead objects.


    How to get total Memory in Java

    You can use Runtime.getRuntime.totalMemory() to get total memory from JVM which represents current heap size of JVM which is a combination of used memory currently occupied by objects and free memory available for new objects. As per Javadoc value returned by totalMemory() may vary over time depending upon the environment. see the code example for getting total memory in Java in next code example section.


    How to get initial Heap Size from Java Program

    We specify initial heap space by using -Xms and JVM creates initial heap with this much size. in order to get this size from Java program call Runtime.getRuntime.totalMemory() before creating any object. See code example of getting initial heap size from java program in next section. Apart from –Xms and –Xmx there are lot of other useful JVM Options I have shared on my post 10 useful JVM parameters Java Programmer should know.

    How to get maximum Heap Size from Java Program

    This is relatively easy as maximum heap space is not going to change over JVM life cycle and call to Runtime.getRuntime.maxMemory() will return value close to -Xmx but keep in mind exact value will be little less than what have you set.


    How to get Used Memory in JVM

    by using Runtime.getRuntime.totalMemory() and Runtime.getRuntime.freeMemory() we can calculate how much space has been currently occupied by Java object or you say used memory in JVM as show in below code example of getting memory sizes in Java:

    Example:


    public class MemoryUtil{
    
           private static final int MegaBytes = 10241024;
    
           public static void main(String args[]) {
    
                  long freeMemory = Runtime.getRuntime().freeMemory()/MegaBytes;
                  long totalMemory = Runtime.getRuntime().totalMemory()/MegaBytes;
                  long maxMemory = Runtime.getRuntime().maxMemory()/MegaBytes;
    
                  System.out.println("JVM freeMemory: " + freeMemory);
                  System.out.println("JVM totalMemory also equals to initial heap size of JVM : "
                                             + totalMemory);
                  System.out.println("JVM maxMemory also equals to maximum heap size of JVM: "
                                             + maxMemory);
    
                  ArrayList objects = new ArrayList();
    
                  for (int i = 0; i < 10000000; i++) {
                         objects.add(("" + 10 * 2710));
                  }
    
                  freeMemory = Runtime.getRuntime().freeMemory() / MegaBytes;
                  totalMemory = Runtime.getRuntime().totalMemory() / MegaBytes;
                  maxMemory = Runtime.getRuntime().maxMemory() / MegaBytes;
    
                  System.out.println("Used Memory in JVM: " + (maxMemory - freeMemory));
                  System.out.println("freeMemory in JVM: " + freeMemory);
                  System.out.println("totalMemory in JVM shows current size of java heap : "
                                             + totalMemory);
                  System.out.println("maxMemory in JVM: " + maxMemory);
    
           }
    }
    
    Output:
    JVM freeMemory: 9
    JVM totalMemory also equals to initial heap size of JVM : 9
    JVM maxMemory also equals to maximum heap size of JVM: 116
    Used Memory in JVM: 81
    freeMemory in JVM: 35
    totalMemory in JVM shows current size of java heap : 108
    maxMemory in JVM: 116
    

    How to find if JVM is 32 or 64 bit from Java program.

    You can find JVM bit size e.g. 32 bit or 64 bit by using either running java command from the command prompt or by using System.getProperty() from Java program. The question is why do you want to know hardware or platform configuration while writing Java code which is supposed to write once and read anywhere(32 bit, 64 bit etc)? Yes we don't really need to know whether JVM is 32 bit or 64 bit more often but there are many situations when this matters

    Check if JVM is 32 or 64 bit from Java program:


    1. Since in 32 bit JVM maximum heap size in Java can not be more than 4GB (theoretically) , if you can get JVM version from a script like running java command you can have different memory configuration for your application. Also, if there is any specific JVM options which only applicable to 64 bit JVM than you can set those.
    2. If your Java application is using native libraries then you certainly want to know whether Java running on the host is 32 bit or 64 bit because native library may have different versions loaded for 32 bit or 64-bit architectures.


    I am sure there could me some more practical reasons when you like to find JVM bit size or whether JVM is 64 bit or not

    Now let's come to second part how to find if JVM is 32 bit or 64 bit in Java.

    How to check if JVM is 32 or 64 bit in host

     As I said earlier there are two different approaches either using Java system property like "sun.arch.data.model" or "os.arch" or by running java command from script and checking its output for certain characters to identify whether JVM is 64 bit or not. let's see example of different ways to find if JVM is 32 bit or 64 bit:


    1. By using System property sun.arch.data.model:


    You can find whether your JVM is 32 bit or 64 bit by calling System.getProperty("sun.arch.data.model") at least on Sun's hotspot JVM. I don't expect this to be run on any other Vendor specific JVM but since most of the programmer or project uses Sun's hotspot JVM. this is an handy option. for 32 bit JVM "sun.arch.data.model" will be 32 and for 64 bit JVM this would be 64. here is an example:

    System.out.println("JVM Bit size: " + System.getProperty("sun.arch.data.model"));

    Output:
    JVM Bit size: 32 //JVM is 32 bit
    JVM Bit size: amd64 //JVM is 64 bit

    2)By using System.getProperty("os.arch")

    "os.arch" is another System property which you can use to find whether installed JRE or JVM is 32 bit or 64 bit. by name it sounds that it will return operating system arch but you can still give it a try. Though I haven't tested on all different JVM, I have read that it can indeed return JVM Bitness.If you try this on 64 bit machine and 32 bit JVM combination than please let us know what does it return. here is what it returns in case of 32 bit JVM:

    System.out.println("JVM Bit size: " + System.getProperty("os.arch"));

    JVM Bit size: x86 //on 32 bit JVM
    JVM Bit size: amd64 //on 64 bit JVM

    3)java -d64 -version

    This is another way of finding whether installed JRE or JVM is 64 bit or not but unfortunately, it
    doesn't work with all windows version like Windows XP but it works fine on Windows 7. So you still
    use it on Windows7 Machine for finding JVM bitness.

    4)java -version

    Plain old java -version reveals information about JVM bitness only if installed JRE is 64 bit, in case
    of 32 bit JVM it doesn't provide any information related to architecture but in the case of 64 bit JVM it
    prints :
    C:\>java -version
    java version "1.6.0_25"
    Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
    Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)

    while in case of 32 bit JVM it will print
    C:\> java -version
    java version "1.6.0_26"
    Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
    Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)


    That’s all on how to find if JVM is 32 bit or 64 bit from Java program and command prompt. As I said its particularly useful if you have a dependency on native libraries which has a different build for 32 bit or 64-bit architecture. Let me know if you have some more ways to find JVM is 64 bit or not, you can also share on which scenario you need to know JVM bitness.




    Wednesday, October 18, 2017

    Top 5 JSON libraries for a java developer should know


    The JSON format is one of the most popular formats to transfer and exchange data in web. Almost all RESTful web services take JSON input and provide JSON output but unfortunately JDK doesn't have built-in support for one of the most common web standard like JSON. As a Java developer if you want to develop RESTful web service and produce JSON data or if you are developing a client to an existing RESTFul web services and want to consume JSON response, you don't need to be disappointed. Fortunately, there are so many open source libraries and API available for creating, parsing and processing JSON response in Java e.g. Jackson, Google GSon, json-simple etc.
    Actually, there are numerous JSON libraries exists in Java but you don't need to learn all of them, learning just one of them e.g. Jackson should be enough, but, on the other hand, it's worth knowing what are some of the most popular JSON parsing library exists in your disposal. In this article, I am going to share 5 useful JSON libraries which I believe every Java JEE developer should be aware of.
    If you are new to JSON, probably heard about it but doesn't know what is JSON there here is a brief introduction of JSON for you. The JSON is an acronym for JavaScript Object Notation, is a lightweight data-interchange format, an alternative to XML, but smaller, faster and easier to parse. Because JSON uses the JavaScript syntax for describing data objects, it is language and platform independent and many parsers and libraries have been developed over the years. You can also read Java XML and JSON to learn more about pros and cons of JSON over XML.

    5 Useful JSON libraries in Java

    Here is my list of most useful and essential JSON libraries for Java developers. Though I have used them some or other time or other I mostly prefer Jackson because it's a feature rich and I believe in consistency. It doesn't mean those other libraries are not useful, they also have their own strength e.g. Gson is much simpler to use as compared to Jackson and json-simple is a really light-weight library without any third party dependency.
    As the purpose of this article is to make you, a Java developer aware of useful JSON library, I leave the decision of choosing the JSON library to yourself. Depending upon your need, you can choose any of them.

    Jackson

    Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers.
    Jackson offers three methods for processing JSON format, each of them having it’s pros and cons:

    1. Streaming API or incremental parsing/generation: reads and writes JSON content as discrete events
    2. Tree model: provides a mutable in-memory tree representation of a JSON document
    3. Data binding: converts JSON to and from POJO’s
    If you are only interested in converting Java object to and from JSON string then the third method is most appropriate for you.
    Pros of Jackson is that It provides heaps of features, and looks to be a good tool for reading and writing JSON in a variety of ways, but same time its size becomes a disadvantage if your requirement is just to serialize and deserialize Java object to JSON String. 
    In order to use Jackson, you can include following maven dependency or manually include jackson-core-2.3.1.jar, jackson-databind-2.3.1.jar, and jackson-annotations-2.3.1.jar in Classpath.
    
    

    GSON

    The second Java JSON binding library we will discuss is Gson, or if you prefer the full name, the google-gson library. Gson is a Java library capable of converting Java objects into their JSON representation and JSON strings to an equivalent Java object without the need for placing Java annotations in your classes.
    Some of the salient features of Gson library are:

    1. Provides simple toJson() and fromJson methods to convert Java objects to JSON and vice-versa
    2. Supports arbitrarily complex objects
    3. It has extensive support of Java Generics
    4. Allow custom representation for objects
    5. Allow pre-existing unmodifiable objects to be converted to and from JSON

     json-simple 

    The json-simple is one of the simplest JSON library, also lightweight. You can use this library to encode or decode JSON text. It's an open source lightweight library which is flexible and easy to be used by reusing Map and List interfaces from JDK. A good thing about this library that it has no external dependency and both source and binary are JDK 1.2 compatible.

    Pros of Json-simple is that it is lightweight, just 12 classes and it provides support for Java IO readers and writers. You can take your decision better if you know about JSON format i.e.g how information is represented there. 
    If you are looking for a simple lightweight Java library that reads and writes JSON and supports Streams, json-simple is probably a good match. It does what it says with just 12 classes, and works on legacy (1.4) JREs as well.
    In order to use JSON-Simple API, you need to include maven dependency in your project's pom.xml file or alternatively, you can also include following JAR files in your classpath.

    Flexjson

    Flexjson is another lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. The depth to which an object is serialized can be controlled with Flexjson and thus making it similar to lazy-loading, allowing us to extract only the information we need. This is not the case since we want an entire object to be written to file, but it’s good to know that it can do that.
    If you know that you are going to use only a small amount of data in your application and you wish to store or read it to and from JSON format, you should consider using Flexjson or Gson.

    JSON-lib

    JSON-lib is a Java library, based on the work by Douglas Crockford, capable of transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.
    If you are going to use large amounts of data and wish to store or read it to and from JSON format, you should consider using Jackson or JSON-lib.
    That's all about some of the useful JSON libraries in Java. You can use these libraries to parse JSON String and generate Java objects or create JSON String from your existing Java objects.
    If you are dealing with Web services which return JSON response then these libraries are very important for you. You can choose between them depending upon your need e.g. if you need features and speed then Jackson is probably the best, if you need simplicity then Google Gson looks better to me and if you are concerned about third party dependencies then json-simple or Flexjson can be a good choice.
    
    

    Sunday, October 15, 2017

    Different implementation of RESTFUL webservices

    The JAX-RS is a Java specification request (JSR 311 & JSR 339) which standardize development and deployment of RESTful web services using Java and JEE technologies. It provides API in Java Programming language to create web services according to the REST (Representational State Transfer) architectural pattern. Both Restlet and Jersey are two of the most popular implementation of JAX-RS used for developing RESTful web services in Java ecosystem but there are a couple of other implementation also exist e.g. Apache Wink, Apache CXF, and JBoss RESTEasy. In this article, I'll introduce with these RESTful web services framework in Java world. It's not a very detailed post about strength and weakness of each of the framework but will just give you enough to understand them in detail later.

    It will also help you to answer the RESTful web service questions like, what is the difference between Restlet, Jersey, and Apache CFX? which one you have used in past, or which one will you choose for your next project and why?

    Difference between JAX-RS, Restlet, Jersey, RESTEasy, and Apache CXF Frameworks

    Jersey



    Jersey RESTful Web Services framework is open source, production quality, a framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) reference Implementation and initially provided by Sun Microsystem.
    Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extends the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.

    Jersey also has some of the best tooling (IDE) support especially if you are using Netbeans. So you can achieve better productivity from the tooling perspective. There are some challenges with Jersey-Spring integration, especially with AOP.

    The latest release of Jersey is 2.26


    Restlet


    One of the first open source framework for developing RESTful web services in Java. Restlet Framework helps Java developers build better web APIs that follow the REST architecture style. Restlet has a light core but thanks to its pluggable extension, it is also a comprehensive REST framework for Java. It supports all REST concepts (Resource, Representation, Connector, Component, etc.) and is suitable for both client and server Web applications.


    It supports major Web standards like HTTP, SMTP, XML, JSON, OData, OAuth, RDF, RSS, WADL, and Atom.

    Many extensions are also available to integrate with Servlet, Spring, Jetty, Simple, JAXB, JAX-RS, JiBX, Velocity, FreeMarker, XStream, Jackson, SLF4J, SDC and much more!

    Special editions for Android, GWT, GAE, Java SE, Java EE, and OSGi are also available and kept synchronized with an automated porting process.

    Another advantage of using Restlet framework is that Restlet based program can run as a standalone Java application. The Restlet also supports Java EE environment with the help of Jetty web container. So this may result in a light-weight implementation and have a unique value that way. There are some challenges or manual work involved in de-marshalling the response into java object. See Restlet in Action to learn more about the Restlet framework.


    Apache CXF

    The CXF is another free and open source web service framework and a JAX-RS implementation from Apache. CXF helps you to build and develop services using frontend programming APIs like JAX-RS and JAX-WS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS, and JBI.

    One of the key difference between Apache CXF and Jersy's JAX-RS implementation is that it is implemented as a CXF filter sitting behind the servlets, while Jersey and RestEasy are, servlet filters.

    One more advantage of using ApacheCXF is that it makes it easy to produce both a JAX-RS and JAX-WS (SOAP) endpoint from the exact same data model and service interface at the same time. So if that is something which matters to you, this may be the way to go. CXF had issues with handling SSL and HTTP proxies which seem to have been addressed in recent releases.  You can also read Developing Web Services with Apache CXF and Axis2 to learn more about developing RESTful web services using Apache CXF framework in Java.



    RESTEasy

    The RESTEasy is another good JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS specification.

    RESTEasy may be a good choice if your environment is JBoss oriented e.g. you are using JBoss Application Server, Hibernate and RedHat Middleware, Linux etc. It also provides good integration with EJB 3.0 and SEAM (something to consider if you have a need for that). Also, it has a proprietary caching for URL or query which could be handy for high volume applications.


    That's all about the difference between JAX-RS, Restlet, and Jersey in Java. In short, JAX-RS provides the API and these two are the implementation of that API, where Jersey serves as reference implementation but Restlet has got bigger and more matured community around it.

    All of these are also mature and production ready frameworks. Chances of going wrong with any of them are quite less. They all have integration capabilities with Spring.  So You can use either Restlet, Jersey or any other framework to develop RESTful web services in Java.


    Happy Reading...

    Click here to installl Flipkart App

    Traditional Threads vs. Virtual Threads: A Performance Benchmark on Spring Boot 4

    Traditional Threads vs. Virtual Threads: A Performance Benchmark on Spring Boot 4 Bottom line: For high-concurrency Spring Boot apps on mo...