Threadsafe vs Synchronized

前端 未结 7 1383
刺人心
刺人心 2021-02-02 11:01

I\'m new to java. I\'m little bit confused between Threadsafe and synchronized. Thread safe means that a method or class instance can be used by multiple threads at the same tim

7条回答
  •  情书的邮戳
    2021-02-02 11:27

    Thread safety: A thread safe program protects it's data from memory consistency errors. In a highly multi-threaded program, a thread safe program does not cause any side effects with multiple read/write operations from multiple threads on shared data (objects). Different threads can share and modify object data without consistency errors.

    synchronized is one basic method of achieving ThreadSafe code.

    Refer to below SE questions for more details:

    What does 'synchronized' mean?

    You can achieve thread safety by using advanced concurrency API. This documentation page provides good programming constructs to achieve thread safety.

    Lock Objects support locking idioms that simplify many concurrent applications.

    Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

    Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

    ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

    Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

    Related SE question:

    Synchronization vs Lock

提交回复
热议问题