Say I have a server with multiple threads that share a reference to a Data instance. Quick eg,
edit1: Updated for readability
public void main() {
Data data = new Data();
ReentrantLock rl = new ReentrantLock(true);
ReadThread t1 = new ReadThread(data, rl);
UploadThread t2 = new UploadThread(data, rl);
t1.start(); t2.start();
}
class ReadThread extends Thread {
private Data data;
private ReentrantLock lock;
ReadThread(Data d, ReentrantLock l){ data = d; lock = l; }
void run(){
lock.lock();
try{
data.put(aString)
} finally { lock.unlock(); }
}
}
class UploadThread extends Thread {
private Data data;
private ReentrantLock lock;
UploadThread(Data d, ReentrantLock l){ data = d; lock = l; }
void run(){
lock.lock();
try{
data.put(aString)
} finally { lock.unlock(); }
}
}
Is it better to use locks like above, or synchronize the put method like below,
class Data {
private LinkedList<String> data = new LinkedList<String>();
synchronized void put(String x){ data.add(x); }
}
This is pretty rough,
I'm mostly just concerned about the concurrency.
With the synchronized method am I correct in assuming the synchronization would occur on the class' "Data" instance/object? So one UploadThread could call the put procedure/method and one ReadThread could do the same in parallel. However using the ReentrantLock example, only one thread would be able to execute a put call at any one time?
What would happen if in the "Data" class I made the LinkedList static and I made the put method synchronized and static? Which is the best approach? Do I lose mut ex if I make things static?