Best programming approach/methodology to assure thread safety

前端 未结 15 1656
一整个雨季
一整个雨季 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:15

    The safest approach to design new applications with multi threading is to adhere to the rule:

    No design below the design.

    What does that mean?

    Imagine you identified major building blocks of your application. Let it be the GUI, some computations engines. Typically, once you have a large enough team size, some people in the team will ask for "libraries" to "share code" between those major building blocks. While it was relatively easy in the start to define the threading and collaboration rules for the major building blocks, all that effort is now in danger as the "code reuse libraries" will be badly designed, designed when needed and littered with locks and mutexes which "feel right". Those ad-hoc libraries are the design below your design and the major risk for your threading architecture.

    What to do about it?

    • Tell them that you rather have code duplication than shared code across thread boundaries.
    • If you think, the project will really benefit from some libraries, establish the rule that they must be state-free and reentrant.
    • Your design is evolving and some of that "common code" could be "moved up" in the design to become a new major building block of your application.
    • Stay away from the cool-library-on-the-web-mania. Some third party libraries can really save you a lot of time. But there is also a tendency that anyone has their "favorites", which are hardly essential. And with each third party library you add, your risk of running into threading problems increases.

    Last not least, consider to have some message based interaction between your major building blocks; see the often mentioned actor model, for example.

提交回复
热议问题