Optimization 42: Code Motion Splitting a sequential task

October 31, 2006 on 3:10 pm | In Java |

Optimization 42: Code Motion Splitting a sequential task into parallel subtasks is just the first step. Beyond that we must structure our multithreaded code to allow the subtasks to execute independently and minimize friction among the threads executing those parallel subtasks. The most common friction among threads is the contention for shared resources. When a thread acquires exclusive access to a shared resource, all other threads that want access to that resource must wait. We therefore must speed up execution inside the synchronized blocks and methods and release shared resources as fast as possible. Code motion is often associated with loop optimization [BEN82]. A computation whose value is constant across loop iterations should not be performed inside a loop. It ought to be computed once before entering the loop. Similarly, the critical section should only contain critical computations. The critical computations are those that directly manipulate shared resources. All other computations ought to be performed outside the critical section. We discuss an example of code motion below. Imagine a multithreaded application that must log some data to a shared file (a Web server must log every request, for example). We will mimic such an application with the code below. The main program creates a number of parallel threads whose run() method attempts to log data to the shared file. The shared file itself is created and closed by the main program. An output stream reference is provided to the threads as a constructor argument: import java.io.*; class CodeMotion { public static void main(String args[]) { try { if(args.length != 2) { System.out.println(”Usage java CodeMotion “); return; } int count = Integer.parseInt(args[0]); int numThreads = Integer.parseInt(args[1]); WorkerThread mc[] = new WorkerThread[numThreads]; BufferedOutputStream fos = new BufferedOutputStream ( new FileOutputStream(”print.out”)); for(int i = 0; i < numThreads; i++) { mc[i] = new WorkerThread(count,i,fos); } long start = System.currentTimeMillis(); // <++++ Start timing for(int i = 0; i < numThreads; i++) { mc[i].start(); } for(int i = 0; i < numThreads; i++) { mc[i].join(); } long stop = System.currentTimeMillis(); // <++++ Stop timing fos.close(); System.out.println("Execution time = " + (stop - start)); } catch(Exception e) { System.err.println(e); } Page 168
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

No Comments yet

TrackBack URI

Sorry, the comment form is closed at this time.