Best programming approach/methodology to assure thread safety

前端 未结 15 1658
一整个雨季
一整个雨季 2021-01-31 06:28

When I was learning Java coming from a background of some 20 years of procedural programming with basic, Pascal, COBOL and C, I thought at the time that the hardest thing about

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 07:17

    This not only applies to Java but to threaded programming in general. I find myself avoiding most of the concurrency and latency problems just by following these guidelines:

    1/ Let each thread run its own lifetime (i.e., decide when to die). It can be prompted from outside (say a flag variable) but it in entirely responsible.

    2/ Have all threads allocate and free their resources in the same order - this guarantees that deadlock will not happen.

    3/ Lock resources for the shortest time possible.

    4/ Pass responsibility for data with the data itself - once you notify a thread that the data is its to process, leave it alone until the responsibility is given back to you.

提交回复
热议问题