Lab 7 - Example 1: Multiples Of 7 Filter

Example of Pipes and Filters

This filter removes all the numbers except multiples of 7 - Download the code

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

public class NumbersGenerator extends Thread {
    private Pipe pipe = null;
 
    public NumbersGenerator(Pipe _pipe) {
        pipe = _pipe;
    }
 
    public void run() {
        for (int i = 1; i<= 100; i++)
            pipe.put(new Integer(i));
        //use -1 to signal that there is no more input
        pipe.put(new Integer(-1));
    }
}

The Multiples of 7 Filter

public class MultiplesOf7Filter extends Thread {
    private Pipe pipe = null;
 
    public MultiplesOf7Filter(Pipe _pipe) {
        pipe = _pipe;
    }
 
    public void run() {
        int number = 0;
        while(true) {
            try {
                number = (Integer) pipe.get();
            } catch (InterruptedException iex) { }
 
            if (number == -1) //end of numbers in the pipe
                break;
            //check if the number is multiple of 7 and print it
            if (number % 7 == 0)
                System.out.println(number);
        }
    }
}

The Main program - which starts the generator and the filter

public class MultiplesOf7Main {
 
    public static void main(String[] args) {
        //create the shared pipe
        Pipe pipe = new PipeImpl();
 
        //create the generator and pass the shared pipe object to it
        Thread numbersGenerator = new NumbersGenerator(pipe);
 
        //create the filter and pass the shared pipe object to it
        Thread multiplesOf7Filter = new MultiplesOf7Filter(pipe);
 
        //start the generator and the filter
        numbersGenerator.start();
        multiplesOf7Filter.start();
     }
}