标签:
java8的lambdas,其实在编译后,会变为此类中的方法,lambdas表达式只不过是一种简单的语法。lambdas表达式其实就是模拟的c,c++语言中的函数指针,这两个语言都可以把函数当作方法的参数传递,但java中就不行了,因为java中一切都是类,方法必须依附于类而存活。
这就免不了java8之前出现的匿名类。不过java8简化了语法,但和命名类还是有实质的区别。我们可以利用aop思想,封装一下通用逻辑,客户端不必要考虑的非业务逻辑,而那些业务逻辑就可以通过lambdas表达式传入。
现在看一下ReentrantReadWriteLock的这中aop思想的体现代码:
package com.doctor.java8; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Supplier; import java.util.stream.Collectors; /** * simplifying-readwritelock-with-java-8-and-lambdas 这也是利用aop编程思想 * * @see http://www.javacodegeeks.com/2014/03/simplifying-readwritelock-with-java-8-and-lambdas.html * * @author doctor * * @time 2015年4月20日 下午2:48:19 */ public class SimplifyingReadwritelockWithJava8AndLambdas { public static void main(String[] args) { MyBuffer myBuffer = new MyBuffer(2); myBuffer.put("name"); myBuffer.put("name1"); myBuffer.put("name2"); System.out.println(myBuffer.getRecent()); System.out.println(myBuffer.getDiscardedCount()); } private static class MyBuffer { private final int capacity; private final Deque<String> recent; private int discarded; private final FunctionalReadWriteLock guard; public MyBuffer(final int capacity) { this.capacity = capacity; recent = new ArrayDeque<String>(this.capacity); discarded = 0; guard = new FunctionalReadWriteLock(); } public void put(String value) { guard.write(() -> { while (recent.size() >= capacity) { recent.removeFirst(); discarded++; } recent.add(value); }); } public List<String> getRecent() { return guard.read(this::defensiveCopyOfRecent); } private List<String> defensiveCopyOfRecent() { return recent.stream().collect(Collectors.toList()); } public int getDiscardedCount() { return guard.read(() -> { return discarded; }); } public int getTotal() { return guard.read(() -> { return discarded + recent.size(); }); } public void flush() { guard.write(this::unsafeFlush); } private void unsafeFlush() { discarded += recent.size(); recent.clear(); } } private static class FunctionalReadWriteLock { private final Lock readLock; private final Lock writeLock; public FunctionalReadWriteLock() { this(new ReentrantReadWriteLock()); } public FunctionalReadWriteLock(final ReentrantReadWriteLock readWriteLock) { readLock = readWriteLock.readLock(); writeLock = readWriteLock.writeLock(); } public void read(Runnable runnable) { readLock.lock(); try { runnable.run(); } finally { readLock.unlock(); } } public <T> T read(Supplier<T> supplier) { readLock.lock(); try { return supplier.get(); } finally { readLock.unlock(); } } public void write(Runnable runnable) { writeLock.lock(); try { runnable.run(); } finally { writeLock.unlock(); } } public <T> T write(Supplier<T> supplier) { writeLock.lock(); try { return supplier.get(); } finally { writeLock.unlock(); } } } }
java8的lambdas表达式模拟aop思想,封装一下锁功能
标签:
原文地址:http://my.oschina.net/doctor2014/blog/404073