What is Stateless Object in Java?

前端 未结 10 1337
猫巷女王i
猫巷女王i 2020-11-30 21:32

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

Since the action of a thread accessing a stateless object can\'

相关标签:
10条回答
  • 2020-11-30 21:39

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-30 21:48

    An objects that have absolutely no state then there is no problem with reusing them at this point the question is: if they have absolutely no state why not make all the methods static and never create one at all?

    0 讨论(0)
  • 2020-11-30 21:51

    The concept of stateless object is highly coupled with concept of side effects. Shortly, that is the object that has no fields underneath which could have different values, dependently on different order of method calls.

    0 讨论(0)
  • 2020-11-30 21:51

    Just a clarification. You can consider your class as stateless in the way that is stated before, even when it has an instance variable as far as this variable is final AND immutable.

    If the instance variable is just final but mutable, a List of Strings in example, yes the variable's reference can not be changed but the contents of the List and thus the state of the class can be changed.

    0 讨论(0)
  • 2020-11-30 21:52

    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.

    0 讨论(0)
  • 2020-11-30 21:52

    If you can not change any parameter or value etc. of an object, after its creation, then that object is thread-safe.

    0 讨论(0)
提交回复
热议问题