Monday, March 5, 2007

TechiScoop Part I(Multithreading)

Multi Threading

What is thread?
It's a light process, has its own copy of stack, but shares global variables with the processs. One process can have one or many threads. What this means is, a thread will have copy of their own local variables but it will share the global and variables declared with static keyword.

Advantages
In multi-processor cpu, one can run multiple threads on more than one cpu simulteneously. So, improved performance for the application. Switching between thread is easier and faster than switching between processes. On a single processors, thread scheduling is done in such a way that, user gets feeling running things in parallel, actually, only one thread is running during a particular time slot.


Disadvantages
Unprotected access of shared data may lead to program crahses, deadlocks.

How to write thread safe programs?
Use locks to access shared variables. Java programmers can write synchronized methods or make use of synchronized blocks in their program to avoid race conditions.

Example

import java.util.HashMap;
import java.util.Map;

class MyCache {

protected static Map aCache=new HashMap();

public void Cache()
{
//do nothing
}

public synchronized Object getValue(String key)
{
return aCache.get(key);
}

public synchronized void setValue(String key, Object val)
{
aCache.put(key, val);
}
}

class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
String randstr[]={"Hello","motion","world","texas","india","cloud","tree","birds","ten","medal"};
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
MyCache c=new MyCache();
String key="key#"+i;
c.setValue(key, randstr[i]);
sleep((int)(Math.random() * 1000));
System.out.println(c.getValue(key));
}
catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}

public class ThreadExample {

public static void main(String[] args) {
SimpleThread s[]=new SimpleThread[5];
for(int i=0;i<5;i++) {
String threadid="Thread"+i;
s[i]=new SimpleThread(threadid);
s[i].start();
}
}
}

Sample output:

0 Thread0
0 Thread1
0 Thread2
0 Thread3
0 Thread4
Hello
1 Thread4
Hello
1 Thread2
motion
2 Thread2
Hello
1 Thread3
Hello
1 Thread0
Hello
1 Thread1
motion
2 Thread4
motion
...
DONE! Thread0
medal
DONE! Thread3
ten
9 Thread1
medal
DONE! Thread1


In the above example, the MyCache class has a static variable aCache. And its initialized along with its declaration(this make sures, only once its initialized). Now, the, two methodes get and set are synchronized, if they are not, then the output will generate NullPointerException. because, your program tries to access the shared cache simulteneously. Making the method synchronized resolved the problem of race-condition like this.

No comments: