Web Hosting Java, JSP, Tomcat 6, J2EE, Servlets, Struts, Jboss
The Cost of Synchronization Multithreaded programming is a
October 31, 2006 on 2:30 am | In Java | The Cost of Synchronization Multithreaded programming is a tricky business and if you don’t watch your step you could get into trouble with race conditions, deadlock, starvation, and other landmines associated with concurrency. Defects resulting from race conditions are particularly difficult to debug. If concurrency is so delicate, why don’t we just synchronize everything and be done with it? From a performance standpoint, there are at least two good reasons why we should use synchronization very sparingly. First is the overhead of the synchronization mechanism itself. Somewhere, a lock must be acquired and released before and after the synchronized code. For instance, take the simple operation of integer increment. We will measure its speed with and without synchronization: class Counter { private long counter; private static long sharedCounter; public static void main(String args[]) { int n = Integer.parseInt(args[0]); Counter c = new Counter(); long start = System.currentTimeMillis(); // <+++ Start timing for (int i = 0; i < n; i++) { c.bumpCounter(); } long stop = System.currentTimeMillis(); // <+++ Stop timing System.out.println("Execution time = " + (stop - start)); } public void bumpCounter() { counter++; } public static synchronized void bumpSharedCounter() { sharedCounter++; } } We invoked this program using Java Counter 1000000 to execute one million iterations of the loop for (int i = 0; i < n; i++) { c.bumpCounter(); } where bumpCounter() is unsynchronized. We then replaced bumpCounter() with its synchronized counterpart bumpSharedCounter() for (int i = 0; i < n; i++) { c.bumpSharedCounter(); } The unsynchronized method ran almost two orders of magnitude faster than the synchronized one. Page 154
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services
No Comments yet
Sorry, the comment form is closed at this time.
...I
just wanted to take the time to say "Thank you!" for our new webmail
system. It's great! Thanks for taking such good care of us.
Thanks
for helping me out. Just for the record, Webhostingjava.net has been a great
web host! So far your support and handling of questions has far
exceeded that of a "larger web hosting company".
I
would like to thank you for helping me with my domain...You have
shown me great patience and professionalism. I would not hesitate to
recommend you to my clients.