读书人

有状态,无状态对像样什么概念

发布时间: 2012-09-25 09:55:58 作者: rapoo

有状态,无状态对象是什么概念
转载标签:设计模式杂谈分类:java

基本概念:

有状态就是有数据存储功能。有状态对象(StatefulBean),就是有实例变量的对象,可以保存数据,是非线程安全的。在不同方法调用间不保留任何状态。

无状态就是一次操作,不能保存数据。无状态对象(StatelessBean),就是没有实例变量的对象.不能保存数据,是不变类,是线程安全的。

代码更好理解:

Java代码
    ??public?class?StatefulBean?{????????public?int?state;??????//?由于多线程环境下,user是引用对象,是非线程安全的??????public?User?user;????????public?int?getState()?{??????????return?state;??????}????????public?void?setState(int?state)?{??????????this.state?=?state;??????}????????public?User?getUser()?{??????????return?user;??????}????????public?void?setUser(User?user)?{??????????this.user?=?user;??????}??} ??????public?class?StatelessBeanService?{????????//?虽然有billDao属性,但billDao是没有状态信息的,是Stateless?Bean.??????BillDao?billDao;????????public?BillDao?getBillDao()?{??????????return?billDao;??????}????????public?void?setBillDao(BillDao?billDao)?{??????????this.billDao?=?billDao;??????}????????public?List<User>?findUser(String?Id)?{??return?null;??????}??}??


单例模式中的有状态和无状态:
单例类可以是有状态的(stateful),一个有状态的单例对象一般也是可变(mutable)单例对象。有状态的可变的单例对象常常当做状态库(repositary)使用。比如一个单例对象TaskCache(Spring中配为singleton)可以持有一个AtomicLong类型的属性,用来给一个系统提供一个数值惟一的序列号码,作为任务通迅管理的ID生成器。同时,一个单例类也可以持有一个聚集,从而允许存储多个状态,如示例中的ExpiringMap缓存任务列表。
代码示例:

Java代码
    import?java.util.concurrent.atomic.AtomicLong;????import?org.apache.mina.util.ExpiringMap;??????public?class?TaskCache?{????????//?请求超时??????private?short?requestTimeout;????????//?这个缓存Map是线程安全,并且有定时超时功能??????private?ExpiringMap<String,?Object>?tasksMap?=?new?ExpiringMap<String,?Object>();????????//?线程安全的原子类,示例有状态的单例类??????private?static?AtomicLong?seqNo?=?new?AtomicLong(1);????????//?示例有状态的单例类??????public?Long?nextSeqNo()?{??????????return?seqNo.getAndIncrement();??????}????????public?void?setRequestTimeout(short?requestTimeout)?{??????????this.requestTimeout?=?requestTimeout;??????}????????//?启动过期检测??????public?void?startExpiring()?{??????????tasksMap.getExpirer().setTimeToLive(requestTimeout);??????????tasksMap.getExpirer().startExpiringIfNotStarted();??????}????????//?停止过期检测??????public?void?stopExpiring()?{??????????tasksMap.getExpirer().stopExpiring();??????}????????//?取任务列表.??????public?Object?getTasks(String?key)?{??????????return?tasksMap.get(key);??????}????????//?去除任务列表.??????public?Object?removeTasks(String?key)?{??????????return?tasksMap.remove(key);??????}????????//?添加任务列表.??????public?void?addTasks(String?key,?Object?value)?{??????????tasksMap.put(key,?value);??????}??}??



单例类也可以是没有状态的(stateless),仅用做提供工具性函数的对象。既然是为了提供工具性函数,也就没有必要创建多个实例,因此使用单例模式很合适。平常的单例类都是没有状态的,这里就不示例了。一个没有状态的单例类也就是不变(Immutable)单例类。关于不变模式,请参考http://www.javaeye.com/topic/959751

EJB中的有状态与无状态:

1.Stateful session bean的每个用户都有自己的一个实例,所以两者对statefulsessionbean的操作不会影响对方。另外注意:如果后面需要操作某个用户的实例,你必须在客户端缓存Bean的Stub对象(JSP通常的做法是用Session缓存),这样在后面每次调用中,容器才知道要提供相同的bean实例。

2.Stateless Session Bean不负责记录使用者状态,Stateless SessionBean一旦实例化就被加进会话池中,各个用户都可以共用。如果它有自己的属性(变量),那么这些变量就会受到所有调用它的用户的影响。

3.从内存方面来看,Stateful Session Bean与Stateless Session Bean比较,StatefulSession Bean会消耗J2EE Server 较多的内存,然而Stateful SessionBean的优势却在于他可以维持使用者的状态。

Spring中的有状态(Stateful)和无状态(Stateless)

1.通过上面的分析,相信大家已经对有状态和无状态有了一定的理解。无状态的Bean适合用不变模式,技术就是单例模式,这样可以共享实例,提高性能。有状态的Bean,多线程环境下不安全,那么适合用Prototype原型模式。Prototype:每次对bean的请求都会创建一个新的bean实例。

2.默认情况下,从Springbean工厂所取得的实例为singleton(scope属性为singleton),容器只存在一个共享的bean实例。

3.理解了两者的关系,那么scope选择的原则就很容易了:有状态的bean都使用prototype作用域,而对无状态的bean则应该使用singleton作用域。

4.如Service层、Dao层用默认singleton就行,虽然Service类也有dao这样的属性,但dao这些类都是没有状态信息的,也就是相当于不变(immutable)类,所以不影响。Struts2中的Action因为会有User、BizEntity这样的实例对象,是有状态信息的,在多线程环境下是不安全的,所以Struts2默认的实现是Prototype模式。在Spring中,Struts2的Action中,scope要配成prototype作用域。

Servlet、Struts中的有状态和无状态:

1.Servlet体系结构是建立在Java多线程机制之上的,它的生命周期是由Web容器负责的。一个Servlet类在Application中只有一个实例存在,也就是有多个线程在使用这个实例。这是单例模式的应用。无状态的单例是线程安全的,但我们如果在Servlet里用了实例变量,那么就变成有状态了,是非线程安全的。如下面的用法就是不安全的,因为user,out都是有状态信息的。

Java代码
    ??public?class?UnSafeServlet?HttpServlet{????????????User?user;??????PrintWriter?out;????????????public?void?doGet?(HttpServletRequest?request,?HttpServletResponse?response)throws?ServletException,?IOException{??????????//do?something...??????}??}??


Out,Request,Response,Session,Config,Page,PageContext是线程安全的,Application在整个系统内被使用,所以不是线程安全的.

2.Struts1也是基于单例模式实现,也就是只有一个Action实例供多线程使用。默认的模式是前台页面数据通过actionForm传入,在action中的excute方法接收,这样action是无状态的,所以一般情况下Strunts1是线程安全的。如果Action中用了实例变量,那么就变成有状态了,同样是非线程安全的。像下面这样就是线程不安全的。

Java代码
    ??public?class?UnSafeAction1?extends?Action?{????????//?因为Struts1是单例实现,有状态情况下,对象引用是非线程安全的??????User?user;????????public?void?execute()?{??????????//?do?something...??????}????????public?User?getUser()?{??????????return?user;??????}????????public?void?setUser(User?user)?{??????????this.user?=?user;??????}??}????



3.Struts2默认的实现是Prototype模式。也就是每个请求都新生成一个Action实例,所以不存在线程安全问题。需要注意的是,如果由Spring管理action的生命周期,scope要配成prototype作用域。

4.如何解决Servlet和Struts1的线程安全问题,当我们能比较好的理解有状态和无状态的原理,自然很容易得出结论:不要使用有状态的bean,也就是不要用实例变量。如果用,就要用prototype模式。Struts1user guide里有: Only Use Local Variables - The most importantprinciple that aids in thread-safe coding is to use only localvariables, not instance variables , in your Action class.

总结:
Stateless无状态用单例Singleton模式,Stateful有状态就用原型Prototype模式。
Stateful有状态是多线程编码的天敌,所以在开发中尽量用Stateless无状态,无状态是不变(immutable)模式的应用,有很多优点:不用管线程和同步的问题,如果值是不可变的,程序不用担心多个线程改变共享状态,所以可以避免线程竞争的bugs.因为没有竞争,就不用用locks等机制,所以无状态的不变机制,也可以避免产生死锁现象。

国外一些哥们的观点:
Immutable objects may not be altered after their creation. So: Yes,they are some kind of stateless.As immutable objects can not bechanged, there is no need for locking - reading access to objectsis always threadsafe (when not modifying variables). Therefore,real immutable objects are always threadsafe.

RodJohnson大叔的观点:
Stateless or Stateful?
Service objects will usually be stateless. Stateless service layersare highly scalable: They pose no replication issues and there isno need to allocate additional resources for every client.(Remember that one of
the key motivations of a middle tier is to share resources betweenmultiple clients.) It is also much easier for stateless servicelayers to support remote clients, if necessary. A stateless servicelayer is one concession of object orientation that I find not toopainful.
此处省去N个字。
If possible, design applications to use a stateless service layer.Hold state in the web tier, rather than in the business logic tier,if possible.

读书人网 >编程

热点推荐