Does it mean that two threads can\'t change the underlying data simultaneously? Or does it mean that the given code segment will run with predictable results when multiple t
I would like to add some more info on top of other good answers.
Thread safety implies multiple threads can write/read data in same object without memory inconsistency errors. In highly multi threaded program, a thread safe program does not cause side effects to shared data.
Have a look at this SE question for more details:
What does threadsafe mean?
Thread safe program guarantees memory consistency.
From oracle documentation page on advanced concurrent API :
Memory Consistency Properties:
Chapter 17 of The Java™ Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation.
The synchronized
and volatile
constructs, as well as the Thread.start()
and Thread.join()
methods, can form happens-before relationships.
The methods of all classes in java.util.concurrent
and its subpackages extend these guarantees to higher-level synchronization. In particular:
Runnable
to an Executor
happen-before its execution begins. Similarly for Callables submitted to an ExecutorService
.Future
happen-before actions subsequent to the retrieval of the result via Future.get()
in another thread.Lock.unlock, Semaphore.release, and CountDownLatch.countDown
happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await
on the same synchronizer object in another thread.Exchanger
, actions prior to the exchange()
in each thread happen-before those subsequent to the corresponding exchange() in another thread.CyclicBarrier.await
and Phaser.awaitAdvance
(as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.