1

I am not sure if I have implemented ReentrantReadWriteLock correctly so I would appreciate if you can let me know if I had done anything wrong.

Scenario: Imagine that there are two steps required to make a shirt. The shirts will all be identical.

  1. In the first step, the sewing-tool sews the shirt
  2. In the second step, the buttoning-tool takes the shirt from the first step and put the buttons on it. For simplicity, only one button will be placed on each shirt.

There are a total of 10 sewing-tool and 10 buttoning-tool to be used by step 1 and 2 respectively. The buttons are kept in different shelves in a cupboard.

My aim is to ensure as much concurrency as possible while ensuring that threads wont:

  1. take button from the same shelf
  2. take shirt from the same sewing-tool
  3. deadlock

As such, I have implemented the locks to the following codes:

    Lock firstLock = new ReentrantReadWriteLock();
    Lock secondLock = new ReentrantReadWriteLock();

    if (buttoningTool.ready()) { //check if buttoning-tool is ready

        firstLock.writeLock();

        if (cupboard.getButton()) { //get button from any available shelf and return true if successful

            int shirtNumber = -1;

            for (tempSewingTool : allSewingTools) {

               if (tempSewingTool.shirtReady()) {

                    secondLock.writeLock();

                    shirtNumber = tempSewingTool.takeShirt();

                    secondLock.unlock();

                    break;
               }
            }

            if (shirtNumber != 1) {
                buttoningTool.activate();
            }
        }

        firstLock.unlock();
    }

Question:

  1. Is is necessary to implement the secondLock? This is because the firstLock would have already locked the codes and block other threads.

  2. Assuming that both locks are indeed necessary, is there a need to create two ReentrantReadWriteLock objects to improve concurrency? I took reference from this link - http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

  3. I did read up on threads and interleave but I do not understand what is meant by "interleaved" in the following statement. Can someone explain it to me in layman term?

Quote: there's no reason to prevent an update of c1 from being interleaved with an update of c2

Source: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

Thanks in advance!

Community
  • 1
  • 1
Tay Wen Bin
  • 111
  • 2
  • 11

0 Answers0