Java implementation of Producer - Consumer Problem using Blocking Queue

             Producer creates data and make it into a buffer. A consumer who always take the data from the buffer.

Let us consider a textile manufacturer. He/she is the producer. Customer is the consumer.

Problem:

When the producer creates more products or no products.

When a consumer doesn’t take the product.

So the solution is implemented in java as Blocking Queue.

This queue provides the solution for this problem.

It is available in java.util.concurrent package.

Let us create the code.

Java implementation:

// Import the built in package

import java.util.concurrent.*;

//class producer declaration and function ‘run()’ defintion

class PCP_Producer implements Runnable {

    private BlockingQueue<Integer> queue1;

    public PCP_Producer(BlockingQueue<Integer> q) {

        this.queue1 = q;

    }

    @Override

    public void run() {

        int i = 0;

        try {

            while (true) {

                System.out.println("The Produced data is  " + i);

                queue1.put(i++);

                Thread.sleep(500); // let us make some time to simulate production

            }

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

    }

}

//Class Consumer declaration and method ‘run()’ definition.

class PCP_Consumer implements Runnable {

    private BlockingQueue<Integer> queue1;

    public PCP_Consumer(BlockingQueue<Integer> q) {

        this.queue1 = q;

    }

    @Override

    public void run() {

        try {

            while (true) {

                Integer item = queue1.take();

                System.out.println("The Consumed data is: " + item);

                Thread.sleep(1000); // make the time to Simulate the consumption

            }

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();

        }

    }

}

//main class. Object creation and function call.

public class PCP_Example {

    public static void main(String[] args) {

        BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<>(5);

        Thread pcp_producer = new Thread(new PCP_Producer(queue1));

        Thread pcp_consumer = new Thread(new PCP_Consumer(queue1));

        pcp_producer.start();

        pcp_consumer.start();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac PCP_Example.java

C:\raji\blog>java PCP_Example

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Produced: 4

Consumed: 3

Produced: 5

Consumed: 4

Consumed: 5

Here, the sample implementation of Producer consumer Problem using Blocking Queue is done. Hope, this code will help you. Keep Coding!!!

Data Structures -An Introduction with Basic Examples

 Let’s consider a social media application. You create an account with your basic details and receive many follow requests, which you accept. Your follower’s list is then organized like a data structure.

Data structures are used to store and manage data in an organized and efficient way.

Everyday Examples: Think of a bookshelf, a wardrobe, or a parking area in a mall—each one organizes different types of items systematically.

Definition:

A data structure is a way of organizing, processing, and retrieving data effectively.

How are data structures classified?

They are broadly categorized into two types:


1. Linear Data Structures

Here, data is stored sequentially and accessed one by one.

  • Array: A basic linear data structure where elements are stored in contiguous memory locations.
  • Linked List: Composed of nodes that are connected using pointers or links.
  • Stack: Follows the Last-In, First-Out (LIFO) principle.
  • Queue: Follows the First-In, First-Out (FIFO) principle—like people standing in a queue.

2. Non-linear Data Structures

The data isn’t stored sequentially; instead, it forms hierarchical or interconnected structures.

  • Tree: Has a root node and child nodes, representing a parent-child relationship.
  • Graph: Consists of nodes (vertices) connected by edges, useful for modeling networks.

Why are data structures important?

They are the backbone of data organization. Proper use of data structures ensures that data can be stored, accessed, and manipulated efficiently.


Real-life Examples of Data Structures:

  • Bank transactions: Utilize stacks and queues to manage operations.
  • Travel apps: Rely on graph structures for route optimization.
  • Social media apps: Often use tree structures to represent follower hierarchies.

Hope ,this introduction will help you to understand Data structures.

Java implementation of MVC Pattern

A Design pattern which separates the data logic, UI (User Interface) and processing. Here, data logic deals with Model. UI is for View. The processing can be done by Controller.

This design pattern is useful for Web Application Architecture.

Model-View-Controller (MVC) separates data logic (Model), UI (View), and processing (Controller).

The technical implementation is given below.

Java implementation:

This program implements four classes namely MVC_Model, MVC_View, MVC_Controller and MVCEg.

‘Class MVC_Model’ :

  • It creates and holds the data.
  • Member function :get_Data()
  • Member variable : m_data.

‘Class M_View’:

  • It displays the data to user.
  • Member function: displayIt( String msg). where ‘msg’ is a member variable as String.

‘Class M_Controller’:

  • This process the data.
  • It initialises the values to above two classes.
  • Member function: ‘updateItView()’.
  • Here, this function gets the data from MVC_Model and use the MVC_View function displayIt().

‘Class MVCEg’:

  • It creates the objects for all classes and make a function call.

Program:

//Class1 for creating data logic

class MVC_Model {

    private String m_data = "MVC Example Sample text!";

    public String get_Data() {

        return m_data;

    }

}

//class 2 is for UI.

class MVC_View {

    public void displayIt(String msg) {

        System.out.println("Displaying the message: " + msg);

    }

}

//Class 3 is for Processing.

class MVC_Controller {

    private MVC_Model model;

    private MVC_View view;

    public MVC_Controller(MVC_Model model, MVC_View view) {

        this.model = model;

        this.view = view;

    }

    public void updateItView() {

        view.displayIt(model.get_Data());

    }

}

//Main Class to create objects and function calls

public class MVCEg {

    public static void main(String[] args) {

        MVC_Model model = new MVC_Model();

        MVC_View view = new MVC_View();

        MVC_Controller controller1 = new MVC_Controller(model, view);

        controller1.updateItView();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac MVCEg.java

C:\raji\blog>java MVCEg

Displaying the message: MVC Example Sample text!

Usage of this code: It is useful in Spring MVC, React and Angular Web frameworks.

This is way of creating MVC Design pattern in java. Hope, this code will useful to you.Keep Coding!!!

Java implementation of Strategy Pattern

     This design pattern deals with Dynamic Behavior Selection. Without modifying the code, the pattern swaps the behavior at run time.

Technical implementation:

This implementation starts with creating interface.

  • ‘interface’ PaymentMethod is developed with a member function payIt().payIt() has a member variable ‘amount’.
  • Two classes “CCPayment” and “BankPayment” are derived from interface PaymentMethod.
  • “payIt() method displays the amount paid message to the user.
  • PaymentContext is a class for developing this design pattern.
  • A private member variable’ meth’ is created for PaymentMethod interface.
  • ‘setMethod()’ initialises the variable ‘meth’.
  • ‘processIt()’ calls the function ‘payIt()’ with ‘amount’ value.
  • Finally, a sample class with main () function is written.
  • An object is created for PaymentContext.
  • First,setMethod is initialised with CCPayment object.
  • It calls the payIt() functions with amount value.
  • Again,the setMethod is initialised with BankPayment object.
  • It calls the payIt() function with amount value.

Program:

interface PaymentMethod {

    void payIt(int amount);

}

class CCPayment implements PaymentMethod {

    public void payIt(int amount) {

        System.out.println("The amount: "+amount + "is paid via Credit Card.");

    }

}

class BankPayment implements PaymentMethod {

    public void payIt(int amount) {

        System.out.println("The amount: " + amount + " is paid via Bank account.");

    }

}

class PaymentContext {

    private PaymentMethod meth;

    public void setMethod(PaymentMethod meth) {

        this.meth = meth;

    }

    public void processIt(int amount) {

        meth.payIt(amount);

    }

}

public class sample {

    public static void main(String[] args) {

        PaymentContext pm = new PaymentContext();

        pm.setMethod(new CCPayment());

        pm.processIt(5000);

        pm.setMethod(new BankPayment());

        pm.processIt(1500);

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac sample.java

C:\raji\blog>java sample

The amount: 5000 is paid via Credit Card.

The amount: 1500 is paid via Bank account.

This design pattern is useful in payment gateways. It also useful in developing AI algorithms.

That’s all. The java program to implement the Strategy Design Pattern is done. Hope, this code sample is useful to you. Keep Coding!!!

Adapter Pattern implementation in java

               It is a structural pattern which organizes the classes and objects. Adapter Pattern is one of its types. This pattern makes the different interfaces to run together.

Java implementation:

              It connects the incompatible interfaces to work together. Let us create two interfaces.

  • One is MPlayer (A media player). It has a play () method.
  • Another interface is AMediaPlayer. It also has playMP4() method.
  • A class (MP3Player) is created for MPlayer interface.
  • ‘play()’ method is used to play Mp3 file.
  • In the same way, another class(MP4Player) is created for AMediaPlayer interface.
  • The ‘playMP4()’ definition is written.
  • Adapter class is created with method. It connects both of the interfaces.
  • A public class ‘MPPlay’ is developed with main() class.
  • Objects are newly created for both classes. ‘play()’ and ‘playMP4()’ functions are called to display the result.

Program:

// interface 1

interface MPlayer {

    void play(String fname);

}

//class1 with method1

class MP3Player implements MPlayer {

    public void play(String fname) {

        System.out.println("Playing MP3 file: " + fname);

    }

}

//interface 2

interface AMediaPlayer {

    void playMP4(String fname);

}

//class 2 with method2

class MP4Player implements AMediaPlayer {

    public void playMP4(String fname) {

        System.out.println("Playing MP4 file: " + fname);

    }

}

//Adapter class definition

class MAdapter implements MPlayer {

    private AMediaPlayer aMediaPlayer;

    MAdapter(String format) {

        if (format.equalsIgnoreCase("mp4")) {

            aMediaPlayer = new MP4Player();

        }

    }

    public void play(String fname) {

        aMediaPlayer.playMP4(fname);

    }

}

//main() function

public class MPPlay {

    public static void main(String[] args) {

        MPlayer player1 = new MP3Player();

        player1.play("Manos Mars - The Tunning.mp3");

        MPlayer player2 = new MAdapter("mp4");

        player2.play("j1.mp4");

    }

}

The program is developed.

Output:

Compile and run the program to get the output.

C:\raji\blog>javac MPPlay.java

C:\raji\blog>java MPPlay

Playing MP3 file: Manos Mars - The Tunning.mp3

Playing MP4 file: j1.mp4

This is the java implementation of Adapter pattern. Hope, this code will helpful to you. Keep Coding!!!

Factory Design Pattern in java

              It is a design pattern which creates objects at run time. It makes the user to develop objects. Even, it does not specify the exact class.

Program implementation:

Here, an interface Fruit is created with findColor() member function.

  • Two more classes are created using this interface. One is for Apple class and another one is guava.
  • A new class “FruitBasket” is developed with a member function getFruit().
  • The main class “FruitEg” is written with main() function.
  • ‘findColor()’ – This function displays the colour of the fruit.
  • ‘getFruit()’ – it gets the type of fruit. Using a if loop, check for fruit type and create the new object.
  • ‘main()’ – this function creates the object for fruit class and call the findColor().

Program:

interface Shape {

    void findCorners();

}

 class Square implements Shape {

    public void findCorners() {

        System.out.println("Square has four Corners");

    }

}

 class Triangle implements Shape {

    public void findCorners() {

        System.out.println("Triangle has three Corners");

    }

}

 class Shapes {

    public static Shape getShape(String type) {

        if (type.equalsIgnoreCase("Square")) return new Square();

        else if (type.equalsIgnoreCase("Triangle")) return new Triangle();

        return null;

    }

}

 public class ShapesEg {

    public static void main(String[] args) {

        Shape myshape = Shapes.getShape("Square");

        myshape.findCorners();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac ShapesEg.java

C:\raji\blog>java ShapesEg

Square has four Corners          

This design Pattern is useful for frameworks.

That’s it. The Java Program to implement Factory Design Pattern was written and executed successfully. Hope, this code is useful to you.

Design Patterns Introduction and Singleton Pattern implementation in Java

What is Design pattern?

    It gives you a structured approach to solve a common problem in software development. Basically, it gives you a reusable code which is easy to maintain. It is flexible too.

Let us categorize the design patterns.

  • Creational patterns
  • Structural patterns
  • Behavioral patterns

Each of the pattern has its own features given as follows

Creational Patterns:

              As the name suggests, it deals with object creation. For example, Singleton, Builder and Factory design patterns.

Structural Patterns:

              These design patterns deal with classes.The main purpose is to structure the class and relationships are made.

Eg: Adapter, Decorator and Proxy.

Behavioral Patterns:

              This design pattern is made for communication between objects.

Eg: Command, Observer and Strategy.

Let us create Singleton Design Pattern.

Java implementation of Singleton Pattern:

              This design pattern has only one instance across the entire application. Even the user creates more than one instance.

  • Singleton class is created with one instance in1.
  • ‘getInstance() method checks the instance is created or not. If it is not created, it creates the instance here.
  • ‘showMessage()’ displays the message.
  • In the main() function, two instances created. But both are equal.

Program:

class Singleton {

    private static Singleton in1;

    private Singleton() {} // Private constructor

    public static Singleton getInstance() {

        if (in1 == null) {

            in1 = new Singleton();

        }

        return in1;

    }

    public void showMessage() {

        System.out.println("Singleton instance is accessed here!");

    }

}

public class SDPEg {

    public static void main(String[] args) {

        Singleton ob1 = Singleton.getInstance();

        Singleton ob2 = Singleton.getInstance();

        ob1.showMessage();

        System.out.println(ob1 == ob2);

    }

}

Output:

Compile and run the above program to get the output

C:\raji\blog>javac SDPEg.java

C:\raji\blog>java SDPEg

Singleton instance is accessed here!

True

This design pattern is used in Database connections and logging.

This is the way of creating Singleton design pattern in java. Hope, it will be useful to you. Keep Coding!!!!

The producer- consumer Problem in java

    It is an evergreen synchronization problem in operating system. It has two entries. They are

  • ·       Producer
  • ·       Consumer

Producer is the one, which generates the item and adds it to a shared region. Consumer is the one which retrieves the item from the shared region and processes it.

So, synchronization plays a vital role here.

To handle this problem, the method “BlockingQueue” is used.

Technical implementation:

              This implementation creates two threads Producer and Consumer as Runnable.

  • A private final BlockingQueue as integer. In the constructor, initialise the value.
  • In the run() method,insert the value for queue and make the thread to sleep for some time.
  • Similarly, do the above steps for Consumer thread also.
  • Finally, in the main() function, create objects for queue. Using these objects, start the
  • Threads.

Program:

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

class Producer implements Runnable {

    private final BlockingQueue<Integer> queue1;

    public Producer(BlockingQueue<Integer> queue1) {

        this.queue1 = queue1;

    }

    @Override

    public void run() {

        for (int i = 1; i <= 5; i++) {

            try {

                System.out.println("Produced: " + i);

                queue1.put(i); // inserts item to the queue

                Thread.sleep(1000); // Delay

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

            }

        }

    }

}

class Consumer implements Runnable {

    private final BlockingQueue<Integer> queue1;

    public Consumer(BlockingQueue<Integer> queue1) {

        this.queue1 = queue1;

    }

    @Override

    public void run() {

        while (true) {

            try {

                Integer item = queue1.take(); // Retrieves item

                System.out.println("Consumed: " + item);

                Thread.sleep(1500); // Delay

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

            }

        }

    }

}

public class ProducerConsumerEg {

    public static void main(String[] args) {

        BlockingQueue<Integer> queue1 = new LinkedBlockingQueue<>(3);

        Thread producer1 = new Thread(new Producer(queue1));

        Thread consumer1 = new Thread(new Consumer(queue1));

        producer1.start();

        consumer1.start();

    }

}

Output:

C:\raji\blog>javac ProducerConsumerEg.java

C:\raji\blog>java ProducerConsumerEg

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Consumed: 3

Produced: 4

Produced: 5

Consumed: 4

Consumed: 5

This is the way of creating Producer consumer Problem in java. Hope, you are understanding about the concept. Keep Coding!!!