Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Stateless Object in Java?

Currently I'm reading "Java concurrency in practice", which contains this sentence:

Since the action of a thread accessing a stateless object can't affect the correctness of operations on other threads, stateless objects are thread-safe.

So, what is stateless object?

like image 721
TU_HEO DAKAI Avatar asked Mar 16 '12 10:03

TU_HEO DAKAI


People also ask

What are stateful objects?

Stateful Objects are that objects which have changeable members or mutable members, that may vary what transactions or operations were previously performed on the object. For a same operation performed many times, the result outputed may be different from previous result's.

Is Oops stateless?

Key Difference Between Functional Programming and OOP Functional programming has a stateless programming model. Object-oriented programming has a stateful programming model. In functional programming, a state does not exist. In object-oriented programming, the state exists.

Is static stateless?

Static methods? Yes, when they are stateless. Some of the reactions to my last blog post on Named Constructors in PHP, originate from the notion that static methods are inherently bad and should never be used. This is rather overgeneralized.

What is stateful class in Java?

A stateful object is an instance of a class that may morph itself into various states. For example an object can be created, but not initialized, later initialized and ready for being used and at the end it can be disposed (but still remain accessible in memory).


2 Answers

Stateless object is an instance of a class without instance fields (instance variables). The class may have fields, but they are compile-time constants (static final).

A very much related term is immutable. Immutable objects may have state, but it does not change when a method is invoked (method invocations do not assign new values to fields). These objects are also thread-safe.

like image 139
Bozho Avatar answered Sep 22 '22 20:09

Bozho


If the object doesn't have any instance fields, it it stateless. Also it can be stateless if it has some fields, but their values are known and don't change.

This is a stateless object:

class Stateless {     void test() {         System.out.println("Test!");     } } 

This is also a stateless object:

class Stateless {     //No static modifier because we're talking about the object itself     final String TEST = "Test!";      void test() {         System.out.println(TEST);     } } 

This object has state, so it is not stateless. However, it has its state set only once, and it doesn't change later, this type of objects is called immutable:

class Immutable {     final String testString;      Immutable(String testString) {         this.testString = testString;     }      void test() {         System.out.println(testString);     } } 
like image 34
Malcolm Avatar answered Sep 26 '22 20:09

Malcolm