package com.example.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SharedResourceRW {

	private int counter = 0;
	private final ReadWriteLock lock = new ReentrantReadWriteLock(); // update 1

	// write operation
	public void increment() {
		System.out.println(Thread.currentThread().getName() + " obtained the write lock...");
		lock.writeLock().lock(); // update 2

		try {

//			synchronized (this) {
			// update counter
			counter++;
			System.out.println(Thread.currentThread().getName() + " increment counter to: " + counter);
//			}
			// here maybe contains some codes that may throw exception

			Thread.currentThread().join(); // this may caused deadlock
			
		} catch (Exception e) {
			// TODO: handle exception

		} finally {
			System.out.println(Thread.currentThread().getName() + " released the write lock...");
			lock.writeLock().unlock(); // update 3
		}
	}

	// read operation
	public int getCounter() {
		System.out.println(Thread.currentThread().getName() + " obtained the read lock...");
		lock.readLock().lock();
		try {
			return counter;
		} finally {
			System.out.println(Thread.currentThread().getName() + " released the read lock...");
			lock.readLock().unlock();
		}
	}
}
