-2

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.

gany
  • 3
  • 2
  • Your code should at least show one of the options you cannot decide between. – llogiq Jun 11 '15 at 10:39
  • Choosing your suitable synchronized collection and the synchronization strategy is not always trivial, it depends also on the rate of read / write operations, whether there are more reads than writes or vice versa. And... you want to synchronize not only your *send* method (basically your *read* operation against the collection *l1*) but also the method which writes into your collection *l1* (*write* operation): that method is missing / undisclosed in your question. – m c Jun 11 '15 at 10:45

1 Answers1

0

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

Giovanni
  • 3,951
  • 2
  • 24
  • 30