package com.example.lock;

import java.util.concurrent.locks.ReentrantLock;

public class LockSharedResource {

	private int counter = 0;
	private final ReentrantLock lock = new ReentrantLock();

	public void increment() {
		System.out.println(Thread.currentThread().getName() + " obtained the lock...");
		lock.lock();

		try {
			// update counter
			counter++;
			System.out.println(Thread.currentThread().getName() 
					+ " increment counter to: " + counter);

			// here maybe contains some codes that may throw exception
			
		} finally {
			System.out.println(Thread.currentThread().getName() + " released the lock...");
			lock.unlock();
		}
	}

	public int getCounter() {
		return counter;
	}
}
