Friday, September 28, 2007

Synchronization - Wait a min.

Somewhere platform independence of Java fails when it all comes on Threading. Not a fault of Java because Threading means lot of dependency on system. How a particular OS is going to handling with your thread. Like if we see Windows NT, it doesn't support priorities of thread like priorities of Process, whereas Unix based system gives you the freedom to prioritize both thread and process.
Anyway, I am writing this article to just say that take care whenever you are writing any synchronized call. Every synchronized block or a method has an overhead and we can't ignore it. So before going to synchronization there is something called atomicity which means atomic operation like int a =2; luckily we never have to worry of threading issue in atomic calls. Its all thread safe. Again, take care x++ or x+=y is not falling under this atomic operation because there are two things going-increment and assignment.

Now, see the code here and also overhead of sync. call, which is of no use here:

import java.util.Date;

class ThreadCheck {

synchronized float uselss(int a, int b, int c)
{
return (a+b+(c/2));
}

float useful(int a, int b, int c)
{
return (a+b+(c/2));
}

public static void main(String[] args)
{
ThreadCheck threadcheck = new ThreadCheck();

//lets check the time
double begin = new Date().getTime();
for(int i=0;i<50000;i++)
{
threadcheck.uselss(4,3,2);
}
double end = new Date().getTime();
System.out.println("Time taken by Sync. call: " + (end-begin));

begin = new Date().getTime();
for(int i=0;i<50000;i++)
{
threadcheck.useful(4,3,2);
}
end = new Date().getTime();
System.out.println("Time taken by non-Sync. call: " + (end-begin));
}
}

This is the output I am getting:

E:\Program Files\Java\jdk1.6.0\bin>java ThreadCheck
Time taken by Sync. call: 16.0
Time taken by non-Sync. call: 0.0

One can clearly see a big overhead here. So the idea is just to take care while writing sync. block because threading is more in demand when we write real time systems and in RTS we can't afford such a wastage of time :).

No comments: