在开始编码之前如何处理并发 [英] How to deal with Concurrency before you start coding

查看:117
本文介绍了在开始编码之前如何处理并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编程一个Java程序的中途,我处在比我想要处理的更多的并发问题的阶段。

I'm midway through programming a Java program, and I'm at the stage where I'm debugging far more concurrency issues than I'd like to be dealing with.

我要问:当你在心理上设计你的程序时,如何处理并发问题?在我的情况下,这是一个相对简单的游戏,但线程的问题不断弹出 - 任何快速修复几乎肯定会导致一个新的问题。

I have to ask: how do you deal with concurrency issues when setting out your program mentally? In my case, it's for a relatively simple game, yet issues with threads keep popping up - any quick-fix almost certainly leads to a new issue.

用非常一般的术语来说,在决定我的应用程序应该如何流动时,我应该使用什么技术来结束我的所有线程?

Speaking in very general terms, what techniques should I use when deciding how my application should 'flow' with out all my threads getting in a knot?

推荐答案

并发性归结于管理共享状态。

Concurrency boils down to managing shared state.


所有并发问题归结为
协调对可变状态的访问
不可变状态it
是确保线程安全。
- Java并发实践

"All concurrency issues boil down to coordinating access to mutable state. The less mutable state, the easier it is to ensure thread safety." -- Java Concurrency in Practice

所以你必须问自己的问题是:

So the question you must ask yourself are:


  • 我的应用程序需要的固有的共享数据是什么?

  • ,可以识别已知的模式 >并且使用更高级的抽象而不是低级锁和线程协调,例如队列,执行程序等。

  • 考虑全局锁定方案,以避免死锁并获得锁的一致性获取

  • What is the inherent shared data that the my application will need?
  • When can a thread work on a snapshot of the data, that is, it momentary work on a clone of the shared data?
  • Can I identify known pattern and use higher-level abstraction rather than low-level locks and thread coordination, e.g. queues, executor, etc. ?
  • Think of a global locking scheme as to avoid deadlock and have a consistent acquisition of locks

管理共享状态的最简单的方法是序列化每个操作。然而,这种粗粒度方法导致高锁争用和差的性能。管理并发性可以看作是一个优化练习,您可以尝试减少争用。因此,后续问题是:

The simplest approach to manage shared state is to serialize every action. This coarse-grained approach results however into a high lock contention and poor performance. Managing concurrency can be seen an optimization exercise where you try to reduce the contention. So subsequent questions are:


  • 最简单的方法是什么?

  • 我可以做出哪些简单的选择来减少争用(可能使用细粒度锁定),并提高性能,而不会使解决方案过于复杂?


很多减少争用的方法依赖于在强制执行正确行为所需的和可以减少争用的可能性之间的某种形式的权衡。

A lot of approach to reduce contention rely on some form of trade-off between what would be necessary to enforce the correct behavior and what is feasible to reduce contention.


  • 我可以在哪里放松一些约束,并接受有时候的东西不会100%正确(例如计数器)?

  • 只有当发生并发修改时(例如使用时间戳和重试逻辑,这是TM所做的),才能保持乐观并处理冲突?

注意,我从来没有在一个游戏,只在服务器端的一部分企业应用程序。我可以想象它可以完全不同。

Note that I never worked on a game, only on server-side part of enterprise apps. I can imagine that it can be quite different.

这篇关于在开始编码之前如何处理并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆