Java ReentrantLock release lock in finally block
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main { static Lock myLock = new ReentrantLock(); static Random random = new Random(); public static void main(String[] args) { for (int i = 0; i < 10; i++) { callFunctionThatHoldsLock();/*ww w . ja va 2 s .c om*/ } } private static void callFunctionThatHoldsLock() { myLock.lock(); try { int number = random.nextInt(5); int result = 100 / number; System.out.println("A result is " + result); FileOutputStream file = new FileOutputStream("file.out"); file.write(result); file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { myLock.unlock(); } } }