Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization pattern

I have a class named "Channel" with two methods defined:

class Channel {

    void read(){...}
    void write(){...}
}

There's an instance of this class used in multi-threaded environment. Several threads periodically read from channel while one thread periodically writes to it. Read operation is thread-safe so that it is ok for several reads to occur simultaneously. However once write operation starts, read threads must be blocked until write operation is finished. It is essential to keep read operations as fast as possible and avoid resource-consuming synchronization routines.

What would be the most appropriate pattern to implement such behaviour? Maybe java classes or libraries to help?

like image 214
andrew.z Avatar asked Feb 03 '12 19:02

andrew.z


People also ask

What is the concept of synchronization?

Synchronization is the coordination of events to operate a system in unison. For example, the conductor of an orchestra keeps the orchestra synchronized or in time. Systems that operate with all parts in synchrony are said to be synchronous or in sync—and those that are not are asynchronous.

What are the types of synchronization?

There are two types of synchronization: data synchronization and process synchronization: Process Synchronization: The simultaneous execution of multiple threads or processes to reach a handshake such that they commit a certain sequence of actions. Lock, mutex, and semaphores are examples of process synchronization.

What is data synchronization example?

Let's see a simple example of data synchronization: Suppose we have added a new popular ringtone to one of the servers of a mobile service provider, so here, data synchronization means that all the service provider servers get identical sets of ringtones.

What is synchronization in data structure?

These data structures are useful when you have shared data that you modify infrequently. A synchronization object, for example, a critical section, causes other threads to wait until the shared resource is available.


1 Answers

Use a ReadWriteLock. It will allow concurrent reads to occur with serial writes. To further satisfy your requirements, an acquisition of a writeLock will prevent any readLock's from making progress until a subsequent release.

class Channel {
    final ReadWriteLock lock = new ReentrantReadWriteLock();

    void read(){
      lock.readLock().lock();
      try{

      }finally{
         lock.readLock().unlock();
      }
    }
    void write(){   
      lock.writeLock().lock();
      try{

      }finally{
         lock.writeLock().unlock();
      }
    }
}
like image 80
John Vint Avatar answered Sep 25 '22 11:09

John Vint