Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5)

javathread.jpeg

Guarded Suspension pattern

The Guarded Suspension pattern has names such as ** guarded wait ** and ** spin lock **.

Request.java


public class Request {
     private final String name;
     public Request(String name) {
         this.name = name;
     }
     public String getName() {
         return name;
     }
     public String toString() {
         return "[ Request " + name + " ]";
     }
}

RequestQueue.java


import java.util.Queue;
import java.util.LinkedList;

public class RequestQueue {
    private final Queue<Request> queue = new LinkedList<Request>();
    public synchronized Request getRequest() {
        while (queue.peek() == null) {
            try {
                wait(); //Wait when the queue is empty(Enter the weight set)
            } catch (InterruptedException e) {
            }
        }
        return queue.remove();
    }
    public synchronized void putRequest(Request request) {
        queue.offer(request);
        notifyAll(); //Notify the waiting thread that a request has been placed in the queue
    }
}

ClientThread.java


import java.lang.Math;

public class ClientThread extends Thread {
    private final RequestQueue requestQueue;
    public ClientThread(RequestQueue requestQueue, String name) {
        super(name);
        this.requestQueue = requestQueue;
    }
    public void run() {
        for (int i = 0; i <= 100; i++) {
            Request request = new Request("No." + i);
            System.out.println(Thread.currentThread().getName() + " put " + request);
            requestQueue.putRequest(request);
            try {
                Thread.sleep((int)(Math.random()*10));
            } catch (InterruptedException e) {
            }
        }
    }
}

ServerThread.java


import java.lang.Math; 
 
public class ServerThread extends Thread { 
    private final RequestQueue requestQueue; 
    public ServerThread(RequestQueue requestQueue, String name) { 
        super(name); 
        this.requestQueue = requestQueue; 
    } 
    public void run() { 
        for (int i = 0; i <= 100; i++) { 
            Request request = requestQueue.getRequest(); 
            System.out.println(Thread.currentThread().getName() + " get " + request); 
            try { 
                Thread.sleep((int)(Math.random()*10)); 
            } catch (InterruptedException e) { 
            } 
        } 
    } 
}

Main.java


public class Main { 
    public static void main(String[] args) { 
        RequestQueue requestQueue = new RequestQueue(); 
        new ClientThread(requestQueue, "A").start(); 
        new ServerThread(requestQueue, "B").start(); 
    } 
}

Execution result


...
A put [ Request No.95 ]
B get [ Request No.91 ]
B get [ Request No.92 ]
A put [ Request No.96 ]
A put [ Request No.97 ]
B get [ Request No.93 ]
A put [ Request No.98 ]
B get [ Request No.94 ]
A put [ Request No.99 ]
B get [ Request No.95 ]
B get [ Request No.96 ]
B get [ Request No.97 ]
B get [ Request No.98 ]
B get [ Request No.99 ]
...

ClientThread passes an instance of Request to SeverThread. This is a very simple ** thread-to-thread communication **. ClientThread and ServerThread are called ** active objects **, and RequestQueue are called ** passive objects **.

ClientThread throws a request to the Queue (put) and ServerThread fetches the request from the Queue (get). put and get are synchronized and exclusive.

The getReques method retrieves one of the oldest requests. If there are no requests, wait until another thread makes a putRequest. The condition queue.peek ()! = Null, that is, the condition that Queue is not empty, must be met. Such a condition that must be satisfied is called a ** guard condition ** of the Guarded Suspension pattern.

The putRequest method adds one request. Then notify the waiting thread with notifyAll.

For wait and notify Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 1) See.

As the execution result shows, B (get) does not overtake A (put).

Character

The GuardedObject role is a class that has a guarded method. If the guard condition is met, it will be executed immediately, and if it is not met, it will be waited. The GuardedObjec role may have a method (stateChangingMethod) that changes the state of the instance. In the sample program, the RequestQueue class plays this role, getRequest corresponds to guardedMethod, and putRequest corresponds to stateChangingMethod.


Relation Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 1) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 2) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 3) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 4)

Recommended Posts

Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 10)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 7)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 3)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 9)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 6)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 4)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 2)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 1)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 11)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 12)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 8)
[Java] Summary of design patterns
A quick review of Java learned in class part4
Summary of Java language basics
A quick review of Java learned in class part3
A quick review of Java learned in class part2
I read Hiroshi Yuki "Introduction to Design Patterns Learned in Java Language" (SB Creative)
Java Design Patterns
What I learned in Java (Part 2) What are variables?
A quick review of Java learned in class
Summary of what I learned in Spring Batch
Try design patterns in C language! Memento pattern-Let's memorize the memories of the data
[Java] Basic summary of Java not covered by Progate ~ Part 1 ~
What I learned in Java (Part 3) Instruction execution statement
Summary of how to implement default arguments in Java
Summary of Java support 2018
Java design pattern summary
What I learned in Java (Part 4) Conditional branching and repetition
[Java] Basic summary of Java not covered by Progate ~ Part 2 ยท List ~
Road to Java Engineer Part2 What kind of language is Java?
Read design patterns in Ruby
[Java11] Stream Summary -Advantages of Stream-
[Java] Summary of regular expressions
[Java] Summary of operators (operator)
[Java] Summary of for statements
Summary of Java Math class
Implementation of gzip in java
[Java] Summary of control syntax
Implementation of tri-tree in Java
Summary of java error processing
[Java] Summary of mathematical operations
What I have learned in Java (Part 1) Java development flow and overview
Summary of ORM "uroboroSQL" that can be used in enterprise Java
[For beginners] Summary of java constructor
Summary of [Java silver study] package
Basic usage of java Optional Part 1
thread safe process in java language
AtCoder 400 points algorithm summary (Java edition)
List of members added in Java 9
Creating lexical analysis in Java 8 (Part 2)
List of types added in Java 9
Summary of object-oriented programming using Java
Implementation of like function in Java
Creating lexical analysis in Java 8 (Part 1)