[英]Java Concurrency in app server
I have a small web application with CRUD operations. 我有一个带有CRUD操作的小型Web应用程序。 For the data, I can't use a db, so I must store it in a map or similar data structure.
对于数据,我不能使用db,所以我必须将它存储在地图或类似的数据结构中。 Based on the requirement, I need two maps to store and access the data, and I have to make sure they are in sync with each other.
根据要求,我需要两个地图来存储和访问数据,我必须确保它们彼此同步。 Now, the question, what is the preferred way to make crud operations on the two maps on in a multi threaded environment making sure they are in consistent state.
现在,问题是,在多线程环境中对两个映射进行crud操作的首选方法是什么,以确保它们处于一致状态。 Is there a better approach or pattern to avoid locking and synchronization?
是否有更好的方法或模式来避免锁定和同步?
Thanks 谢谢
I believe there has to be some synchronization involved. 我认为必须有一些同步。 You can try the following approach.
您可以尝试以下方法。 First of all use a
ConcurrentHashMap
for both of your maps. 首先为两个地图使用
ConcurrentHashMap
。 Then encapsulate both your maps in an object that will have synchronized methods to ensure your data is in a consistent state. 然后将您的映射封装在将具有同步方法的对象中,以确保您的数据处于一致状态。 The following is an example:
以下是一个例子:
public class ParentMap {
private ConcurrentHashMap<String, Object> map1 = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, Object> map2 = new ConcurrentHashMap<>();
public synchronized void add(Object objectToAdd) {
// Add to map1
// Add to map2
}
public synchronized void update(String key, Object object) {
// Update the object based on the key on both maps (following the rules of your application)
}
public synchronized void delete(String key) {
// Delete in both maps following the rules of your application
}
public Object get(String key) {
// Use the rules of your application to read
}
}
Ensure that there is only one ParentMap
object in your application. 确保应用程序中只有一个
ParentMap
对象。 You may use the Singleton Pattern for this. 您可以使用Singleton模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.