SERVLET.SYN
Minimize synchronization in Servlets
Description
This rule flags excessive synchronization in servlets.
Servlets are multi-threaded. Servlet-based applications have to recognize and handle this. However, if large sections of code are synchronized, an application effectively becomes single threaded, and throughput decreases.
Example
package SERVLET;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class SYN extends HttpServlet {
private int numberOfRows = 0;
private javax.sql.DataSource ds = null;
public void synExample (HttpServletRequest request) {
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
int startingRows;
try {
synchronized (this) {
startingRows = numberOfRows;
String info = null;
conn = ds.getConnection ("db2admin", "db2admin");
stmt = conn.prepareStatement ("select * from
db2admin.employy");
rs = stmt.executeQuery ();
info = rs.getString ("Name");
}
} catch (Exception e) {
} finally {
try { rs.close (); }
catch (Exception e) {}
}
}
}
Repair
public void synBetterExample (HttpServletRequest request) {
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
int startingRows;
// lock only necessary one.
synchronized (this) {
startingRows = numberOfRows;
}
try {
String info = null;
conn = ds.getConnection ("db2admin", "db2admin");
stmt = conn.prepareStatement ("select * from
db2admin.employy");
rs = stmt.executeQuery ();
info = rs.getString ("Name");
} catch (Exception e) {
} finally {
try { rs.close (); }
catch (Exception e) {}
}
}
Reference
IBM WebSphere Application Server Standard and Advanced Editions, Harvey W. Gunther.
http://www-4.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
|