Page 160

October 31, 2006 on 8:25 am | In Java |

Optimization 40: Synchronization False Sharing Every Java object and class has a single lock associated with it. If you synchronize on an object via a synchronized method or block, you are locking up the object. If two synchronized methods in the same object try to access completely unrelated resources, they will lock each other out. This is a case of false sharing, where two logically unrelated operations are forced to physically share the object’s lock. The same point applies to the class lock in the case of static shared resources. Take, for instance, a multithreaded Web server listening on both HTTP and HTTPS (otherwise known as SSL) ports. Most reasonable implementations of a Web server will make some rudimentary statistics available to the Webmaster. At the very least, they will keep track of the number of HTTP and HTTPS requests: class HTStats { private static int httpReqs; private static int sslReqs; … }; Since multiple threads may try to manipulate the statistics concurrently, such manipulations must be synchronized: public synchronized static void addHttpReq() { httpReqs++; // Increment the counter for HTTP requests. } public synchronized static void addSslReq() { sslReqs++; // incement the counter for HTTPS requests. } The HTStats class uses a single lock to protect the manipulation of all of its static counters. Fusing multiple unrelated shared resources under the umbrella of a single lock is normally a bad idea. It widens the scope of the synchronized regions and creates friction among otherwise independent threads. The only possible exception to this rule is when both of the following two conditions are satisfied: . All of the shared resources are always manipulated together. . None of the manipulations of the shared resources consume significant CPU cycles. In the case of counting HTTP and SSL requests, the second condition was satisfied (shared counters; updates are fast) but the first condition was broken: A thread that updated one counter did not access the other. An SSL thread might update the SSL counter but have no interest in the state of the HTTP counter. The preferred solution is to have two distinct locks protecting two unrelated counters so that the contention for each lock is reduced by half: class HTStats { private static int httpReqs; private static Object lockHttp = new Object(); private static int sslReqs; private static Object lockSsl = new Object(); … public static void addHttpReq() { synchronized (lockHttp) { httpReqs++; // Increment the counter for HTTP requests. Page 161
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

No Comments yet

TrackBack URI

Sorry, the comment form is closed at this time.