I don't get how this class is not thread safe?
(You may already now the answer to this, but I include it here for completeness.)
The problem is the value++ statement. It's a multi part statement.
- The value of
value is read. - The read value is incremented by one.
- The new value is stored in
value.
This sequence can be intermixed by another thread. Say that value is 5. If two threads calls getNext() (on the same instance), you would expect value to be 7 when they are done. However, if both threads has done step 1 and 2 before any of the threads do step 3, they will both write the value 6 to value:
- Thread 1 do step 1 - reads
5 - Thread 2 do step 1 - reads
5 - Thread 2 do step 2 - increment
5 by 1 - Thread 2 do step 3 - saves the value
6 - Thread 1 do step 2 - increment
5 by 1 - Thread 1 do step 3 - saves the value
6
Won't every time a thread needs to call the method getNext(), it would first create instance of this class?
Not every time. That would be new UnsafeSequence().getNext() over and over again, which wouldn't make sense. But perhaps that's not exactly what you meant. Each thread can have their own instance of the class and call getNext() on that. In that case there is no problem.
Can two threads share same instance of this class (barring explicit share)?
No, an instance must be shared somehow. But it could be shared without you knowing it. E.g., some class may have a static method that return an instance of UnsafeSequence. You wouldn't know if it's the same instance that is returned every time or if a new instance is created by each call. Unless this is documented somewhere.
The discussion about if a class is thread safe or not in API documentation refers to cases when an instance is shared between threads. If an instance is not shared, it's OK to use it in a multi threaded application, as long as it's available and used by only one of the threads.