//$Id$
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadSafe {
public static final Logger LOGGER = Logger.getLogger(ThreadSafe.class.getName());
public static int random(int num){
LOGGER.log(Level.INFO,"Entered Num : {0}",num);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
LOGGER.log(Level.INFO,"Interrupted Exception");
}
return num + 2;
}
public static void main(String[] args){
for(int threads=1;threads<100;threads++){
final int number = threads;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int val = ThreadSafe.random(number);
System.out.println("Excepted Value = " + (number+2) + " Returned Value = " + val);
}
},"Thread : "+threads);
thread.start();
}
}
}
Output:
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 2
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 45
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 44
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 43
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 42
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 38
Excepted Value = 47 Returned Value = 47
30 Jan, 2013 11:41:26 PM com.zoho.learn.test.ThreadSafe random
INFO: Entered Num : 41
Excepted Value = 44 Returned Value = 44
Excepted Value = 46 Returned Value = 46
I am excepting multi threads accessing a same method at same time. What happens if we access a static methods at same time?
When race condition occurs?
What is shared-state?
Please correct me If I am wrong.
The only piece of code (except
run()) executed concurrently is:Stripping logging (which is thread-safe in every sane implementation), sleeping (which only affects current thread) and exception handling, this is what you are left with:
Not only
numargument is private to each thread (each thread has its own stack memory), but also it’s never modified. Thus, race condition cannot occur in your program.There is no shared state (global variables) in your code, race condition is only possible when one thread modifies shared data while other reads it.
You want to see a race condition? Here you go!
Last seconds from disaster:
Thread 1 enters
random(42), assigningglobalNum = 42and goes to sleepThread 2 enters
random(17), assigningglobalNum = 17and goes to sleepThread 1 wakes up reads current value of
globalNum(which is17) and returns19instead of44as expected.See also