Category Archives: Java

Reverse a Link List

private static Node reverseList(Node head){
Node temp=null;
Node temp2=null;
//Initial state- set temp pointer at head->next
if(head.next!=null)temp=head.next;
//Set head.next null as this will eventually become last node
head.next=null;
while(temp!=null)
{
//Temporary pointer 2 to be placeholder of temp.next
temp2=temp.next;
temp.next=head;
head=temp;
temp=temp2;
}
return head;
}

Synchronization: Object vs Class level

In my last post I wrote about how synchronization can help making sure that multiple threads do not execute same block of code at the same time. I will take the concept of synchronization a little further here. Going back to previous example.

public void test()
{
 synchronized(this){
  try {
   count++;
   Thread.sleep(1000);
   System.out.println(“Hello from Runnable:”+count);
   } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

synchronized(this) or using synchronized keyword at method level makes sure that no 2 threads execute the block of code at the same time. But there is a bit more to it. To elaborate, I have modified my test method slightly

public void test()
{
 synchronized(this){
  try {
   count++;
   Thread.sleep(1000);
   System.out.println(Thread.currentThread().getName()+" says Hello from  R unnable:"+count); 
   } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

And modified calling main method

public static void main(String s[])
{
Runnable r=new RunnableTest();
Runnable r2=new RunnableTest();
for(int i=0;i<20;i++)
{
Thread t1=new Thread(r);
t1.setName("1");
t1.start();
Thread t2=new Thread(r2);
  t2.start();
  t2.setName("2");
 }
}

Now if I run this we will see something like

2 says Hello from Runnable:1
1 says Hello from Runnable:1
1 says Hello from Runnable:2
2 says Hello from Runnable:2
1 says Hello from Runnable:3
2 says Hello from Runnable:3

And if you will observe the output, it is appearing in pairs. So let us understand what is happening here.

First change, instead of one object of runnable we are using 2 objects, this is to basically highlight the behavior in synchronized(this) block. Second change is that I added name for thread so that we can print it out to understand which thread is actually executing.

Coming back to synchronized(this), look at the “this” keyword. “this” in Java refers to current object. So when we synchronize on this, it means we are synchronizing on current object, so as we are using two different objects, hence we see the behavior that two stream of threads is executing simultaneously in synchronized block. So we can say that with synchronized this, we make sure only one thread of the object is executing in synchronized block at a time.

Now there can be a situation where you want exactly one thread for whole class gets executed at a time, no matter if thread belongs to same object or not. There is a simple solution to it.

public void test()
{
 synchronized(RunnableTest.class){ //Change this with class name
  try {
   count++;
   Thread.sleep(1000);
   System.out.println(Thread.currentThread().getName()+" says Hello from  Runnable:"+count);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

There are other options for synchronization as well, not of much practical use (atleast I have not used them ever), but worth noting.

synchronized("1")

Remember, string is an object. So we are synchronizing based on a constant object here, which will make sure only one thread executes at a time, irrespective of class or objects. So for our example this will be same as synchronized(RunnableTest.class).

A more practical use can when we are trying to synchronizing a group of thread.

String key=Thread.currentThread().getName();
public void test()
{
 synchronized(key){
  try {
   count++;
   Thread.sleep(1000);
   System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

Here I am using key to group threads based on which synchronization is done. The key here is simply name of thread, but it can be more realistic in real scenario.

Handling Multithreading with Synchronization

In last post I wrote about how can we speed up our processing using multiple threads in Java, basically doing parallel processing using threads. Using multithreading definitely helps speed up processing, but it can also result in corrupting data if not used properly. Let’s look at this example

//A simple Runnable class
public class RunnableTest implements Runnable{
 int count=0;
 public void test()
 {
  try {
   count++;
   Thread.sleep(1000); //This will just introduce some delay
   System.out.println("Hello from Runnable:"+count);
   } catch (Exception e) {
    e.printStackTrace();
  }
 }

@Override
public void run() {
test();
}
}

//and call it from somewhere like
Runnable r=new RunnableTest();
for(int i=0;i<20;i++)
{
Thread t1=new Thread(r);
t1.start();
}

Output:
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
Hello from Runnable:20
..
..

We are calling run method 20 times which in turn calls test. We have deliberately introduced some delay in test to give it a feel of real method which is taking time to execute some statements. The output depicts that instead of count being printed as 1, 2, 3 and so on, it is 20 for all the calls. Which means that all the threads are trying to execute same block of code simultaneously. Though parallel processing of code is desirable behavior from multithreading, it can cause issues in scenarios mentioned above.

Let’s say in actual code we are trying to write data into a database. Instead of count we have ID. So first thread creates and ID as X. Then it does some processing and creates an insert statement. While it is doing the processing, a second thread starts executing the same code and creates another ID Y which overrides the ID X (same as count is being modified). So when our thread 1 reaches to the code where it is inserting the data, it will try inserting ID as Y (as X is overridden by Y). Then thread 2 comes and again try to insert ID Y, causing an error.

So in real world we can have blocks of code (or complete methods) which we want to make sure does not get executed by multiple threads at the same time. Fortunately Java provides a simple way to do this. The keyword is synchronized.

public void test()
{
 synchronized(this){
  try {
count++;
Thread.sleep(1000);
System.out.println("Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Now if we run the same code, we will get

Hello from Runnable:1
Hello from Runnable:2
Hello from Runnable:3
Hello from Runnable:4
Hello from Runnable:5
Hello from Runnable:6

Synchronized block makes sure that only one thread is executing blocked code at a time. Another way to synchronize is define method itself as synchronized.

public synchronized void test()

This will make sure only one thread enters this method at a time.

Multithreading: Runnable vs Thread

What is multithreading? First of all let us understand what is thread? A thread is simply flow of control in a program/ process.

Now Let’s understand what is multithreading? Let’s take an example, there is a code which reads data from a file and uploads it to a database. Let’s say there are 10 such files and each file takes 1 hr to finish data upload. In a single threaded environment, it will simply translate to 10 hrs job as our code will read and upload files one by one.  Whereas when we move to multithreading, that is multiple threads are executing at the same time asynchronously, it will result in parallel processing of these files and the total time taken might be close to time taken by one file only.

Before getting into details lets understand how to implement multithreading in Java? There are 2 ways to achieve this.

//1. Extend Thread class
public class ThreadTest extends Thread{
 public void test()
 {
  System.out.println("Hello from Thread");
 }
 public void run()
 {
  test();
 }
}
 //2. Implement Runnable interface 
public class RunnableTest implements Runnable{
 public void test()
 {
  System.out.println("Hello from Runnable");
 }
@Override
 public void run() {
  test();
 }
}

//And somewhere in the main method 
public static void main(String s[])
{
 Thread t1=new ThreadTest();
 t1.start();
 Thread t2=new Thread(new RunnableTest());
 t2.start();
}

As you can see the important method while using threads is “run”. This method gets called automatically by JVM whenever a thread starts.

Note that we do not call the run method directly, as that will be like calling a normal method and will wait for control to come back to calling class. Whereas using start will make sure the control flow continues without waiting for method call return. To understand what I am referring here, lets change the main method slightly

for(int i=0;i<20;i++)
{
 Thread t1=new ThreadTest();
 t1.start();
 Thread t2=new Thread(new RunnableTest());
 t2.start();
}

We will something like (no order)

Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable
Hello from Runnable
Hello from Thread
Hello from Thread
Hello from Thread
Hello from Runnable
Hello from Runnable

Now let’s change it to run

for(int i=0;i<20;i++)
{
 Thread t1=new ThreadTest();
 t1.run();
 Thread t2=new Thread(new RunnableTest());
 t2.run();
}

Output

Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable
Hello from Thread
Hello from Runnable

So not actually using multithreading here.

Coming back to original example. Now you can see if we write the code for uploading the data from file to run method, and execute it in multithreaded fashion, we will be able to upload files simultaneously.

We have seen 2 ways to create threads in Java, one by extending thread class and other by implementing runnable. Which is better?

Usually we go for implementing runnable. When implementing runnable we can only override run method, and that is the only thing which we need in most of the cases. Whereas when we extent Thread, we can override other methods like start, sleep, stop etc, which is usually not required. Additionally, extending Thread has the obvious implementation that now our class cannot extend any other class (as Java allows only one class to be extended).

Error using Maven with Eclipse Kepler

When I tried using Maven’s embedded version in Eclipse Kepler, it gave an error.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".

A little googling showed this as a genuine issue with embedded version of Maven in Eclipse. The workaround is to download external maven and link to eclipse.

For windows.

  1. Download Maven zip from http://maven.apache.org/download.cgi
  2. Unzip the file to some location say “D:\Maven”
  3. In Eclipse go to Windows->Preferences->Maven->Installation; Click add and provide the path in step 2 (D:\Maven)

Related http://stackoverflow.com/questions/11916706/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder-error

What is Middleware?

If you look around for the term Middleware, you will see it being used widely but unfortunately not explained properly anywhere. What is middleware? If you are working on simple web applications, the possibility is that you have mostly worked on client-server paradigm without worrying about middleware concepts. Middleware genrally comes into picture when we are dealing with multiple(atleast 2) applications. It helps these applications talk to each other, even if these applications are on different platforms, technologies and servers.

How does Middleware do it? Lets take a simple example. We have a college A, which has an inhouse application (colA app), used to track students data, attendence, results etc. Now there is an internet application which is supposed to display results of students online (result.com). Now result.com app needs to communicate to colA app to fetch student result data. We introduce a middleware application which helps these 2 app communicate. Let’s say this is message oriented middleware, so as soon as a new result is available on colA app, it writes it on a queue of middleware app. Now middleware might do some processing on the data if required and add it to another queue, which is listened to by result app.

Why can’t result app directly talk to colA app? It can, but what will happen if complexity increases and we introduce many new applications into the arena. Say we have hundereds of colleges and tens of result apps. And to complicate it further, college apps also need to communicate to each other. Just imagine the comexity that each app is listening to tens of other apps and fetching data from tens of apps. Each app need to worry about security, concurrency, connectivity, handling so much load. Different apps might be using different technologies to make the communication difficult. With introduction of middleware, we are moving all the complexity out of the apps so that they can focus on their core areas and let middleware worry about handling load, setting up clustors, managing security, dealing with different technologies and platforms.

Middleware

Weak Reference

A WeakReference object is same as an ordinary object but differs only when garbage collection comes into picture.

How does garbage collection work?

When JVM is running out of memory, it triggers garbage collection, i.e. a process which reclaims any space used by dead objects. Dead objects can be thought of the ones which are not referenced from anywhere.

Now coming back to WeakReferece, it is a reference which is ignored by GC process. That is, if an object is only referenced by a weak reference, it will still be removed (collected as garbage).

Let’s take an example to clarify the point (http://en.wikipedia.org/wiki/Weak_reference)

import java.lang.ref.WeakReference;

public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference(new String(“I’m here”))
WeakReference sr = new WeakReference(“I’m here”);
System.out.println(“before gc: r=” + r.get() + “, static=” + sr.get());
System.gc();
Thread.sleep(100);

// only r.get() becomes null
System.out.println(“after gc: r=” + r.get() + “, static=” + sr.get());

}
}

Output

before gc: r=I’m here, static=I’m here
after gc: r=null, static=I’m here

Practical usage:

When will I need to make an object as WeakReference?

In case there is some data which is good to have in memory but can be GCed if memory requirements occur. For example, say I have a list of Employees and each employee has address. The address details are not referenced as frequently as other details so I will mark the address as WeakReference object, as it can be re-fetched from database if required. And if JVM needs memory, it can reclaim the address space.

Interesting Java Facts 3: Cloning a multidimensional Array

Consider the following code

int arr[][]={{10,20,30},{23, 45, 67,}};
int clone[][]=arr.clone();
clone[0][0]=-1;

Q. What should be the value of arr[0][0] and clone [0][0]?

A. It is -1 for both. Why? Let understand 2 things- clone always make a shallow copy of object  & Array is an object in Java.

Shallow copy: When we clone an object in Java, it only creates duplicate copies of primitive types, and for objects, the reference is copied. For example if an Employee object containing an address object is cloned, for address only reference is copied, that is not bot employee and clone are referencing same address object and any change in address is reflected in both.

We can override the clone method for Employee to make sure whenever a clone is made a new object for Address is created as well and all the values are actually copied one by one to new object. This will make sure both the original object and clone are referencing to their own address and changes in one does not get reflected in other.

Array is an object: In java array is an object, so a multidimensional array is actually an object with multiple objects (arrays) in it.

Putting both the above concepts together, we can figure out that while cloning, only the references of array objects  in multidimensional array are copied to cloned object, that means any change in one will get reflected to another.

Java multiple Inheritance: Interfaces and Composition

Inheritance means a class extending other class. Multiple Inheritance means single class extending more than one class. Java does not support this kind of inheritance as one class can inherit only a single class.

Q. Why Java does not support multiple inheritance?

Consider a scenario, there are 2 classes

class A{

public void mymethod(){//some code

}

}

class B{

public void mymethod(){//some code

}

}

class C extends A,B{//illegal in Java

//which implementation of mymethod is imported ?

}

If java allow multiple inheritance, it will be tricky to handle above situation with multiple inheritance, hence Java does not allow it.

Q. How does Java implement Multiple inheritance?

Java does not provide direct implementation of multiple inheritance by extending more than one classes, but it provides you 2 alternatives.

1. Use of Interfaces: A Java class cannot extend more than one class, but it can implement any number of interfaces.

Class C implements A,B{ // this time A and B are interface

public void mymethod(){//interfaces did not provide implementation and hence no conflict

}

}

2. Composition: Other way to use properties of other classes is to use composition, that is have the object of other classes as part of current class.

Class C{//A and B are different classes

A objA=new A();

B objB=new B();

}

Best Approach: A mix of implementing interfaces, extending class and using composition, based on different requirements