/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aika;

/**
 *
 * @author Lukas Molzberger
 */
public class ReadWriteLock {

    private int readers = 0;
    private int writers = 0;
    private int writeRequests = 0;
    private Thread writerThreadId = null;

    private Object writeLock = new Object();

    public void acquireWriteLock() {
        try {
            synchronized (this) {
                writeRequests++;
                while (readers > 0) {
                    wait();
                }
            }

            synchronized (writeLock) {
                Thread t = Thread.currentThread();
                if(writerThreadId != t) {
                    while (writers > 0) {
                        writeLock.wait();
                    }
                    writerThreadId = t;
                }
                writers++;
            }
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }


    public synchronized void acquireReadLock() {
        try {
            while (writeRequests > 0) {
                wait();
            }
            readers++;
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void releaseWriteLock() {
        synchronized (writeLock) {
            writers--;
            if(writers == 0) {
                writerThreadId = null;
                writeLock.notify();
            }
        }
        synchronized(this) {
            writeRequests--;
            if(writeRequests == 0) {
                notifyAll();
            }
        }
    }


    public synchronized void releaseReadLock() {
        readers--;
        if(writeRequests > 0 && readers == 0) {
            notifyAll();
        }
    }
}
@@ -988,22 +988,20 @@
 private 
-Thread
+long
  writerT
@@ -1010,20 +1010,18 @@
 eadId = 
-null
+-1
 ;%0A%0A    p
@@ -1337,16 +1337,16 @@
     
-Thread t
+long tid
  = T
@@ -1366,16 +1366,24 @@
 Thread()
+.getId()
 ;%0A      
@@ -1414,16 +1414,18 @@
 dId != t
+id
 ) %7B%0A    
@@ -1564,16 +1564,18 @@
 adId = t
+id
 ;%0A      
@@ -2140,12 +2140,10 @@
 d = 
-null
+-1
 ;%0A  

use the thread id in the read write lock