I am new to concurrent programming and have read synchronization and Locks. What i get to know that we can write one at a time. However my requirement is to: 1. write concurrently for different key values 2. lock only at key level i.e. if one thread is executing write operation for key1, another thread for key1 should wait
Any advice which option to use for this implementation?
I am using KeyValueLib Class in vetx framework
You can have multiple locks, and use a unique lock for each key separately. for example:
public class MultipleKeyExample{
private Object lock1=new Object();
private Object lock2=new Object();
private int x,y;// these could be your keys
......
public void setX(int x){
synchronized(lock1){
this.x=x;
}
}
public void setY(int y){
synchronized(lock2){
this.y=y;
}
}
public int getX(){
synchronized(lock1){
return x;
}
}
public int getY(){
synchronized(lock2){
return y;
}
}
}
Though I personally prefer the locks that come in Java's concurrent utilities.
You could use the ReentrantReadWriteLock
. You can change the above code as:
public class MultipleKeyExample{
private ReadWriteLock lock1=new ReentrantReadWriteLock();
private ReadWriteLock lock2=new ReentrantReadWriteLock();
private int x,y;
......
public void setX(int x){
lock1.writeLock().lock();
this.x=x;
lock1.writeLock().unlock();
}
public void setY(int y){
lock2.writeLock().lock();
this.y=y;
lock2.writeLock().unlock();
}
public int getX(){
lock1.readLock().lock();
return x;
lock1.readLock().unlock();
}
public int getY(){
lock2.readLock().lock();
return y;
lock2.readLock().unlock()
}
}
Edit:
If you want the number of keys not to be predefined, you can create objects for each key, and store them in a collection frameworks data structure. or more simply, use a concurrent data structure like ConcurrentHashTable
.
hope this helps.