how to lock free use two ConcurrentHashMap in java/scala?
I headache with the problem long time ago, hope some help really.
I want store many Task
with ConcurrentSkipListMap
which inner is ConcurrentHashMap
as known as multi-segment lock.
The simple example code show with scala(java also readable):
val tasks = new ConcurrentSkipListMap[TaskKey, Task]()
refer class simple as:
class TaskKey(id: String, systemTime: Long)
TaskKey class used to identity Task is unique and the Task as follow:
trait Task {
val taskId: TaskKey //account and custom name
def execute(): Unit //do the task
}
When I use TaskKey to operate my HashMap is grate but actually, the HashMap can access with id barely.So, I must define another ConcurrentHashMap to store map of id to TaskKey:
val auxiliaryMap = new ConcurrentHashMap[String, TaskKey]()
Let's consider a add and remove operate:
def get(taskId: String) = {
Option(auxiliaryMap.get(taskId)).flatMap{x => //try get TaskKey
//if TaskKey exist, try get it.
Option(tasks.get(x)) //make null to None
}
}
def remove(taskId: String) = {
Option(auxiliaryMap.remove(taskId)).flatMap{ x => //try get TaskKey
//if TaskKey exist, try remove it.
Option(tasks.remove(x)) //make null to None
}
}
Obviously, although both of Map is thread safe, the wrapper make data not consistency. If I use a lock the multi-segment Map become meaningless. How can I deal with the problem make two ConcurrentHashMap work well?
Besides, the TaskKey contains a systemTime variable used to sort data,complete ConcurrentSkipListMap
define as this:
val tasks = new ConcurrentSkipListMap[TaskKey, Task](new Comparator[TaskKey]() {
override def compare(o1: TaskKey, o2: TaskKey): Int = {
val compare = (o1.systemTime - o2.systemTime).toInt
if (compare == 0) {
o1.hashCode() - o2.hashCode()
} else compare //distinct same time task
}
})
any question are welcome if I miss something.
我正在使用消息队列来将运算符平铺到这些maps.besides,这种方式根本不需要concurrenthashmap,但消息队列可能需要一个并发队列。
链接地址: http://www.djcxy.com/p/91922.html