struts action线程不安全

本文探讨了在处理HTTP请求时,多个线程同时访问同一个Action实例可能导致的数据共享问题。通过实例展示了如何在Java环境中实现线程安全的Action管理,确保每个请求得到独立且正确的响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Action instance = null;
        synchronized (actions) {

            // Return any existing Action instance of this class
            instance = (Action) actions.get(className);
            if (instance != null) {
                if (log.isTraceEnabled()) {
                    log.trace("  Returning existing Action instance");
                }
                return (instance);
            }

            // Create and return a new Action instance
            if (log.isTraceEnabled()) {
                log.trace("  Creating new Action instance");
            }
            
            try {
                instance = (Action) RequestUtils.applicationInstance(className);
                // :TODO: Maybe we should propagate this exception
                // instead of returning null.
            } catch (Exception e) {
                log.error(
                    getInternal().getMessage("actionCreate", mapping.getPath()),
                    e);
                    
                response.sendError(
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    getInternal().getMessage("actionCreate", mapping.getPath()));
                    
                return (null);
            }
            
            instance.setServlet(this.servlet);
            actions.put(className, instance);
        }


instance = (Action) actions.get(className);

此代码表情当带有同样URL的请求过来时,会拿同样的action。此时就会发生多线程资源共享的问题。所以如果action类的成员变量修改会传递到下一个使用action的线程。所以不建议在action中使用成员变量。另外只允许一个线程对action进行操作!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值