Page 164

Optimization 41: Lock Fusion In the previous optimization we lobbied in favor of splitting two unrelated updates under the protection of two independent lock objects. On the other extreme, if two shared resources are related to one another and their updates seem to happen in tandem, it does make sense to fuse those two updates under the protection of a single object lock. Let’s continue along the lines of a Web-server implementation. Suppose that the server not only records the number of HTTP and SSL requests, but also the number of bytes served for each protocol. The class keeping track of those statistics is HTStats: class HTStats { private static int httpReqs; // Number of requests. private static Object lockHttpReqs = new Object(); private static int httpBytes; // Number of bytes served. private static Object lockHttpBytes = new Object(); … public static void updateHttpStats(int bytes) { addHttpReq(); addHttpBytes(bytes); } public static void addHttpReq() { synchronized (lockHttpReqs) { httpReqs++; // Increment the counter for HTTP requests. } } public static void addHttpBytes(int bytes) { synchronized (lockHttpBytes) { httpBytes += bytes; // Increment the counter for HTTP bytes. } } }; As is stands, the methods for updating the HTTP requests and byte counters are using distinct objects to provide synchronization. The updateHttpStats(), however, always updates those two counters together. It seems to make more sense to fuse those two counters under the same synchronized block. That’s the theoretical solution. Let’s see what happens in practice. We develop a test case that closely mimics the above scenario. The scaffolding of the test is pretty much the same as previous tests: We launch a few threads, give them something to do and measure it: class MtFusion { public static void main(String args[]) { try { if(args.length != 2) { System.out.println(”Usage java MtFusion “); return; } int count = Integer.parseInt(args[0]); int numThreads = Integer.parseInt(args[1]); WorkerThread mc[] = new WorkerThread[numThreads]; for(int i = 0; i < numThreads; i++) { Page 165
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check Actions tomcat hosting services

Comments are closed.