Java7新特性(四)并发 4 Atomic、ConcurrentHashMap对象

本文主要根据《Java程序员修炼之道》整理的代码笔记片段

Java 5 原子类操作,采用现代并发 序列号机制

public class AtomicClass {
	
	private final AtomicLong sequenceNumber = new AtomicLong(0);
	//序列号机制,利用原子操作方法
	
	public long nextID(){
		return sequenceNumber.getAndIncrement();
	}
	
	public long decreID(){
		return sequenceNumber.getAndDecrement();
	}
	
	public long set(long newValue){
		return sequenceNumber.getAndSet(newValue);
	}
	
	public long add(long delta){
		return sequenceNumber.getAndAdd(delta);
	}
}

Java 5 ConcurrentHashMap  无显示同步、安全高效   putIfAbsent remove replace方法

public class ExampleTimingBode implements IBlogNode {

	private final String identifier;
	private final ConcurrentHashMap<Update ,Long> arrivalTime = new ConcurrentHashMap<>();
	//无显示同步、安全高效   putIfAbsent remove replace
	
	public ExampleTimingBode(String identifier_){
		identifier=identifier_;
	}
	
	@Override
	public String getIdent() {	
		return identifier;
	}
		
	@Override
	public void propagateUpdate(Update upd_, IBlogNode backup_) {
		long current = System.currentTimeMillis();
		arrivalTime.putIfAbsent(upd_, current);
	}

	@Override
	public boolean confirmUpdate(IBlogNode other_, Update update_) {
		Long recvd = arrivalTime.get(update_);		
		return recvd!=null;

	}

}


你可能感兴趣的:(并发,新特性,java7,atomic)