Synchronized Vs Semaphore

前端 未结 3 682
[愿得一人]
[愿得一人] 2021-02-07 01:18

While reading concurrency in Java, I have following doubts:

  1. Does Java provides lower level construct then synchronized for synchronization?

  2. In

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 01:38

    There is also atomics. This gives access to the basic hardware compare-and-swap command that's the basis of all synchronization. It allows you, for example, to increment a number safely. If you ++ a volatile field, another thread executing the same instruction could read the field before your thread writes to it, then write back to it after your thread. So one increment gets lost. Atomics do the read and write "atomically" and so avoid the problem.

    Actually, volatiles, synchronized statements, and atomics tend to force all thread data to be refreshed from main memory and/or written to main memory as appropriate, so none of them are really that low level. (I'm simplifying here. Unlike C#, Java does not really have a concept of "main memory".)

提交回复
热议问题