What is Stateless Object in Java?

前端 未结 10 1406
猫巷女王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);
        }
    }
    

提交回复
热议问题