The Cost of Synchronization Multithreaded programming is a

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

Comments are closed.