java multi threading - how to synchronise

57 views Asked by At

I have a class with following method

public class Test {
    private List l1;
    public void send() {
         for (<type> x : l1) {
               //send to receivers and put a log in DB
          }
    }
}

This Test class is used by different threads which will fill the variable 'l1' with their own data and send them to receivers. If I have to synchronize this to send data sequentially so that receivers get one full frame of data every time(without jumbling of data from different threads), should I synchronize on 'l1' or synchronize on the class Test. I read the tutorials and samples but I still have this question.

1

There are 1 answers

0
Giovanni On BEST ANSWER

You should synchronize on the object that represents you "shared state" (l1 in this case); you must ensure that every insert/read operation is synchronized so you must have a synchronized(l1) {...} block for add (and remove) call and one while sending:

public void send() {
     synchronized(l1) {
         for (<type> x : l1) {
           //send to receivers and put a log in DB
         }
     }
}

depending on you requirements you can also implement something more complex like:

public void send() {
     synchronized(l1) {
         List l2=new ArrayList(l1);
         //clear l1?
     }
     for (<type> x : l2) {
        //send to receivers and put a log in DB
     }
}

and allow a grater degree of concurrency