JSP 預設以多執行緒方式執行,這是區別於 ASP、PHP、Perl 等腳本語言的優勢之一,能大幅降低系統資源需求、提高併發量與響應速度。然而,若忽略多執行緒環境下的同步問題,將導致難以重現的錯誤。
| 變量類型 | 儲存位置 | 是否線程安全 | 說明 |
|---|---|---|---|
| 實例變量 | 堆積區 | 否 | 屬於該實例的所有執行緒共享 |
| JSP 內建物件 (out, request, response, session, config, page, pageContext) | — | 是 | 每個請求獨立 |
| application | — | 否 | 整個系統共享 |
| 局部變量 | 堆疊區 | 是 | 每個執行緒擁有獨立堆疊空間 |
| 靜態類/靜態變量 | 方法區 | 否 | 全域共享 |
| 外部資源 (檔案、資料庫連線等) | — | 視情況 | 多執行緒/進程同時操作時需同步 |
<%@ page import="javax.naming.*, java.util.*, java.sql.*, weblogic.common.*" %>
<%
String name = request.getParameter("name");
String product = request.getParameter("product");
long quantity = Long.parseLong(request.getParameter("quantity")); // (1)
savebuy();
%>
<%!
public void savebuy() {
try {
Properties props = new Properties();
props.put("user", "scott");
props.put("password", "tiger");
props.put("server", "DEMO");
Driver myDriver = (Driver) Class.forName("weblogic.jdbc.oci.Driver").newInstance();
Connection conn = myDriver.connect("jdbc:weblogic:oracle", props);
Statement stmt = conn.createStatement();
String inssql = "insert into buy(empid, name, dept) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(inssql);
pstmt.setString(1, name);
pstmt.setString(2, product);
pstmt.setLong(3, quantity);
pstmt.execute();
} catch (Exception e) {
System.out.println("SQLException: " + e.getMessage());
} finally {
// 關閉資源...
}
}
%>
問題分析: 程式碼在 savebuy() 中使用了實例變量 name、product、quantity。每條 Java 敘述並非原子操作,執行緒 A 在 (1) 處休眠時,執行緒 B 可能修改 quantity,導致執行緒 A 寫入錯誤資料——這是嚴重的資料不一致問題。
<%@ page isThreadSafe="false" %>
所有請求串列執行,雖解決線程安全,但嚴重降低系統效能,不推薦用於高併發場景。
synchronized 同步public synchronized void savebuy() { ... }
保持多執行緒執行,但同步鎖會造成執行緒阻塞,同樣降低效能。
將資料以參數傳遞給方法,參數在堆疊分配,天然線程安全:
<%!
public void savebuy(String name, String product, long quantity) {
// 使用參數進行資料庫操作...
}
%>
<%
String name = request.getParameter("name");
String product = request.getParameter("product");
long quantity = Long.parseLong(request.getParameter("quantity"));
savebuy(name, product, quantity);
%>
若參數過多,可封裝為資料傳輸物件 (DTO):
public class BuyInfo {
String name;
String product;
long quantity;
}
public void savebuy(BuyInfo info) { ... }
<%
BuyInfo userbuy = new BuyInfo();
userbuy.name = request.getParameter("name");
userbuy.product = request.getParameter("product");
userbuy.quantity = Long.parseLong(request.getParameter("quantity"));
savebuy(userbuy);
%>
優先採用方案三(局部變量/DTO 參數傳遞),因為它不犧牲效能,且從架構上徹底消除共享狀態。方案一、二雖能解決問題,但會嚴重影響系統吞吐量。
線程安全問題通常僅在高併發時出現,且難以重現,因此開發階段必須時刻保持警覺,養成「無共享狀態」的編程習慣。