What is the meaning of the term “thread-safe”?

前端 未结 18 1765
孤独总比滥情好
孤独总比滥情好 2020-11-22 13:51

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

相关标签:
18条回答
  • 2020-11-22 14:08

    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:

    1. Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
    2. Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
    3. Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
    4. Actions prior to "releasing" synchronizer methods such as 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.
    5. For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
    6. Actions prior to calling 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.
    0 讨论(0)
  • 2020-11-22 14:09

    As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.

    It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.

    For example, Java has two classes that are almost equivalent, StringBuffer and StringBuilder. The difference is that StringBuffer is thread-safe, so a single instance of a StringBuffer may be used by multiple threads at once. StringBuilder is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.

    0 讨论(0)
  • 2020-11-22 14:09

    Thread-safe-code works as specified, even when entered simultaneously by different threads. This often means, that internal data-structures or operations that should run uninterrupted are protected against different modifications at the same time.

    0 讨论(0)
  • 2020-11-22 14:10

    In simplest words :P If it is safe to execute multiple threads on a block of code it is thread safe*

    *conditions apply

    Conditions are mentioned by other answeres like 1. The result should be same if you execute one thread or multiple threads over it etc.

    0 讨论(0)
  • 2020-11-22 14:17

    Don't confuse thread safety with determinism. Thread-safe code can also be non-deterministic. Given the difficulty of debugging problems with threaded code, this is probably the normal case. :-)

    Thread safety simply ensures that when a thread is modifying or reading shared data, no other thread can access it in a way that changes the data. If your code depends on a certain order for execution for correctness, then you need other synchronization mechanisms beyond those required for thread safety to ensure this.

    0 讨论(0)
  • 2020-11-22 14:18

    From Wikipedia:

    Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

    There are a few ways to achieve thread safety:

    Re-entrancy:

    Writing code in such a way that it can be partially executed by one task, reentered by another task, and then resumed from the original task. This requires the saving of state information in variables local to each task, usually on its stack, instead of in static or global variables.

    Mutual exclusion:

    Access to shared data is serialized using mechanisms that ensure only one thread reads or writes the shared data at any time. Great care is required if a piece of code accesses multiple shared pieces of data—problems include race conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.

    Thread-local storage:

    Variables are localized so that each thread has its own private copy. These variables retain their values across subroutine and other code boundaries, and are thread-safe since they are local to each thread, even though the code which accesses them might be reentrant.

    Atomic operations:

    Shared data are accessed by using atomic operations which cannot be interrupted by other threads. This usually requires using special machine language instructions, which might be available in a runtime library. Since the operations are atomic, the shared data are always kept in a valid state, no matter what other threads access it. Atomic operations form the basis of many thread locking mechanisms.

    read more:

    http://en.wikipedia.org/wiki/Thread_safety


    • in German: http://de.wikipedia.org/wiki/Threadsicherheit

    • in French: http://fr.wikipedia.org/wiki/Threadsafe (very short)

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