对于哪些类型变量绝对不能是静态的?

发布于 2024-10-05 01:19:34 字数 319 浏览 3 评论 0原文

在我们的项目中大量使用的一个库中,存在一个限制,即其类的变量绝不能是静态的。 (它是ULC)。据我了解,这是因为需要将它们全部序列化。这个规则的问题在于它并不严格,并且可能会导致很难调试的错误。

我们将为 Checkstyle 编写一个模块来检测此类类型的静态变量(可能由一些可定制的正则表达式检测)。我们需要知道这项检查对于其他开发人员来说有多么必要。

所以问题是:一般情况下,某些类型的变量绝对不能是静态的?

In one library that is in heavy use in our project there is a restriction that variables of its classes must never be static. (It is ULC). As far as I understood it is because of the need to serialize all of them. And the problem with this rule, is that it is not strict and may be the cause of bugs that are very hard to debug.

We are going to write a module for Checkstyle to detect static variables of such types (detected by some customizable regexp probably). And we need to know how necessary is this check for other developers.

So the question is: What are the general circumstances when variables of some types must never be static?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜味拾荒者 2024-10-12 01:19:34

首先,正确的面向对象设计应该告知将方法/字段设为静态的决定。

其次,在 Web 应用程序中,请求都是在单独的线程上处理的,因此您必须非常小心如何使用静态方法/字段。如果您的静态方法在调用之间维护任何状态(例如,通过使用静态字段来保持计数),则可能会遇到线程问题。发生这种情况是因为一个请求可能会调用静态方法,然后在执行过程中被调用该方法的另一个线程停止。如果第一次调用修改了公共资源,但未完成,则第二次调用可能会破坏第一次执行的进度。

First, proper object oriented design should inform the decision to make a method/field static.

Second, in a web application, where requests are all handled on separate threads, you have to be very careful how you use static methods/fields. If your static method maintains any state across invocations(by using a static field to keep a count, for example), you can run into threading issues. This happens because one request might invoke the static method, and then be stopped in the middle of execution by another thread that invokes the method. If the first invocation modified a common resource, but did not finish, the second invocation might corrupt the progress of the first execution.

彡翼 2024-10-12 01:19:34

简单的答案:如果类型将以线程不安全的方式修改,则绝对不能将其用作静态实例。我怀疑这就是为什么 ULC 建议不要以这种方式使用它们的类型(不是因为序列化)。

不幸的是,用 checkstyle 之类的东西来检查这一点非常困难。例如,HashMap 不是线程安全的。但是,如果我构造一个实例并在类加载期间静态填充它,然后只从映射中读取,那么这是 HashMap 的安全用法(因为类加载在设置时提供了外部线程安全保证,并且之后永远不会修改) 。

Simple answer: a type must never be used as a static instance if it will be modified in a thread-unsafe manner. i suspect this is why the ULC recommends not using their types this way (not because of serialization).

unfortunately, checking this with something like checkstyle is exceedingly difficult. as an example, HashMap is not thread-safe. however, if i construct an instance and populate it staticly during class loading and then only ever read from the map afterwards, this is a safe usage of HashMap (because classloading provides the external thread-safety guarantee on setup and it is never modified afterwards).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文