jdk7和8的一些新特性介绍 (四)
rkFilePath() {
Path listDir = Paths.get("/tmp"); // define the starting file
ListTree walk = new ListTree();
…Files.walkFileTree(listDir, walk);…
// 遍历的时候跟踪链接
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
try {
Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);
} catch (IOException e) {
System.err.println(e);
}
class ListTree extends SimpleFileVisitor {// NIO2 递归遍历文件目录的接口
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
System.out.println("Visited directory: " + dir.toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.out.println(exc);
return FileVisitResult.CONTINUE;
}
}
2.3 AIO异步IO 文件和网络 异步IO在java
NIO2实现了,都是用AsynchronousFileChannel,AsynchronousSocketChanne等实现,关于同步阻塞IO,同步非阻塞IO,异步阻塞IO和异步非阻塞IO在ppt的这页上下面备注有说明,有兴趣的可以深入了解下。Java NIO2中就实现了操作系统的异步非阻塞IO。
// 使用AsynchronousFileChannel.open(path, withOptions(),
// taskExecutor))这个API对异步文件IO的处理
public static void asyFileChannel2() {
final int THREADS = 5;
ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
String encoding = System.getProperty("file.encoding");
List> list = new ArrayList<>();
int sheeps = 0;
Path path = Paths.get("/tmp",
"store.txt");
try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
.open(path, withOptions(), taskExecutor)) {
for (int i = 0; i < 50; i++) {
Callable worker = new Callable() {
@Override
public ByteBuffer call() throws Exception {
ByteBuffer buffer = ByteBuffer
.allocateDirect(ThreadLocalRandom.current()
.nextInt(100, 200));
asynchronousFileChannel.read(buffer, ThreadLocalRandom
……
3. JDBC 4.1
3.1.可以使用try-with-resources自动关闭Connection, ResultSet, 和 Statement资源对象
3.2. RowSet 1.1:引入RowSetFactory接口和RowSetProvider类,可以创建JDBC driver支持的各种 row sets,这里的rowset实现其实就是将sql语句上的一些操作转为方法的操作,封装了一些功能。
3.3. JDBC-ODBC驱动会在jdk8中删除
try (Statement stmt = con.createStatement()) {
RowSetFactory aFactory = RowSetProvider.newFactory();
CachedRowSet crs = aFactory.createCachedRowSet();
RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);
WebRowSet wrs = rsf.createWebRowSet();
createCachedRowSet
createFilteredRowSet
createJdbcRowSet
createJoinRowSet
createWebRowSet
4. 并发工具增强
4.1.fork-join
最大的增强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu可以同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,然后调用fork计算,最后用join合并结果。
class Fibonacci extends RecursiveTask
{
final int n;
Fibonacci(int n) {
this.n = n;
}
private int compute(int small) {
final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
return results[small];
}
public Integer compute() {
if (n <= 10) {
return compute(n);
}
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
System.out.println("fork new thread for " + (n - 1));
f1.fork();
System.out.println("fork new thread for " + (n - 2));
f2.fork();
return f1.join() + f2.join();
}
}
4.2.ThreadLocalRandon 并发下随机数生成类,保证并发下的随机数生成的线程安全,实际上就是使用threadlocal
final int MAX = 100000;
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
long start = System.nanoTime();
for (int i = 0; i < MAX; i++) {
threadLocalRandom.nextDouble();
}
long end = System.nanoTime() - start;
System.out.println("use time1 : " + end);
long start2 = System.nanoTime();
for (int i = 0; i < MAX; i++) {
Math.random();
}
long end2 = System.nanoTime() - start2;
System.out.println("use time2 : " + end2);
4.3. phaser 类似cyclebarrier和countdownlatch,不过可以动态添加资源减少资源
void runTasks(List tasks) {
final Phaser phaser = new Phaser(1); // "1" to register self
// create and start threads
for (final Runnable task : tasks) {
phaser.register();
new Thread() {
public void run() {
phaser.arriveAndAwaitAdvance(); // await all creation
task.run();
}
}.start();
}
// allow threads to start and deregister self
phaser.arriveAndDeregister();
}