Lab 7 - Example 2 : File Sort Filter

Example 2 : A sort filter

Example 2 - Word Sort using Pipes and filters

The Pipe interface

//interface Pipe
interface Pipe{
    public boolean put(Object obj);
    public Object get() throws InterruptedException;
}

The Pipe Implementation

//PipeImpl.java
import java.util.*;
 
public class PipeImpl implements Pipe{
 
    private List buffer = new ArrayList();
 
    public synchronized boolean put(Object obj){
        boolean bAdded = buffer.add(obj);
        notify();
        return bAdded;
    }
 
    public synchronized Object get() throws InterruptedException{
        while(buffer.isEmpty()) wait(); //pipe empty - wait
        Object obj = buffer.remove(0);
        return obj;
    }
}

The Generator

import java.io.*;
 
public class WordSortGenerator extends Thread {
    private Pipe pipe = null;
 
    public WordSortGenerator(Pipe _pipe) {
        pipe = _pipe;
    }
 
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("words.txt"));
            String word = null;
            while((word = br.readLine()) != null)
                pipe.put(word);
 
            pipe.put(null); //null signals no more input
            br.close();
        }catch (IOException ioex) {
            ioex.printStackTrace();
        }
    }
}

The Filter

import java.io.*;
import java.util.*;
 
public class WordSortFilter extends Thread {
    private Pipe pipe = null;
    private List<String> wordList = new ArrayList<String>();
 
    public WordSortFilter(Pipe _pipe) {
        pipe = _pipe;
    }
 
    public void run() {
        String word = null;
 
        try {
            while ((word = (String) pipe.get()) != null)
                wordList.add(word);
        } catch (InterruptedException intrtex) {}
 
        //now sort the word list
        Collections.sort(wordList);
 
        //print the sorted word list and write it to a file
        try {
            FileWriter fw = new FileWriter("sortedwords.txt");
            for (String s : wordList) {
                System.out.println(s);
                fw.write(s + "\n");
            }
            fw.close();
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
 
    }
}

The main program which creates the shared pipe and starts the generator and the filter

public class WordSortMain {
 
    public static void main(String args[]) {
        //Creat a pipe between a Generator and Filter
        Pipe pipe = new PipeImpl();
 
        //create the Generator and Filter
        Thread wordGenerator = new WordSortGenerator(pipe);
        Thread wordSortFilter = new WordSortFilter(pipe);
 
        //start the generator and the filter
        wordGenerator.start();
        wordSortFilter.start();
    }
}

How to run

Put the words.txt file in the directory where you are running this code since the WordsGenerators depends on this file