Originally posted by Paul Caudle:
What is a stateless object in Java (if there is such a thing) and what is it used for (or when does it occur)?
An object without state, which roughly translates to: without member variables.
You would prefer to use stateless objects in multi-threaded contexts, because they are inherently threadsafe. Common examples are JSPs and
servlets. Rather than maintaining any state themselves, they pull their state from their context -- the request, the session, the servlet context.
JSPs and servlets which need to maintain state usually end up implementing the SingleThreadModel. This causes the server to never run more than a single request through them. This is because
JSP programmers are generally wimps
You will also find stateless objects in certain design
patterns, most notably the Flyweight pattern from the GoF book. Flyweights are used where you need lots of objects which are essentially identical; by removing all state from them, you never need to create more than one copy for each type of object. (They gave the rather convoluted example of representing each single character in a document using objects).
- Peter