How to create a variable that can be set only once but isn't final in Java

后端 未结 12 1577
感情败类
感情败类 2020-12-14 05:43

I want a class that I can create instances of with one variable unset (the id), then initialise this variable later, and have it immutable after initial

12条回答
  •  伪装坚强ぢ
    2020-12-14 06:34

    Google's Guava library (which I recommend very highly) comes with a class that solves this problem very well: SettableFuture. This provides the set-once semantics that you ask about, but also a lot more:

    1. The ability to communicate an exception instead (the setException method);
    2. The ability to cancel the event explicitly;
    3. The ability to register listeners that will be notified when the value is set, an exception is notified or the future is canceled (the ListenableFuture interface).
    4. The Future family of types in general used for synchronization between threads in multithreaded programs, so SettableFuture plays very nicely with these.

    Java 8 also has its own version of this: CompletableFuture.

提交回复
热议问题