"Java concurrent Programming Combat" reading notes 4. The combination of __ algorithm for objects

Source: Internet
Author: User

This chapter describes some of the combination patterns that make a class easier to thread-safe and do not unintentionally break security guarantees for classes when they are maintained.

In a single thread, if an operation cannot satisfy a priori condition, it can only be a failure, but in a concurrent program, a priori condition may become true due to an operation performed by another thread. Wait until the prior condition is true in the concurrent program before performing the operation.

In Java, a variety of built-in mechanisms, including wait and notification mechanisms, that wait for a condition to be true are closely associated with the built-in locking mechanism, and it is not easy to use them correctly. A simpler way to implement an action that waits for a priori condition to be true is to implement the dependent state behavior through a class in an existing library, such as blocking queue [blockingqueue] or semaphore [semaphore].


If the allocation populates a HashMap object, it is equivalent to populating multiple objects: HashMap objects, multiple objects contained in HashMap objects, and internal objects that may be contained in Map.entry.

Instance closures are one of the easiest ways to build thread-safe classes.

Vehicle tracking:

Import java.util.Collections;
Import Java.util.HashMap;

Import Java.util.Map;

	public class Monitorvehicletracker {private final map<string, mutablepoint> locations;
	Public Monitorvehicletracker (map<string, mutablepoint> locations) {this.locations = deepcopy (locations);
	Public synchronized map<string, mutablepoint> getlocations () {return deepcopy (locations);
		Public synchronized Mutablepoint getLocation (String id) {Mutablepoint loc = Locations.get (ID); return loc = null?
	Null:new mutablepoint (Loc);
		Public synchronized void setlocation (String ID, int x, int y) {Mutablepoint loc = Locations.get (ID);
		if (loc = = null) {throw new IllegalArgumentException ("No such ID:" + ID);
		} loc.x = x;
	Loc.y = y; private static map<string, mutablepoint> deepcopy (map<string, mutablepoint> m) {hashmap<string, Muta
		blepoint> result = new hashmap<string, mutablepoint> (); For (String Id:m.keyset ()) {result.Put (ID, new Mutablepoint (M.get (ID)));
	return Collections.unmodifiablemap (Result); }

}
public class Mutablepoint {public

	int x, y;

	Public Mutablepoint () {
		x = 0;
		y = 0;
	}
	
	Public Mutablepoint (Mutablepoint p) {
		this.x = p.x;
		This.y = p.y;
	}

Although class Mutablepoint is not thread-safe, the tracker class is thread-safe. It contains both a map object and a mutable point object that has not been published. When you need to return to the vehicle's location, copy the correct value by using the Mutablepoint copy constructor or the Deepcopy method to generate a new map object that has the same value as the key value and value in the original map object.


public class Point {public
	
	final int x, y;
	
	public point (int x, int y) {
		this.x = x;
		This.y = y;
	}

}

Import java.util.Collections;
Import Java.util.Map;
Import Java.util.concurrent.ConcurrentHashMap;

public class Delegatingvehicletracker {

	private final concurrenthashmap<string, point> locations;
	Private final map<string, point> Unmodifiablemap;

	Public Delegatingvehicletracker (map<string, point> points) {
		locations = new Concurrenthashmap<> ( points);
		Unmodifiablemap = Collections.unmodifiablemap (locations);
	}

	Public map<string, Point> getlocations () {return
		unmodifiablemap;
	}

	Public point getLocation (String ID) {return
		locations.get (ID);
	}
	
	public void setlocation (String ID, int x, int y) {
		if (Locations.replace (IDs, new Point (x, y)) = = null) {
			throw n EW illegalargumentexception ("Invalid vehicle name:" + ID);
		}
	}

If a state variable is thread safe, and there is no invariant condition to constrain its value, there is no state transition that is not allowed on the operation of the variable, so it is safe to publish the variable.


adding functionality to existing thread-safe classes

If you need a thread-safe list, it needs to provide an atomic "if not add (put-if-absent)" operation. The Synchronized list class has implemented most of the functionality, and we can construct a "if not added" operation based on the Contains method and the Add method that it provides.

1. Vector extension

@ThreadSafe public
class Bettervector<e> extends vector<e>{public
	
	synchronized Boolean Putifabsent (E x) {
		Boolean absent =!contains (x);
		if (absent) {
			add (x);
		}
		return absent
	}

}

2. Through the client plus lock to achieve "if not add"

@ThreadSafe public
class Listhelper<e> {public
	
	list<e> List = collections.synchronizedlist (new Arraylist<e> ());
	
	// ...
	public boolean putifabsent (E x) {
		synchronized (list) {
			Boolean absent =!list.contains (x);
			if (absent) {
				list.add (x);
			}
			return absent;
		}
	}

The client lock mechanism has much in common with the extended class mechanism, both of which combine the behavior of the derived class with the implementation of the base class. Just as the extension destroys the encapsulation of the implementation, client locking also destroys the encapsulation of the synchronization strategy.

3. Through the combination of "if not add"

when adding an atomic operation to an existing class, there is a better way: a combination (composition).

@ThreadSafe public
class Improvedlist<t> implements list<t>{
	
	private final list<t> List;

	Public improvedlist (list<t> list) {
		this.list = list;
	}
	
	Public synchronized Boolean putifabsent (T x) {
		Boolean absent =!list.contains (x);
		if (absent) {
			list.add (x);
		}
		return absent;
	}
	
	Public synchronized void Iclear () {
		list.clear ();
	}
	// ... Other ways to delegate a list in a similar way
}

Improvelist adds an extra layer of lock through its own built-in locks. It does not care whether the underlying list is thread-safe, and even if the list is not thread-safe or modifies its lock implementation, Improvelist also provides a consistent locking mechanism to implement thread security. Although the additional synchronization layer may cause slight performance loss, improvedlist is more robust than the lock strategy that simulates another object.

In fact, we use the Java monitor pattern to encapsulate an existing list, and we can ensure thread security by having a unique external reference to the underlying list in the class.


Synchronizing Policy Documentation

The documentation describes the thread security guarantees that client code needs to know, and the synchronization policies that code maintainers need to understand.

Synchronized, volatile, or any of the thread-safe classes correspond to a synchronization policy that ensures the integrity of the data in concurrent access. This strategy is one of the elements of programming, so it should be documented.

multiple aspects to consider when designing a synchronization strategy

For example, which variables are declared as volatile types, which variables are protected with locks, which locks protect which variables, which variables must be immutable or enclosed in threads, and which operations must be atomic operations.

some of these aspects are strict implementation details and should be documented for later maintenance. There are also aspects that affect the external performance of the lock behavior in the class, and should be written to the document as part of the specification.

at the very least, you should ensure that thread security in your class is documented. Whether it is thread-safe.    Whether a lock is held when the callback is executed. Whether there are certain locks that affect their behavior. Don't let the client risk guessing.

Java.text.SimpleDateFormat is not thread-safe.

if a class does not explicitly state that it is thread-safe, then do not assume it is thread-safe.

Explain the specification from the perspective of the person who implements it, not from the user's perspective.

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.