Java thread pool and the use of Countdownlatch __java

Source: Internet
Author: User
Java Multithreading In addition to the direct use of thread and runnable to implement, Jdk5 later provides a more convenient way to use: thread pool (executors), this chapter does not describe what is the thread pool, and thread pool classification and use. This paper mainly introduces the statistical usage of the thread pool in the actual work, and introduces the realization of synchronous lock in Java and contract: Countdownlatch.

1, what is Countdownlatch

The literal translation is the inverted count (Countdown) latch (Latch). Count Needless to say, the meaning of the latch is to prevent progress. This means that the countdownlatch.await () method blocks the current thread before it counts backwards to 0. The role of Countdownlatch is similar to the Thread.Join () method, which can be used for collaboration between a set of threads and another set of threads. For example, the main thread needs a series of preparations before doing a job, and only if the preparation is complete will the main thread continue its work. These preparations are independent of each other, so they can be executed concurrently to improve speed. In this scenario, you can use countdownlatch to coordinate the scheduling between threads. In the era of direct creation of threads (before Java 5.0), we can use Thread.Join (). After JUC appears, because threads in the thread pool cannot be referenced directly, you must use Countdownlatch. The most important method of Countdownlatch is Countdown () and await (), the former is mainly the penultimate, the latter is waiting for the countdown to 0, if not reached 0, only blocking wait.

2, the actual case

Now there is a requirement to traverse the 8 Redis master instances on one machine in the production environment, parse out the 1W records, and remove the dev and ver fields, splice the two fields to the URL, and request a third party service to query. Determine if the corresponding records for Dev and ver exist in another library and return the results. Final statistics: Total number of query records (possibly less than 1W in Redis), number of records not queried.

In this example is a typical thread pool and synchronization of the use of the case, divided into 8 threads of statistics, only when each thread is finished before the final result rollup.

3. Specific code

package com.ua;
import java.net.urlencoder;
import java.util.hashset;
import java.util.list;
import java.util.set;
import java.util.concurrent.countdownlatch;
import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

import org.apache.commons.lang.stringutils;

import com.util.httputil;
import net.sf.json.jsonobject;
import redis.clients.jedis.jedis;

import redis.clients.jedis.scanresult; /**  * ua Statistics  */public class uatest {Jedis jedis = new jedis ("
	192.168.1.5 ",  19001);
	int errorsum = 0;
	int sum = 0;
	
	Set<string> set = new hashset<> (); /**  *  up to 1W Records  *  @param  jedis  */public void scan (Jedis jedis) & nbsp
		{string key =  "Shanghai: Aphone";
		string cursor =  ""; Scanresult<string> scan = null;
		list<string> list = null;
			while  (!cursor.equals ("0"))  {Scan = jedis.sscan (key, cursor);
			List = scan.getresult ();
				for  (string str : list)  {if  (sum >= 10000)  {break;
				} getuid (str);
			sum++;
		} cursor = scan.getstringcursor (); }/**  *  parse every record, get dev and ver node values  *  @param  uid  */public void getuid (S
		TRING&NBSP;UID)  {String res = jedis.get (UID); if  (!
			Stringutils.isempty (res))  {Jsonobject jsonobject = jsonobject.fromobject (res);
			String dev = jsonobject.getstring ("Dev");
			String ver = jsonobject.getstring ("ver");
		Getua (Dev, ver); /**  *  request third party interfaces to determine whether the combination of Dev and ver exists  *  @param  dev  *  @param  ver  */PU Blic void getuA (string dev, string ver)  {string res; try {res = httputil.gethttp ("http://localhost:3000/getUa?test=true&dev="  + 
			Urlencoder.encode (Dev, "utf-8")  +  "&version="  + ver);
				if (Res.indexof ("Error") >=0) {System.out.println (Thread.CurrentThread (). GetName () + "&NBSP;:" +res); Set.add (dev+ "|")
				+ver);
			errorsum++;
		}} catch  (Exception e)  {e.printstacktrace (); } public static void main (String[] args)  {//defines a thread pool size of 8 because there are 8 Redis of master instances Executorserv
		Ice pool = executors.newfixedthreadpool (8);
		The end of the countdown lock, because the thread pool has 8 threads, so also defines 8 thread end lock Count Final countdownlatch latch = new countdownlatch (8);
		Final uatest uatest = new uatest (); for  (int i = 0; i < 8; i++)  {final int tmp =
			 i; runnable runnable = New runnable ()  {@Override public void run ()  {try{Uatest.scan (New jedis
					("192.168.1.5",  6381 + tmp));
					}finally{//There is a thread coming in on the minus 1 latch.countdown ();
			}
				}
			};
		Pool.submit (runnable); ///The first method of blocking statistics: using the Countlatch method of descending, and executing the await () method to block, each thread is decremented until it is 0 to continue executing the final statistic output code try {//blocking,
			The following output statement is not executed until the latch is 0 latch.await (); System.out.println ("All threads are finished.")
			");
			SYSTEM.OUT.PRINTLN (total number of users: "+uatest.sum+", no number of UA found: "+uatest.errorsum);"
		System.out.println (Uatest.set);
		} catch  (interruptedexception e)  {e.printstacktrace ();
		} pool.shutdown (); /*  *  Second Statistical method: This method outputs the final result by blocking and then determining whether the thread is fully executed.
		Instead, the thread pool's isterminated () method is used to determine whether the string pool has completely ended, and the prerequisite is that the shutdown () method that calls the thread pool should be invoked.  *  to determine whether the entire thread pool ends by means of a dead loop, and if it ends, prints the statistic and ends the dead loop while (true) {if (pool.isterminated ()) {System.out.println ("all Lines The execution of the process is complete.
				");
		SYSTEM.OUT.PRINTLN (total number of users: "+uatest.sum+", no number of UA found: "+uatest.errorsum);"		System.out.println (Uatest.set);
			Break }
		}*/
	}
}

4, Code Analysis

public void Countdown ()

Decrements the Count of latches, releasing all waiting threads if the count reaches 0. If the current count is greater than 0, the count is reduced. If the new count is zero, all waiting threads will be re-enabled for thread scheduling purposes.

If the current count equals zero, no action occurs.

Public boolean await (long timeout, timeunit) throws Interruptedexception

Causes the current thread to wait until the latch is counted down to 0 unless the thread is interrupted or the specified wait time is exceeded. If the current count is zero, this method returns a true value immediately.

If the current count is greater than 0, the current thread is disabled for thread scheduling purposes, and the thread remains dormant until one of the following three cases occurs:

By calling the countdown () method, the count reaches 0;

One of the other threads interrupts the current thread;

The specified wait time has been exceeded.

If the count reaches 0, the method returns a true value.

If the current thread:

The interrupt state of the thread has been set when entering this method;

is interrupted while waiting,

The interruptedexception is thrown and the interrupted state of the current thread is cleared. If the specified wait time is exceeded, the return value is false. If the time is less than or equal to zero, this method does not wait at all.

Parameters:

Timeout-the longest time to wait

The time unit for the unit-timeout parameter.

Return:

Returns true if the count reaches 0, or False if the wait time is exceeded before the count reaches 0

Thrown:

Interruptedexception-If the current thread is interrupted while waiting

Pool.isterminated ()

Determines whether the thread pool is closed and no threads are executing. By calling this method in the while loop, you can determine whether the thread pool ends and then count

Reprint please indicate the source all the way blog: http://www.16boke.com/article/detail/178 Java ee

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.