Java Reentrant Lock

ReentrantLock implements the lock interface to provide Mutual Exclusion. It uses the bridge pattern.

It inherits functionality from the AbstractQueuedSynchronizer class which provides a framework for implementing blocking locks and synchronizers that rely on First In, First Out or FIFO wait queues.

It implements several lock acquisition models via its common interface. It optionally implements fair or non-fair lock acquisition model. If the fair paraameter pass, so the ReentrantLock instructor is true, then access is always granted to the longest waiting thread. However if it is false or if the default constructor is used, a lock does not guarantee any particular access order.

Effective Java tip no 2

Effective Java Notes:  CONSIDER A BUILDER WHEN FACED WITH MANY CONSTRUCTOR PARAMETERS

Constructors with large number of optional parameters do not scale too well.

Consider the following class

class Appointment {
    String appointmentTitle; //Mandatory
    Date appointmentStartTime; //Mandatory
    Date appointmentEndTime; //Optional
    ArrayList < Contact > invitedPeople; //Optional
    String description; //Optional
    ArrayList < Task > toDoList; //Optional

    ////////Constructor with two parameters
    public Appointment(String appointmentTitle, Date appointmentStartTime) {
      ...
    }

Print Last n sentences from a file java

My version of program :- Print Last n sentences / lines from a file java


Open to a better solution. Just a trial
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.io.RandomAccessFile;  
 import java.util.logging.Level;  
 import java.util.logging.Logger;  
 public class PrintLastNSentences {  
   public void printLastNSentences(int n) {  
     try {  
       /*creating a simple file */  
       File file = new File("/home/jasleen/d.txt");  
       FileWriter fw = new FileWriter(file);  
       for (int i = 0; i < 100000; i++) {  
         fw.append("\nAs Macbeth takes a journey, so does his speech and its punctuation. Note the increasingly long sentences as Macbeth delves deeper into the horror and chaos of the contemplated deed. The first complete sentence is nearly five lines. The next sentence is over nine lines. And if, for the purpose of analyzing this speech, we consider the semicolons and colons to serve the same purpose as periods (which they could, depending on the actor), then we see even more clearly the escalation of sentence length. While Macbeth begins with a simple five-word phrase (\"He's here in double trust\") he culminates with a 36-word sentence (ending with \"drown the wind.\").");  
       }  
       fw.close();
       /*Using a RandomAccessFile to seek the file*/  
       RandomAccessFile raf = new RandomAccessFile(file, "rw");  
       /*Retreiving the length of the file and subtracting by   
        1 to seek to the last character of the file*/  
       long pointer = file.length() - 1;  
       /*Using a StringBuilder to store the setence character by character.   
        Not used String because String is immutable*/  
       StringBuilder sb = new StringBuilder();  
       int linecount = 0;  
       /*Running the loop till we have reached a point where no more characters  
        are left to read or 10 lines have been processed*/  
       while (pointer != -1 && linecount < n) {  
         /*Seeking to the current poistion*/  
         raf.seek(pointer);  
         /*Reading the byte*/  
         int aByte = raf.read();  
         /*Checking to see if the current character is a new line character*/  
         if (((char) aByte) != '\n') {  
           sb.insert(0, (char) aByte); //here we are inserting the char at first position  
         } else {  
           if (sb.length() > 1)///This is a check to avoid blank sentences  
           ///It can be removed if blank sentence are also allowed.  
           {  
             System.out.println(sb.toString());  
             sb.delete(0, sb.length()); //This is to empty the string builder  
             linecount++;  
           }  
         }  
         pointer--;  
       }  
       raf.close();//Closing the file after reading  
     } catch (FileNotFoundException ex) {  
       Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);  
     } catch (IOException ex) {  
       Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);  
     }  
   }  
   public static void main(String args[]) {  
     new PrintLastNSentences().printLastNSentences(10);  
   }  
 }  

Merge Sort implementation java

Merge sort is a sorting algorithm that splits the collection into two halves and sorts each half and then merging the two halves. Consider the following example.


Following is the java implementation of the algorithm in java.

public class MergeSort {

    public MergeSort(Integer a[]) {
        this.a = a;
    }
    Integer a[];

    public void merge(int p, int q, int r) {
        int n1 = q - p + 1;
        int n2 = r - q;
        Integer L[] = new Integer[n1 + 1];
        Integer R[] = new Integer[n2 + 1];
        for (int i = 0; i < n1; i++) {
            L[i] = a[p + i];

        }
        for (int j = 0; j < n2; j++) {

            R[j] = a[q + j + 1];
        }
        L[n1] = Integer.MAX_VALUE;
        R[n2] = Integer.MAX_VALUE;
        int i = 0;
        int j = 0;
        for (int k = p; k <= r; k++) {
            if (L[i] < R[j]) {
                a[k] = L[i];
                i = i + 1;
            } else {
                a[k] = R[j];
                j = j + 1;
            }
        }
    }

    public void mergeSortPass(int p, int r) {
        if (p < r) {
            int q = (p + r) / 2;
            mergeSortPass(p, q);
            mergeSortPass(q + 1, r);
            merge(p, q, r);
        }
    }

    public void mergeSort() {
        mergeSortPass(0, a.length - 1);
    }

}

JUnit test for MergeSort

import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;

public class MergeSortTest {

    private Integer[] numbers;
    private final static int SIZE = 7;
    private final static int MAX = 20;

    @Test
    public void testMergeSort() {
         for (int i = 0; i < 200; i++) {
            numbers = new Integer[SIZE];
            
            Random generator = new Random();
            for (int a = 0; a < numbers.length; a++) {
                numbers[a] = generator.nextInt(MAX);
            }
            Integer copy[]=new Integer[SIZE];
            System.arraycopy(numbers, 0, copy, 0, numbers.length);
            MergeSort ms=new MergeSort(numbers);
            ms.mergeSort();
            Arrays.sort(copy);
            assertArrayEquals(copy, numbers);
        }

    }
}
Reference- Introduction To Algorithms