且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

会话bean中的静态变量限制

更新时间:2023-12-03 16:00:52

如关于EJB限制的常见问题解答,使用EJB的一个限制是:

As stated in the FAQ on EJB restrictions, one of the restrictions for using EJBs is:


企业bean不应读取或写入非最终静态字段

enterprise beans should not read or write nonfinal static fields

静态字段讨论中进一步扩展:


EJB中不允许使用非最终静态类字段,因为这些字段使企业bean难以或无法分发。静态类字段在特定类的所有实例之间共享,但仅在单个Java虚拟机(JVM)***享。更新静态类字段意味着在类的所有实例之间共享字段值的意图。但是,如果一个类同时在多个JVM中运行,则只有与更新实例在同一JVM中运行的那些实例才能访问新值。换句话说,如果在单个JVM中运行,非最终静态类字段的行为将不同于在多个JVM中运行的行为。 EJB容器保留了跨多个JVM(在同一服务器或任何服务器集群上运行)分发企业bean的选项。不允许使用非最终静态类字段,因为企业bean实例的行为会有所不同,具体取决于它们是否已分发。

Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). Updating a static class field implies an intent to share the field's value among all instances of the class. But if a class is running in several JVMs simultaneously, only those instances running in the same JVM as the updating instance will have access to the new value. In other words, a nonfinal static class field will behave differently if running in a single JVM, than it will running in multiple JVMs. The EJB container reserves the option of distributing enterprise beans across multiple JVMs (running on the same server, or on any of a cluster of servers). Nonfinal static class fields are disallowed because enterprise bean instances will behave differently depending on whether or not they are distributed.

如果这些字段是标记为最终。由于无法更新最终字段,因此容器可以分发企业bean的实例,而无需担心这些字段的值变得不同步。

It is acceptable practice to use static class fields if those fields are marked as final. Since final fields cannot be updated, instances of the enterprise bean can be distributed by the container without concern for those fields' values becoming unsynchronized.