Java multithreaded Programming---JAVA5 blocking queue __ algorithm

Source: Internet
Author: User
Tags addall sorts
application of Java5 blocking queue

Queues contain fixed-length queues and unfixed-length queues, FIFO.

fixed-length queues to put data, if filled with also put, blocking queues will wait until there is data out, vacated position before continuing to put; non-blocking queues can only complain if they cannot wait.

When speaking condition, the principle of blocking queue is mentioned, and the blocking queue Arrayblockingqueue and blockingqueue<e> are implemented in Java.

Public interface Blockingqueue<e> extendsqueue<e>

A queue that supports two additional operations: wait for the queue to become non-null when the element is fetched, and wait for the space to become available when the element is stored.

The Blockingqueue method appears in four different ways, for operations that cannot be met immediately but may be satisfied at some point in the future: the first is to throw an exception, and the second is to return a special value (null or FALSE, depending on the operation), The third is to block the current thread indefinitely until the operation succeeds, and the fourth is to block only within the given maximum time limit before giving up. These methods are summarized in the following table:

Throw an exception

Special value

Blocking

Timeout

Insert

Add (E)

Offer (e)

Put (e)

Offer (E, time, unit)

Removed from

Remove ()

Poll ()

Take ()

Poll (time, unit)

Check

Element ()

Peek ()

Not available

Not available

Blockingqueue does not accept null elements. when attempting to add, put, or offer a null element, some implementations throw nullpointerexception. Null is used as a warning value to indicate the failure of the poll operation.

Blockingqueue can be of limited capacity. It can have a remainingcapacity at any given time, exceeding this capacity, and cannot put additional elements without blocking. Blockingqueue that do not have any internal capacity constraints always report the remaining capacity of the integer.max_value.

The Blockingqueue implementation is primarily used for producer-consumer queues, but it also supports collection interfaces. Therefore, for example, it is possible to remove any element from the queue using remove (x). However, such operations are usually not performed effectively and can only be used occasionally, for example, when the queued information is canceled.

the Blockingqueue implementation is thread-safe. all queuing methods can automatically achieve their purpose by using internal locks or other forms of concurrency control. However, a large number of collection operations (AddAll, Containsall, Retainall, and RemoveAll) do not need to be performed automatically unless specifically described in the implementation. Thus, for example, AddAll (c) may fail (throw an exception) after adding only some elements in C.

java.util.concurrent.arrayblockingqueue<e>

E-element types maintained in this collection

Extends Abstractqueue<e>implements Blockingqueue<e> Serializable

A bounded blocking queue supported by the array. This queue sorts the elements according to the FIFO (first-in first Out) principle. The head of the queue is the element that has the longest time in the queue. The tail of the queue is the element that has the shortest time in the queue. The new element is inserted at the end of the queue, and the queue fetch operation starts from the queue header to obtain the element.

This is a typical "bounded buffer" with fixed-size arrays in which the producer inserts elements and the user extracts the elements. Once you create such a buffer, you can no longer increase its capacity. Attempting to put an element into a full queue causes the operation to be blocked, and attempting to extract elements from an empty queue causes a similar blockage.

This class supports an optional fair policy that sorts waiting producer and consumer threads. By default, this sort is not guaranteed. However, queues constructed by setting the fairness (fairness) to true allow the thread to be accessed in FIFO order. Fairness generally lowers throughput, but also reduces variability and avoids "imbalances."

This class and its iterators implement all of the optional methods for the collection and iterator interfaces. This class is a member of the Java collections Framework. Construction Method Summary

1, Arrayblockingqueue (intcapacity): Create a arrayblockingqueue with the given (fixed) capacity and default Access policy.

2, Arrayblockingqueue (Intcapacity, Boolean Fair): Creates a arrayblockingqueue with the given (fixed) capacity and the specified access policy.

3, Arrayblockingqueue (Intcapacity, Boolean fair, collection< extends e> c) : Creates a arrayblockingqueue with a given (fixed) capacity and a specified access policy that initially contains the elements of a given collection and adds elements in the traversal order of the collection iterator. Method Summary

1. Boolean Add (E): Inserts the specified element at the end of this queue (if it is immediately feasible and does not exceed the capacity of the queue), returns true on success and throws IllegalStateException if the queue is full.

2, Voidclear (): Automatically remove all elements in this queue.

3. Boolean contains (Object O): Returns True if the queue contains the specified element.

4, int drainto (COLLECTION< super e> C): Removes all available elements from this queue and adds them to the given Collection.

5, int drainto (COLLECTION< Super e> C, intmaxelements): Removes a given number of available elements from this queue and adds them to the given Collection.

6, Iterator<e>iterator (): An iterator that returns the iteration in the appropriate order on the elements in this queue.

7. Boolean Offer (E): Inserts the specified element at the end of this queue (if it is immediately feasible and does not exceed the capacity of the queue), returns true on success, or False if the queue is full.

8. Boolean offer (e E, long timeout, timeunit unit): Inserts the specified element at the end of this queue, and waits for the available space before the specified wait time is reached if the queue is full.

9, E Peek (): Gets but does not remove the header of this queue, or returns null if the queue is empty.

10, E poll (): Gets and removes the header of this queue, and returns null if the queue is empty.

11, Epoll (long timeout, timeunit unit): Gets and removes the header of this queue, waits for the available elements (if necessary) before the specified wait time.

12. Void put (e E): Inserts the specified element at the end of this queue, and waits for available space if the queue is full.

13, Intremainingcapacity (): Returns the number of other elements that this queue can accept without blocking ideally (no memory or resource constraints exist).

14. Boolean Remove (Object o): Removes a single instance of the specified element (if present) from this queue.

15, Intsize (): Returns the number of elements in this queue.

16, Etake (): Gets and removes the header of this queue, and waits (if necessary) before the element becomes available.

17, Object[]toarray (): Returns an array that contains all the elements in this queue in the appropriate order.

18, <t>t[] ToArray (t[] a): Returns an array that contains all the elements in this queue in the appropriate order; The Run-time type of the array is the Run-time type of the specified array.

19, Stringtostring (): Returns the string representation of this collection.

Program Instance

1, the simple use of blocking queues

public class Blockingqueuetest {public static void main (string[] args) {//fixed size 3 blocking queue final blockingqueue<
		
		integer> queue = new arrayblockingqueue<integer> (3); for (int i = 0; i < 2; i++) {//queue for data in queue new Thread () {public void run () {while (true) {try
							{Thread.Sleep ((long) (Math.random () * 1000));
							System.out.println (Thread.CurrentThread (). GetName () + "ready to put data!");
							
							If the queue is full, it will block Queue.put (1);
							
						System.out.println (Thread.CurrentThread (). GetName () + "has already put the data," + "queue currently has" + queue.size () + "data");
						catch (Interruptedexception e) {e.printstacktrace ();
		}}}.start (); Queue for data from queue new Thread () {public void run () {while (true) {try {///change the sleep time here to 100 and 1000, respectively, view
						The results of Thread.Sleep (1000) were observed;
						System.out.println (Thread.CurrentThread (). GetName () + "Ready to fetch data!");
						
						Block Queue.take () if the queue is empty; SyStem.out. println (Thread.CurrentThread (). GetName () + "has taken away data," + "queue currently has" + queue.size () + "data");
					catch (Interruptedexception e) {e.printstacktrace ();
	}}}.start (); }
}


2, using blocking queue to achieve communication between threads

The implementation principle of the blocking queue (condition in the lock is mentioned awaitsignal)

Import Java.util.concurrent.ArrayBlockingQueue;

Import Java.util.concurrent.BlockingQueue; public class Blockingqueuecommunication {public static void main (string[] args) {final Business Business = new Busin
		
		ESS (); Child thread new Thread (new Runnable () {@Override public void run () {for (int i = 1; i <=; i++) {Bus
				Iness.sub (i);
		
		}}). Start ();
		Main thread for (int i = 1; I <= i++) {business.main (i); } static class Business {//Every time before execution, the value is placed in the queue for, the thread is blocked with full queues, and after the operation completes, the other queue is emptied, equivalent to a notification blockingqueue<integer> que
		ue1 = new arrayblockingqueue<integer> (1);
		
		blockingqueue<integer> queue2 = new arrayblockingqueue<integer> (1); When you execute {try {///initial queue2 full at each new object, before calling the constructor method, the data in the queue2 is blocked, and only if another thread takes the value of queue2, it is equivalent to giving it a notification QUEUE2.P
				
			UT (1);
			catch (Interruptedexception e) {e.printstacktrace ();
			The public void sub (int i) {try {queue1.put (1); catch (InterruptEdexception e) {e.printstacktrace ();
			for (int j = 1; J <= J + +) {System.out.println ("sub thread Sequece of" + j + ", loop of" + i);
			try {queue2.take ();
			catch (Interruptedexception e) {e.printstacktrace ();
			} public void Main (int i) {try {queue2.put (1);
			catch (Interruptedexception E1) {e1.printstacktrace ();
			for (int j = 1; J <= J + +) {System.out.println ("main thread sequece of" + j + ", loop of" + i);
			try {queue1.take ();
			catch (Interruptedexception e) {e.printstacktrace (); }
		}
	}
}


Application of Java5 synchronous collection class

The traditional set implementation synchronization problem, for example: The Map collection thread is not synchronized caused by the problem.

Workaround: Use a synchronized map collection, and use methods in the Collection tool class to convert an unsynchronized set to a synchronized Collections.synchronizedmap (Newmap ()) This method returns a synchronized collection:

Publicstatic<k, v> map<k, v> synchronizedmap (map<k, v> m) {

return new synchronizedmap<k, v> (m);

}

The Synchronizedmap class is equivalent to a proxy class, by viewing the source code discovery: All methods in this class are returned directly: the result of the original map collection method call, but the code that returns the result is placed in the synchronized code block for synchronization, which is constructed to default the synchronization lock to the current object.

The relationship and difference between HashSet and HashMap:

HashSet is a single-column, HashMap is a double column (key-value pair)

Relationship: HashSet Internal use is the key in the HashMap, regardless of the value.

View HashSet's source code found that its internal is implemented with HashMap, but did not use the HashMap V, only its k.

Concurrency collection is provided in JDK1.5: A collection implementation designed for multithreaded contexts is provided: Concurrenthashmap, Concurrentskiplistmap, Concurrentskiplistset, Copyonwritearraylist and Copyonwritearrayset. When many threads are expected to access a given collection, the concurrenthashmap is usually better than the synchronized hashmap,concurrentskiplistmap is usually better than the synchronized treemap. Copyonwritearraylist is better than synchronized ArrayList when the expected readings and traversal are much greater than the number of updates in the list.

Concurrentskiplistmap<k,v> mappings can be sorted according to the natural order of the keys, or they can be sorted according to the comparator provided when the mapping is created, depending on the construction method used.

concurrentskiplistset<e> A scalable concurrency Navigableset implementation based on Concurrentskiplistmap. The elements of a set can be sorted according to their natural order, or they can be sorted according to the comparator provided when the set was created, depending on the construction method used.

A thread-safe variant of copyonwritearraylist<e>arraylist, where all the mutable operations (add, set, and so on) are implemented by a new replication of the underlying array. This generally requires a lot of overhead, but when the number of traversal operations is much greater than the number of variable operations, this method may be more efficient than other workarounds. It is also useful when you cannot or do not want to perform a synchronous traversal, but you need to exclude conflicts from concurrent threads.

Copyonwritearrayset<e> uses the internal copyonwritearraylist Set for all its operations. Therefore, it shares the following basic properties:

It is best suited for applications with the following characteristics: The set size is usually kept small, read-only operations are much more than the variable operation, and there is a need to prevent conflicts between threads during traversal. It is thread-safe. Because it is often necessary to replicate the entire underlying array, the overhead of volatile operations (add, set, and remove, and so on) is high. The variable remove operation is not supported by iterators. Iterating with iterators is fast and does not conflict with other threads. When constructing an iterator, the iterator relies on an invariant array snapshot.

Other problems in traditional collections: When iterating over a collection, you cannot modify the elements in the collection (add, delete ...). ), the Concurrency collection provided in Java5 solves this problem.

Program Instance

Copyonwritearraylist Use Example:

public class User implements cloneable {
	private String name;
	private int age;

	Public User (String name, int age) {
		this.name = name;
		This.age = age;
	}

	public boolean equals (Object obj) {
		if (this = = obj) {return
			true;
		}
		if (!) ( obj instanceof User)) {return
			false;
		}
		
		User user = (user) obj;
		if (This.name.equals (user.name) && this.age = = user.age) {return
			true;
		} else {return
			false;< c19/>}
	public

	int hashcode () {return
		Name.hashcode () + age;
	}

	Public String toString () {return
		"{name: ' + name +" ', Age: "+ Age +"} ";
	}

	public Object Clone () {
		object = null;
		
		try {
			object = Super.clone ();
			
		} catch (Clonenotsupportedexception e) {
			
		} return
		
		object;
	}

	public void Setage (int age) {
		this.age = age;
	}

	Public String GetName () {return
		name;
	}
}

public class Collectionmodifyexceptiontest {public static void main (string[] args) {//Arrayslist
		
		Iterator, and if the structure of the list is modified during the iteration, the exception//collection<user> users = new arraylist<user> ();

		collection<user> users = new copyonwritearraylist<user> ();
		Users.add (New User ("John", 28));
		Users.add (New User ("Dick", 25));
		
		Users.add (New User ("Harry", 31));
		iterator<user> itrusers = Users.iterator ();
			while (Itrusers.hasnext ()) {User user = Itrusers.next ();
				
			if ("John". Equals (User.getname ())) {users.remove (user);
			else {System.out.println (user); }
		}
	}
}

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.