[Java 8] (10) Using lambda to complete function combination, map-reduce and parallelization

Source: Internet
Author: User

GOOD TEXT recommended!!!!!

See the original: http://blog.csdn.net/dm_vincent/article/details/40856569

There are two programming paradigms for object-oriented programming (OOP) and functional programming (FP, functional programming) in Java 8. In fact, the two paradigms do not contradict each other, but focus on differences. In OOP, the focus is on modeling the problems that need to be addressed through a rich type system, while the FP focuses on calculating with higher-order functions and lambda expressions. So we can combine the two together and propose a more elegant solution to the problem.

In this article, you will learn how to combine several function units into one map-reduce mode application by using function composition. It also describes how to parallelize the entire computational process.

Using function combinations

When using functional programming, the function is the unit that makes up the program. By organizing functions in the form of higher-order functions, the invariance (immutability) can be effectively improved, thus reducing the state change of the program and ultimately making parallelization easier.

The following diagram reflects the style of pure object-oriented design and hybrid design (object-oriented and functional).

In OOP, the state of an object changes continuously as the program progresses, but there is always only one object. In FP, after each object is processed by a function, it gets a new object, and the original object does not change.

Here is a small example that gives you a basic understanding of this hybrid programming paradigm. Let's say we have some stock codes that require stocks with a stock price greater than $100 and sort them:

 public class tickers {public static final list<string> symbols = arrays.aslist ( "AMD",  "HPQ",  "IBM",  "AAPL",  "CSCO",  "Intu",  "VRSN",  "YHOO");               

For each stock code, you can get the corresponding share price by invoking the following program with the Web service provided by Yahoo!:

PublicClassyahoofinance {PublicStaticBigDecimalGetPrice (FinalStringTicker) {try {FinalURL URL=NewURL ("Http://ichart.finance.yahoo.com/table.csv?s="+ ticker);FinalBufferedReader Reader= new bufferedreader (new .openstream ())); final string data = reader.lines () .skip (1) .findfirst () .get (); final string[] dataitems = data.split ( return new bigdecimal (Dataitems[dataitems-1]); } catch (exception ex) {throw new  RuntimeException (ex); } }} 

Finally, get the answers we need with a bunch of actions:

BigDecimal ("the");  System.println (tickers-yahoofinance. GetPrice (symbol).CompareTo (0). Sorted (). Collect (Joining (",")));          

This is the application of a mixed paradigm that encapsulates the main computational logic through methods, and then uses these functions to model object-oriented based on the type they belong to, such as the GetPrice method belongs to type Yahoofinance. Finally, use the stream type and lambda expression to complete the calculation logic that needs to be executed to get the final result.

The benefits of encapsulating the computational logic into a chain of function calls are:

    • More concise, the code is much less, so the code is easier to understand
    • Improves object invariance (immutability), making it easier to parallelize
    • Each ring in the call chain is easily reused, such as filter,sorted, etc.
Using Map-reduce

As the name implies, Map-reduce is actually divided into two steps:

    1. Map stage: Manipulating elements in a collection
    2. Reduce phase: Merge the results from the previous step to get the final result

It is because of the simplicity of this model and the ability to maximize the use of multicore processors, so it has been widely watched.

For example, what should we do when we need to get a stock with a stock price that is less than $500 in the highest price? First, we start with the most familiar command-style code.

Preparatory work

First, we need to do a basic modeling of this problem, which is the process of object-oriented design. It is easy to get the following entity type:

Stockinfo {    stockinfo (String. Format ("Ticker:%s Price:%g", ticker, price); }}

At the same time, some tools are needed to help us solve this problem:

    1. The corresponding entity information is obtained through the stock code. We can do this by using the GetPrice method defined in the Yahoofinance described earlier.
    2. Judging if the price of a stock is less than a certain value, it can be implemented through the predicate function interface, which is a high-order function that generates a lambda expression as a threshold value and returns.
    3. Used to compare the methods of acquiring objects with a higher stock price in two stock price entity objects.

The following are implemented separately:

PublicClassStockutil {PublicStaticStockinfoGetPrice (FinalStringTicker) {ReturnNewStockinfo (Ticker,Yahoofinance. GetPrice (ticker)); }PublicStaticpredicate<Stockinfo>Ispricelessthan (final int price) {return Stockinfo -> stockinfo.price.compareto ( bigdecimal.valueof (price)) < 0;} public static stockinfo pickhigh ( final stockinfo stockinfo1, final stockinfo stockinfo2) {return stockinfo1.price< Span class= "O" >.compareto (stockinfo2.price) > 0  StockInfo1 : StockInfo2;}}          
Imperative style

With the above preparatory work, we can begin to implement it. The first is imperative-style code, which is also the most familiar way:

Finallist<Stockinfo> Stocks=NewArraylist<> ();ForString symbol:Tickers. Symbols) {Stocks. Add (Stockutil. GetPrice (symbol));}Finallist<Stockinfo> stocksPricedUnder500=NewArraylist<> ();Finalpredicate<Stockinfo> isPriceLessThan500=Stockutil.ispricelessthan (500); stockinfo stock : Stocks) {if (isPriceLessThan500 .test (stock) Stockspricedunder500.add (stock);} stockinfo highpriced = new stockinfo ( bigdecimalfor (stockinfo stock : stocksPricedUnder500) {highpriced = stockutil.pickhigh (highpriced, stock);} system.out.println ( "high priced under Span class= "o" >+ highpriced);              

The code above completes the following tasks:

    1. The first is to get stock price information according to the stock code, and then put the stock price entity into a list object.
    2. The collection is then traversed once to get all the price entities with prices below $500.
    3. Iterate over the results in step 2 to get the entity with the highest stock price.

Of course, if you feel that there are too many loops, we can also merge them into a loop:

Stockinfo highpriced=NewStockinfo ("",BigDecimalfinal predicate<stockinfo> isPriceLessThan500 = stockutil.ispricelessthan (500); string symbol : tickers.symbols) {stockinfo stockinfo = stockutil.getprice (symbol); if (Ispricelessthan500.test (stockinfo)) highpriced = stockutil.pickhigh (highpriced, stockinfo);} system.out.println ( "high priced under Span class= "o" >+ highpriced);              

You can see that just using a lambda expression of the predicate type can make the code much less space. However, the above code is still an imperative style and will still implement the computational logic by modifying the variables. More importantly, the above code reusability is poor, when we need to change the filter conditions, we need to modify it.

A better approach would be to encapsulate all the changed code into separate small modules, and then use the functional style code to connect them.

Functional style

After using the functional style, the code does not see the trace for the For loop:

void findhighpriced (stream<= symbols. Map (stockutil:: GetPrice). Filter (stockutil  . Ispricelessthan.reduce (stockutilSystem.println (+ highpriced);}  

The Map,filter and reduce methods replace three for loops respectively, and the code becomes unusually concise. In addition to brevity, it is more important that this code can be parallelized at any time.

The above calculation logic can be expressed using:

Parallelization of

Before implementing Parallelization, let's look at a few of the actions above: map,filter and reduce.

Obviously, the speed of the map method is the slowest because it relies on external web Service. However, it can also be noted that for each stock code, to obtain their corresponding share price information is completely independent, so you can consider this part of parallelization.

There are two things to consider when you need to make a piece of code run in parallel:

    • How to complete?
    • How do I do it in the right way?

For the first aspect, we can do this using the various concurrency-related libraries available in the JDK. For the second aspect, we need to consider the characteristics of this code. For concurrent programs, the first thing to avoid is a race condition (Race Condition), which can occur when multiple threads try to update an object or a variable. So for this kind of update, we need to be careful to maintain its thread security. Conversely, if the state of an object is immutable (state variables are modified to final), then the soil that breeds the race condition ceases to exist, which is precisely what functional programming has repeatedly emphasized and advertised.

So, after the best practices of functional programming are strictly adhered to, parallelization is nothing more than a kick-off:

The invocation mode of serial execution findhighpriced (tickers. Symbols. Stream ());  The invocation mode of parallel execution findhighpriced (tickers. Symbols. Parallelstream ());      

Just by replacing the stream method with the Parallelstream method, the code is plugged into parallel wings. There is no need to think about how to do this, nor do you need to consider various risks such as race conditions.

The definition of these two methods can be found in the collection interface, which also means that not only the list type can be easily implemented in parallel, it is also very convenient for other types that implement the collection interface:

stream<e> Stream () {    streamsupportfalse);} stream<Streamsupporttrue);}     

This is not intended to be an analysis of the underlying implementation principle, but when using parallelstream, it means that methods like Map,filter are run in parallel, while worker threads come from a pool of threads at the bottom. These details have been packaged pretty well, and as developers only need to make sure that your code does adhere to the rules of the game.

The performance comparison of the serial and parallel modes is as follows:

Serial Parallel
24.325s 5.621s

By simply changing a method, the performance is improved by nearly 5 times times! This may be one of the charms of functional programming.

So, there are a few questions to consider when choosing from the stream and Parallelstream methods:

    1. Do you need parallelism?
    2. are tasks independent of each other? Does it cause any race conditions?
    3. Does the result depend on the order in which the tasks are called?

For question 2, if the tasks are independent, and the code does not involve a state of the same object or an update operation on a variable, then the code can be parallelized.

For problem 3, because the order in which tasks are executed in a parallel environment is indeterminate, parallelization may not give the correct results for tasks that depend on order.

For question 1, before you answer this question, you need to figure out what the problem is, how big the data is, and what is the characteristic of the calculation? Not all problems are suitable for use with concurrent programs, such as when the amount of data is small, sequential execution is often faster than parallel execution. After all, it takes time to prepare the thread pool and other related resources.

However, Parallelization is a good choice when tasks involve I/O operations and the tasks do not depend on each other. In general, after parallelization of such programs, the execution speed increases by several levels, as in the example above.

[Java 8] (10) Using lambda to complete function combination, map-reduce and parallelization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.