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

javathread.jpeg

Future pattern

Suppose you have a method that takes a long time to get the execution result. ** Get a voucher instead of waiting for the execution result **. It doesn't take long to get a voucher. The voucher at this time is called the Future role. The thread that received the voucher will later use the Future role to receive the execution result. If the execution result is available, you will receive it immediately, and if not, you will wait until you can.

(See this manual for the entire code)

Main.java


public class Main { 
    public static void main(String[] args) { 
        ...
        Host host = new Host(); 
        Data data1 = host.request(10, 'A'); 
        Data data2 = host.request(20, 'B'); 
        Data data3 = host.request(30, 'C'); 

        try { 
            Thread.sleep(2000); 
        } catch (InterruptedException e) { 
        } 
 
        System.out.println("data1 = " + data1.getContent()); 
        System.out.println("data2 = " + data2.getContent()); 
        System.out.println("data3 = " + data3.getContent()); 
    } 
}

Host.java


public class Host { 
    public Data request(final int count, final char c) { 
        final FutureData future = new FutureData();  //Create a voucher

        new Thread() { 
            public void run() { 
                RealData realdata = new RealData(count, c); 
                future.setRealData(realdata); 
            } 
        }.start(); 

        return future;  //Return voucher
    } 
}

Data.java


public interface Data { 
    public abstract String getContent(); 
}

Future.java


public class FutureData implements Data { 
    private RealData realdata = null; 
    private boolean ready = false; 
    public synchronized void setRealData(RealData realdata) { 
        if (ready) { 
            return;     // balk 
        } 
        this.realdata = realdata; 
        this.ready = true; 
        notifyAll(); 
    } 
    public synchronized String getContent() { 
        while (!ready) { 
            try { 
                wait(); 
            } catch (InterruptedException e) { 
            } 
        } 
        return realdata.getContent(); 
    } 
}

The Host class first creates an instance of FutureData. This instance is the return value. Next, start a new thread and create an instance of RealData in it. It takes time to create an instance of RealData. Once you have an instance, call the setRealData method to set it in your FutureData instance.

The FureData class is a voucher class. The realData field is a field that holds an instance of RealData that will be created. This field is assigned by the setRealData method. The getContent method is a method for getting the actual data. Wait for realdata to be set by setRealData. If it is set, it returns immediately, and if it is not set, it waits. Threads waiting in wait are woken up by notifyAll calling in setRealData.

Character

Client role The Client role makes a request to the Host role and immediately receives the VirtualData role as a result (return value). The VirtualData role received here is actually the Future role. The Client role does not need to know whether the return value is a RealData role or a Future role. In the sample program, the Main class played this role.

Host role The Host role creates a new thread and begins to create the RealData role. On the other hand, the role of Client returns the role of Future as the role of Virtual Data. In the sample program, the Host class played this role.

Virtual Data role The VirtualData role is a role that equates the Future role with the RealData role. In the sample program, the Data interface played this role.

Real Data role The RealData role is a role that represents actual data. It takes time to create this object. In the sample program, the RealData class played this role.

Future role The Future role is a role passed from the Host role to the Client role as a voucher for the RealData role. The Future role behaves as a Virtual Data role for the Client role. When operated from the Client role, the thread waits with wait until the RealData role is completed. In the sample program, the FureData class played this role.

Tips for expanding your thoughts

The role of Future that can't wait It is also possible to implement the getContent method asynchronously. Instead of the confusing story of creating a new thread in the getContent method, you can use the Balking pattern to "go home if you can't."

Callbacks and Future Patterns If you want to wait for the completion of processing and get the return value, you can think of a method called ** callback **. Callback is a method in which the thread started by the Host role when the processing is completed calls back the method of the Client role.


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) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 6) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 7) Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 8) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 9) Summary of "Design Patterns Learned in Java Language (Multithreaded Edition)" (Part 10)

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)
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
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
[For beginners] Summary of java constructor
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
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)