In the previous post in this sequence (Producer and Consumer) we got to the point of getting the Ring Buffer class to work when used without threads. Now let’s see if we can make the class thread safe. There are at least a couple ways to get this done.
I will try to get it done with the use of a Mutex. By the way, it seems Java does not provide a Mutex class :o( A mutex is an inter process communication primitive. In Java there is a Semaphore and a Lock. At this time I will go with a Semaphore and use it as a Mutex. Based on my experience, operating systems tend to provide a single type of lock. The rest tend to be implemented based on it. That said; there are two basic types of locks. One is a spin lock and the other is implemented using some type of queue. In the first the thread enters a loop using the CPU polling for the release of the lock. This is quite expensive and does not let the thread get other things done. It tends to use the entire quantum for the thread. On the ones implemented with a queue, the lock is checked and if not available, the thread is put in a queue waiting for the mutex to be released. The thread sleeps until access to the mutex is granted. Continue reading “Producer and Consumer – Part II”