Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, December 12, 2019

Resolving ClassNotFoundException in Java

ClassNotFoundException is a checked exception and subclass of java.lang.Exception. Recall that, checked exceptions need to be handled either by providing try/catch or by throwing it to the caller. You get this exception when JVM is unable to load a class from the classpath. So, troubleshooting this exception requires an understanding of how classes get loaded and the significance of classpath.

Root Cause of java.lang.ClassNotFoundException

Java doc of java.lang.ClassNotFoundException puts it quite clearly. It gets thrown in below cases when the class definition is not found-
  • Load class using forname method of class Class
  • Load class using findSystemClass method of ClassLoader
  • Load using loadClass method of ClassLoader
References:
http://javaeesupportpatterns.blogspot.in/2012/11/javalangclassnotfoundexception-how-to.html 

Saturday, July 20, 2019

Thoughts on GC friendly programmig

Garbage Collections in Java gets triggered automatically to reclaim some of the occupied memory by freeing up objects. Hotspot VM divides the Heap into different memory segments to optimize the garbage collection cycle. It mainly separates objects into two segments - young generation and old generation.

Objects get initially created into young gen. Young gen is quite small and thus minor garbage collection runs on it. If objects survive the minor GC; then they get moved to the old gen. So it's better to use short-lived and immutable objects than long-lived mutable objects.

Minor GC is quite fast (as its runs on smaller memory segment) and hence it's less disruptive. The ideal scenario will be that GC never compacts old gen. So if full GC can be avoided you will achieve the best performance.

So a lot depends on how you have configured your heap memory and another important factor is do you code keeping in mind these aspects.

http://www.ibm.com/developerworks/library/j-leaks/
http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java/6471947#6471947

Sunday, June 11, 2017

Measuring Execution Time of a Method in Java

Old fashioned Way
System.currentTimeMillis()
Accuracy is only in milli seconds, so if you are timing a method which is quite small then you might not get good results.

List<Integer> input = getInputList();
long t1 = System.currentTimeMillis();
Collections.sort(input);
long t2 = System.currentTimeMillis();
System.out.println("Time Taken ="+ (t2-t1) + " in milli seconds");

Using Nano seconds
System.nanoTime()
Preferred approach (compared to first one). But do keep in mind that not all systems will provide accuracy in nano time.

List<Integer> input = getInputList();
long t1 = System.nanoTime();
Collections.sort(input);
long t2 = System.nanoTime();
System.out.println("Time Taken ="+ (t2-t1) + " in nano seconds");

Java 8
List<Integer> input = getInputList();
Instant start = Instant.now();
Collections.sort(input);
Instant end = Instant.now();
System.out.println("Time Taken ="+ Duration.between(start, end) + " in nano seconds");

Guava

Stopwatch stopwatch = new Stopwatch().start();
Collections.sort(input);
stopwatch.stop();


Saturday, February 18, 2017

Java 8 method references

This post talks about one of the coolest feature of Java 8; method references!

Methods are no longer second class values in Java 8. Just like object references which can be passed around as values, methods can also be passed around as values. To achieve this, Java 8 provides notation, :: (along with lambda, off course)

You might argue that, lambda functions do the same thing. And you are write to a great extent. The only fundamental difference is that, this way you can simply refer to a method without writing the full body of the method (as we do in lambda).

Lambda vs Method Reference
Function<Double, Double> square = (Double d) -> d * d;   //lambda
Function<Double, Double> square = Arithmatic::square    //method reference

Arithmatic::square is a method reference to the method getSquare defined in the Arithmatic class. Brackets are not needed because we aren't calling the method actually.

(String s) -> System.out.println(s)     //lambda
System.out::println                            //method reference

In lambda, you just call the method without it's name but in method reference you explicitly refer it by name. This way, code is more readable.

--
happy functional programming !

Sunday, January 29, 2017

Applying RxJava on a Fibonacci Sequence Generator

This post shows how can we marry an exiting method which generates a Collection into an Event Stream and then React to it using RxJava. I have discussed fundamentals of RxJava in this previous post.

Let's assume that we have a method which generates first k Fibonacci sequences and returns them as a Collection.


//Generates first k fibonacci numbers
private static List<Integer> generateFibonacci(int count) {
        List<Integer> resp = new ArrayList<> ();
        resp.add (0);
        resp.add (1);
        for(int i=2; i< count; i++){
            resp.add(resp.get (i-1) + resp.get (i-2));
        }
        return resp;
    }


Reactive Programming is programming with Asynchronous Data Streams. In this previous post, I have discussed fundamentals of RxJava. This post will show different ways to apply RxJava constructs on above method.

Observable Creation

Observable provides methods to convert an array, Collection, Future, or even a normal function into Observable. 

from - Converts an Iterable sequence into an Observable that emits the items in the sequence. 

Observable.from (generateFibonacci (10) );

Please note that, method returns a Collection which is of type Iterable so it can be converted into an Observable. 

fromCallable - Returns an Observable that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function.
Observable.fromCallable (() -> generateFibonacci (10));

Transforming Observable

RxJava provides different operation which can be applied on Observable to transform it. Let transform above observable in such a way that only fibonacci element which are less than 15 gets finally pushed to the subscriber. 
filter - Filters items emitted by an Observable by only emitting those that satisfy a specified predicate.
   //1st Approach
        Predicate<Integer> predicate = new Predicate<Integer> ( ) {
            @Override
            public boolean test(Integer integer) {
                return integer < 15;
            }
        };

        Observable.from (generateFibonacci (10))
                .filter (i -> predicate.test (i));

        //2nd Approach
        Observable.from (generateFibonacci (10))
                .filter (integer -> {
                    return integer < 15;
                });

        //3rd Approach
        Observable.from (generateFibonacci (10))
                .filter ((integer) -> integer < 15);

Subscribing Observable

Observables emit events and subscribers react to it. Both Observable and Subscriber/Observers are independent and they just agree to the contract. 


      Observable.from(generateFibonacci(10))

                .subscribe (System.out::println);



        //Or a more detailed and formal subscriber which gives all 3 event handlers!



        Observable.from (generateFibonacci (10))

                .subscribe(new Subscriber<Integer> () {
                    @Override
                    public void onNext(Integer s) { System.out.println(s); }

                    @Override
                    public void onCompleted() { System.out.println("Completed!"); }

                    @Override
                    public void onError(Throwable e) { System.out.println("Ouch!"); }
                });


--happy Rx !!!

Thursday, January 26, 2017

Reactive Programming through RxJava

Rx was originally developed as Reactive Extension for C#. Later, Netflix ported it for JVM platform under Apache license, named as RxJava!

RxJava is also an extension of Observer Design Pattern.This post, I will be focusing mostly on the fundamentals and constructs of RxJava.

Rx Building Blocks

The two fundamental constructs of Rx are Observables and Subscribers. Observables abstract event stream and emit them asynchronously to the subscibers (or observers).  There could be zero or more events and it terminates either by successfully completing or ending to an error. Streams can be created out of anything- list of integers, user clicks in UI, DB queries, tweeter feeds and what not. It's up to you, you can convert any sequence of data, input, function etc into a stream. And on top of streams, we have the functional toolkit to filter, modify, combine, merge these events/streams. We can merge two streams to form a single stream, map values from one stream to another. Below image shows the UI click represented as events. An instance of Subscription represents the connection between Observables and Subscribers. 



Observables: rx.Observable<T>

Observable is the first core component of Rx. Let's see what are ways through which observables can be created-

//1
List<Integer> list = Arrays.asList (1,2,3,4 );
Observable<List<Integer>> listObservable = Observable.just (list);

//2

Observable.from(Arrays.asList(1,2,3)); 
//from can take an Array, Iterable and Future

//3

Callable<String> call = () -> function1();
Observable.fromCallable(call)

Observable.fromCallable(()-> {throw new RuntimeException("some error")}); 




The observable class provides method- subscribe which will be used to push values to the observers. The subscriber is basically an implementation of Observer interface. Observable pushes three kinds of events as shown below as part of Observer interface. 

Observer
Provides a mechanism for receiving push-based notification. This interface provides three methods which will get called accordingly.

public Interface Observer<T>{
      void onCompleted();  
      void onError(Throwable e);
     void onNext(T t);
}

onCompleted() notifies the observer that observable has finished sending events.
onError() notifies the observer that observable has encountered an error / unhandled exception.
onNext() provides the subscribed observer with the new item/event.

Usually, in the code, you will not be able to explicitly notice Observers and those three callback methods; thanks to lambda and some other shorthands. To subscribe to an Observable, it's not necessary to provide an instance of Observer at all. Also, it's not always necessary to provide an implementation of onNext, onCompleted and onError; you could just provide a subset of them.


Consuming Observables (i.e. Subscribing)

Consuming Observables basically means Subscribing to them. Only when you subscribe, you can receive events abstracted by observable. 

Observable
                .just(1, 2, 3)
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        System.out.println("Completed Observable.");
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        System.err.println("Whoops: " + throwable.getMessage());
                    }

                    @Override
                    public void onNext(Integer integer) {
                        System.out.println("Got: " + integer);
                    }
                });

Output

Got: 1
Got: 2
Got: 3

Completed Observable.

A well-formed Observable will call onNext 0 or more times and then will call either onError or onNext exactly once. 


Now let's simulate through an example; how observable can throw an Error.


Observable
                .just(1, 2, 3)
                .doOnNext(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        if (integer.equals(2)) {
                            throw new RuntimeException("I don't like 2");
                        }
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        System.out.println("Completed Observable.");
                    }

                    @Override

                    public void onError(Throwable throwable) {
                        System.err.println("Oops: " + throwable.getMessage());
                    }

                    @Override

                    public void onNext(Integer integer) {
                        System.out.println("Got: " + integer);
                    }
                });


Output

Got: 1
Oops: I don't like 2

The first value gets through without any obstacle, but the second value throws an exception and then terminates the Observable. This will get confirmed if you run above snippet.

We don't need to always implement full subscriber every time. 
        Observable
                .just(1, 2, 3)
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        System.out.println("Got: " + integer);
                    }
                });

    
In this case, if error happens it will come on your face as there is no handler for that. It's best to always implement error handler right from the beginning.


Note: 
RxJava is single threaded by default.
To understand different operations visually: http://rxmarbles.com/

References:

http://reactivex.io/tutorials.html
https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
http://docs.couchbase.com/developer/java-2.0/observables.html
http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/



Saturday, January 21, 2017

Function as First Class Citizens in Java

Java (in version 8) added support for treating functions as first-class citizens. Before this, Java programmers had to wrap standalone functions with Runnables or other anonymous interface implementation class to be able to refer to them. 

Function as first-class citizen/type/object/entity/value:
Functions can be passed around like any other value!

What this basically means is that-

  •  functions can be passed as arguments to other functions, 
  • functions can be returned as values from other functions, 
  • functions can be assigned to variables 
  • functions can be stored in data structures. 

Before Java 8, Objects and primitives data types were treated as first-class citizens (Classes and Functions were treated as second class as they were not values). But, functions are just as valuable to manipulate and reuse. Java inherited this modern feature from other functional programming languages (like JavaScript, Scala). This will help in improving productivity as programmers now can code at the different level of abstraction. 

Read more in detail about what is first class, here


Lambda expression enables you to provide an implementation of the functional interfaces (which has only one method ) directly inline and they treat the whole expression as an instance of the functional interface. Below, we will see how lambda enables functional interfaces to be treated as first-class objects.


Function As Value

java.util.function package (ref) provides multipurpose functional interfaces which come in handy.


import java.util.function.BiFunction;
import java.util.function.Predicate;

/**
 * Creates Inline lambda functions and stores as variable. And then function can be called directly from variable.
 */
public class FunctionAsValue {
    public static void main(String[] args){
        Predicate<String> predicate = (s) -> s!=null || !s.isEmpty ();
        System.out.println(predicate.test ("geekrai"));

        //static method which confirms to Predicate method signature can be stored in invoked
        Predicate<String> pedicateRef = FunctionAsValue::isNotEmpty;
        System.out.println(pedicateRef.test ("geekrai"));

        //BiFunction accepts two arguments and produces a result
        BiFunction<String, String, String> concat = (s, t) -> s+t;
        System.out.println(concat.apply ("hello", " world"));
    }

    private static boolean isNotEmpty(String s){
        return s!=null || !s.isEmpty ();
    }
}


Output:

true
true
hello world


Function As Parameter




import java.util.function.Function;

/**
 * Illustrates how to pass function as parameter
 */
public class FunctionAsParam {
    public static void main(String[] args){
        //pass function as parameter to transform method
        System.out.println(transform ("geek", "Rai", s -> s.toUpperCase ()));

        Function<String, String> toLower = s -> s.toLowerCase ();

        System.out.println(transform("geek", "Rai", toLower));
    }

    private static String transform(String a, String b, Function<String,String> toUpper){
        if(toUpper != null){
            a = toUpper.apply (a);
            b = toUpper.apply (b);
        }
        return a + b;
    }
}

Output:
GEEKRAI
geekrai

--happy functional programming !!!


Friday, January 6, 2017

Pure Functions

This post discusses one of the important aspects of functional programming, Pure Function using Java example.

Pure functions are side-effect free functions or stateless functions. The output of pure functions depends purely (or completely) on input. What side-effect free basically means is that pure functions should not modify argument as well as any other state variables. 

Now, the obvious question is why is it so important. We will see later how it's one of the important ingredients for functional and Reactive programming. Let take a simple Java class to understand pure functions.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package functional;

import java.util.Random;

public class PureFunction {
 private int state = 420;

 // pure function
 public int addTwo(int x) {
  return x + 2;
 }

 // Impure function
 public int addState(int x) {
  return x + state;
 }

 // Impure Function
 public int randomizeArgument(int x) {
  Random r = new Random(1000);
  return x + r.nextInt(1000);
 }
}

Method, addTwo purely depends on its input/argument. No matter how many times you call it, it will behave in a predictable manner (i.e just add 2 to the argument and return the added number as the response). While the response of the other two methods (addState and randomizeArgument) is not going to be consistent even if it's called with same argument multiple times. The response of method addState depends on the instance variable of the class. If it gets mutated somewhere else, the response of the method will not be consistent. Similarly, the randomizedArgument method response will vary depending on the random value.

Let's cover some of the important points

  • If a pure function references any instance variable of the class, then that instance variable should be declared as final.
  • Pure functions help in highly concurrent and scalable environment by making the behavior predictable. 
  • You get parallelism free of cost if your method doesn't access a shared mutable data to perform its job. 

--happy learning !!!


Wednesday, July 20, 2016

Gradle - Create Java Project Structure

Gradle Init plugin can be used to bootstrap the process of creating a new Java, Groovy or Scala project. This plugin needs to be applied to a project before it can be used. So if we want to create default directory structure of a Java project this plugin can be handy (Especially if you don't have Gradle plugin in your IDE).

$gradle init --type java-library

The init plugin supports multiple types (it's 'java-library' in above command). Below are the command sequence and directory which gets created after successful execution.


$ mkdir hello-gradle
$ cd hello-gradle/
$ gradle init --type java-library
:wrapper
:init

BUILD SUCCESSFUL


Total time: 8.766 secs

$ ls -ltr
total 20
drwxrwxr-x. 3 vagrant vagrant   20 Jul 20 06:00 gradle
-rwxrwxr-x. 1 vagrant vagrant 5080 Jul 20 06:00 gradlew
-rw-rw-r--. 1 vagrant vagrant 2404 Jul 20 06:00 gradlew.bat
-rw-rw-r--. 1 vagrant vagrant  643 Jul 20 06:00 settings.gradle
-rw-rw-r--. 1 vagrant vagrant 1212 Jul 20 06:00 build.gradle
drwxrwxr-x. 4 vagrant vagrant   28 Jul 20 06:00 src
-- 

So above command also installs the other Gradle dependencies to run the build (i.e. gradl, gradlew.bat). If you don't know what the appropriate type for your project, specify any value then it will list valid types.

$ gradle init --type something

Execution failed for task ':init'.
> The requested build setup type 'something' is not supported. Supported types: 'basic', 'groovy-library', 'java-library', 'pom', 'scala-library'.
--

So, if you just type any random text as type; Gradle tells the allowed types.

If you just use $gradle init , then gradle tries (it's best) to automatically detect the type. If it fails to identify the type, then applies basic type. 

Importing Gradle Project to Eclipse

Note that, above command created gradle specific files along with default java directories (like src) but it didn't create eclipse specific files. This means, if you try to import above created project in eclipse it will not work. To achieve that, do below:
  1. Add eclipse plugin in gradle build file (i.e. build.gradle).  Put below after java plugin. 
          apply plugin: 'eclipse'
  1. Run $gradle eclipse

This basically creates files - .classpath, .project and .settings

Now, you are good to import above project in eclipse.

Alternatively, you can clone from my GitHub repository


---
Happy coding !!!


Friday, January 22, 2016

Concurrency or Thread Model of Java

Thread Model in Java is built around shared memory and Locking!

Concurrency basically means two or more tasks happen in parallel and they compete to access a resource.  In the object-oriented world, the resource would be an object which could abstract a database, file, socket, network connection etc. In the concurrent environment, multiple threads try to get hold of the same resource. Locks are used to ensuring consistency in case there is a possibility of concurrent execution of a piece of code. Let's cover these aspects briefly:

Concurrent Execution is about

  1. Mutual Exclusion or Mutex
  2. Memory Consistency or Visibility of change

Mutual Exclusion
Mutual exclusion ensures that at a given point of time only one thread can modify a resource.  If you write an algorithm which guarantees that a given resource can be modified by (only) one thread then mutual exclusion is not required.  


Visibility of Change
This is about propagating changes to all threads. If a thread modifies the value of a resource and then (right after that) another thread wants to read the same then the thread model should ensure that read thread/task gets the updated value. 

The most costly operation in a concurrent environment contends write access. Write access to a resource, by multiple threads, requires expensive and complex coordination. Both read as well as write requires that all changes are made visible to other threads. 


Locks

Locks provide mutual exclusion and ensure that visibility of change is guaranteed (Java implements locks using the synchronized keyword which can be applied on a code block or method).

Read about the cost of locks, here

Wednesday, January 20, 2016

Preventing logging overhead in Log4J

Have you seen something like below in your application, and ever wondered about the overhead (due to the if condition). This post covers ways to get rid of the overhead with Log4j 2.x and Java 8.

if(log.isDebugEnabled()){
   log.debug("Person="+ person);
}

Above style is quite common in log4j-1.x; though it adds few extra lines it improves the performance.


Below log calls toString method on the person even if it's not going to get logged.
log.debug(person);  //big NO; avoid this !

So how do we remove the overhead of if check

The if condition is an overhead and it's going to appear multiple places in method/class. Also, if you don't do logging judiciously then it can be spread all over.

log4j 2.x
log4j 2.x is out there after a long gap and this particular issue has been addressed. Inspired by SLF4J it has added parameterized logging.

log.debug("{}"+person); //will not call .toString method on person
log.debug("{}"+person.toString());   //this is still going to be an issue

So log4j 2.x parameterized logging mechanism will not call implicit (toString) method on the person, but if you call it explicitly then it will make the call. So log4j 2 has partially addressed the problem.

log4j 2.4 + Java 8 lambda
log4j 2.4 supports lambda based mechanism which solves the problem completely. So it doesn't call the method (implicit or explicit) at all if the statement being logged is at the level less specific than the current level.

log.debug(() -> person.toString());   //all good 
log.debug("{}"+ this::expensiveOperation());   //all good

Final Note:
Be mindful of logging overhead when you do code review!


References
https://logging.apache.org/log4j/2.0/manual/api.html
http://marxsoftware.blogspot.pt/2015/10/log4j2-non-logging-performance.html
http://www.jroller.com/bantunes/entry/java_lazy_logging_features_ways
http://www.infoq.com/news/2014/07/apache-log4j2
http://www.grobmeier.de/log4j-2-performance-close-to-insane-20072013.html

Saturday, January 16, 2016

Extracting root cause from Stack Trace

Don't tell me the problem; show me the logs first!

Whether you are a fresh graduate, an experienced programmer, QA engineer, production engineer or even a product manager - a good understanding of stack trace is vital to crack critical issues. Your ability to find the real culprit from a lengthy stack trace will be instrumental in resolving a problem. This is even more important if you work on a distributed system where you use many libraries so stack trace is not well structured. Let's start with a simple scenario-

Scenario 1: Simple

This is the most trivial case, where the exception gets thrown by a method of your project and during the call duration, it doesn't go out of your code base. This is the most trivial scenario which you will encounter but very important to understand how the stack trace gets printed.

Shown below is Eclipse screenshot of MyController.java which two classes. Right click and run the program. 

Let's Decode Above stack trace:
  • RuntimeException is shown in line number 29, in method MyService.four()
  • Method MyService.four() gets called by MyService.three() in line number 25
  • Method MyService.three() gets called by MyController.two() in line 11
  • Method MyController.two() gets called by MyController.one() in line 6
  • Method MyController.one() gets called by MyController.main() in line 17


First frame of stack trace holds all important information required to know the root cause. 
Be mindful of the very important line number 

Scenario 2: Chain Of Exception

Let's modify above code a bit by catching exception at the origin and then throwing a brand new Exception. 


Let's Decode Above stack trace:

This stack trace has a caused by section. It has only one caused by but in real applications you can have multiple caused by sections. The last caused by will have the root cause of the exception.


Caused by: java.lang.RuntimeException: here, comes the exception!
at MyService.four(MyController.java:30)


... 4 more


But, if you are using external jars or libraries, finding the root cause could be bit tricky as the real reason might be nested deep inside. In such case you should look for Class.method name which belongs to your application. Also, you should look the complete stack trace carefully as the real root cause could lie in any part of stack trace. 


References:
http://www.nurkiewicz.com/2011/09/logging-exceptions-root-cause-first.html
http://stackoverflow.com/questions/12688068/how-to-read-and-understand-the-java-stack-trace
http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors


Saturday, July 25, 2015

Insertion Sort

Insertion sort is one of the most fundamental comparison based stable sorting algorithm. It is also known as playing card sort. It is based on a fundamental principle that a single element array is already sorted.  A two element array requires single comparison to sort it. A three element array can be visualized as two sub arrays (first with 2 elements and second with one element). So in each iteration, a new value is added to an already sorted sublist. 

a1 = {101}   // already sorted
a2 = {101, 2} // can visualize it as, add 2 to a already sorted sub-array having 101
       {2, 101} // one comparison required to put 2 in proper place
a3 = {101, 2, 5} // a new number added to a2
        {2, 101, 5}
        {2, 5, 101}  // put 5 in proper place

To visualize how it works, check out animation on wikipedia.

Java Implementation


/**
 * Insertion sort implementation
 * 
 * @author Siddheshwar
 *
 */
public class InsertionSort {
 /**
  * Insertion sort in ascending order
  * 
  * @param arr
  * @return arr
  */
 public int[] sort(int[] arr) {
  int tmp = 0;
  for (int i = 1; i < arr.length; i++) {
   for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
    tmp = arr[j];
    arr[j] = arr[j - 1];
    arr[j - 1] = tmp;
   }
   print(arr);
  }
  return arr;
 }

 // print current state of array
 private void print(int[] arr) {
  System.out.println();
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + "  ");
  }
 }

 public static void main(String[] args) {
  int[] arr = { 12, 11, 13, 5, 6 };
  InsertionSort is = new InsertionSort();
  arr = is.sort(arr);
  // is.print(arr);
 }
}

Output:
11  12  13  5  6  
11  12  13  5  6  
5  11  12  13  6  
5  6  11  12  13 

Performs ideal when array is nearly sorted or size is small. It can also be used as base sorting algorithm in recursive divide and conquer quick sort and merge sort algorithms.

Important Points

  • If the array is already sorted, swapping will never be performed and hence time complexity will be O(n). Adaptive sorting algorithm. 
  • Average and worst case time complexity is O(n^2). Space complexity is O(1)
  • Worst performance when array is reverse sorted. 
  • Not ideal approach if data is random.
  • In the best case (when already sorted), all the elements are in proper place so it takes linear time. 
  • In-efficient for value based data with large memory footprint as amount of memory shift/swap will be high. Performs good when sorting on pointer based data. 
keep coding !

Saturday, July 4, 2015

Invoking Java class through Ant

Ant is a powerful tool which can run Java programs as well as part of your build process. This might be helpful in running a utility class during the build. It can also be handy to do smoke testing by running some of the test classes during the build. Literary you can perform any operation during the build if you are able to call a Java class.

This post, I will discuss creating a dedicated target to run a Java class.

Create Java Project

Let's create a sample Java project with a single class file with the main method so that it can be invoked from an external tool (i.e. Ant).




/**
 * Sample Java class
 * @author Siddheshwar
 *
 */
public class RunMe{
 public static void main(String[] args){
     System.out.println("Inside main method of RunMe");
            if(args.length !=0 ){
              System.out.println("you passed argument="+args[0]);
            }  
       }
} 

build.xml

<?xml version="1.0"?>
<project name="AntSample" default="compile">
 <!--Declare common properties  -->
 <property name="src.dir"     value="src"/>
 <property name="build.dir"   value="build"/>
 <property name="RunMe-class"  value="RunMe"/>
 <property name="classes.dir" value="${build.dir}/classes"/>

 <!-- init target to clean up existing build directory -->
 <target name="clean">
  <delete dir="${build.dir}"/>
 </target>

 <!--Before running a Java class; that class should be compiled   -->
 <target name="compile" depends="clean">
  <echo>compilation started -</echo>
  <mkdir dir="${classes.dir}"/>
  <javac srcdir="src" destdir="build/classes" />
  <echo>compilation complete!</echo>
 </target>

 <!--Execute the java class   -->
 <target name="execute" depends="compile">
  <java classname="RunMe" classpath="build/classes">
   <arg value="hello" />
   <arg file="." />
  </java>
 </target>

 <!-- abstracts clean and execute target -->
 <target name="main" depends="clean,execute"/>
</project>


Executing Java class

In build.xml file execute target is declared to run the Java class. Before running the class it should have been compiled and that's the reason for adding dependency on compile target. This way when we run execute target, it will run compile first. Target, execute provides all information required for running a program. It provides name of the class (i.e. className) as well as path of class through classpath. It also passes an argument to the main method having value hello. 
The last argument file, tells Ant to resolve that attribute to an absolute file location. 

That's it; you are done!

Now let's run the class: 
I have given below multiple options for running the Java program (Ant Cheat Sheet), you can call any of them:

$ant execute
or
$ant main
or
$ant compile execute
or
$ant clean compile execute

Response

$ant main
Buildfile: /Users/siddheshwar/Documents/gitRepo/AntSample/build.xml

clean:
   [delete] Deleting directory /Users/siddheshwar/Documents/gitRepo/AntSample/build

compile:
     [echo] compilation started -
    [mkdir] Created dir: /Users/siddheshwar/Documents/gitRepo/AntSample/build/classes
    [javac] /Users/siddheshwar/Documents/gitRepo/AntSample/build.xml:18: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 1 source file to /Users/siddheshwar/Documents/gitRepo/AntSample/build/classes
     [echo] compilation complete!

execute:
     [java] Inside main method of RunMe
     [java] you passed argument=hello

main:

BUILD SUCCESSFUL
Total time: 0 seconds

--

Keep coding!