简体   繁体   English

在Web应用程序Java中存储静态实例变量

[英]Storing in static instance variable in web app Java

Suppose i have a static instance variable which stores Lists<?> . 假设我有一个静态实例变量,它存储Lists<?> As it is marked static the contents stored in this variable stay till the class is unloaded. 由于标记为静态,因此存储在该变量中的内容将一直保留到卸载该类为止。

Now take the case of a web app. 现在以网络应用程序为例。 suppose i am using a framework like play and jpa as persistence. 假设我使用诸如play和jpa之类的框架作为持久性。

In case i use this variable to persist using jpa. 如果我使用此变量来持久使用jpa。 but as its static instance variable everything will be in memory till the app reloads. 但作为其静态实例变量,所有内容都将保留在内存中,直到应用程序重新加载为止。 As its a web app everything being persisted from that variable will be also stored in memory till the app reloads. 由于它是一个Web应用程序,因此从该变量中持久存储的所有内容也将存储在内存中,直到应用程序重新加载。 so won't the jvm run out of memory if i don't unload the class? 因此,如果我不卸载类,jvm会不会耗尽内存?

Also what is the best practice of using instance variable for persistence 还有使用实例变量进行持久化的最佳实践是什么

I don't think persisting those objects with JPA (or any similar technology) will change anything. 我不认为使用JPA(或任何类似技术)保留那些对象不会改变任何事情。 When you persist something, you are just saving it somewhere (in this case a database). 当您保留某些内容时,您只是将其保存在某个位置(在本例中为数据库)。 Those objects will still exist in memory after persisted. 这些对象在持久化后仍将存在于内存中。

If those are referenced by something (in your case those lists in the static var(s)) they can't be garbage collected, and so if you keep adding elements to those lists and don't remove them you will eventually run out of memory. 如果这些被某些东西引用(在您的情况下是静态var中的那些列表),则它们将不会被垃圾回收,因此,如果您继续向这些列表中添加元素并且不删除它们,最终将用完记忆。

Also note that if you store those objects in a static variable, they may be shared by a lot of objects (ex: instances of that class trying to add, remove or count the number of elements) and you may run into concurrency problems. 还要注意,如果将这些对象存储在静态变量中,则它们可能被许多对象共享(例如:该类的实例试图添加,删除或计算元素数量),并且可能会遇到并发问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM