What is a race condition?

后端 未结 18 2406
谎友^
谎友^ 2020-11-21 04:52

When writing multithreaded applications, one of the most common problems experienced is race conditions.

My questions to the community are:

What is the rac

18条回答
  •  有刺的猬
    2020-11-21 05:25

    What is a Race Condition?

    You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That's a race condition - specifically a "check-then-act" scenario of race conditions.

    How do you detect them?

    Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.

    How do you handle and prevent them?

    The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.

    The best resource for concurrency is JCIP. You can also get some more details on above explanation here.

提交回复
热议问题