java nio在多线程环境下的恶梦之终结
有人说java nio在多线程环境下编程简直就是个恶梦,其实你如果能把握住java nio API的要领,你就可以将之驾驭.
0. 一个 channal 对应一个SelectionKey in the same selector.
e.g:
SelectionKey sk=sc.register(selector, SelectionKey.OP_READ, handler);
sk==sc.register(selector, SelectionKey.OP_WRITE, handler) true?
selector.select() 每次返回的对同一channal的sk是否相同?
1.channel.register(...) may block if invoked concurrently with another registration[another.register(...)] or selection operation[selector.select(...)] involving *****the same selector*****.
这个是register方法jdk src上的原文,
e.g:
如果一个selection thread已经在select方法上等待ing,那么这个时候如果有另一条线程调用channal.register方法的话,那么它将被blocking.
2.selectionKey.cancel() : The key will be removed from all of the selector's key sets during *****the next selection operation[selector.select(...)]*****.
may block briefly if invoked concurrently with a cancellation[cancel()] or selection operation[select(...)] involving ***the same selector***.
这个也是cancel方法jdk src上的原文,
e.g:
你先将一个selectionKey.cancel(),然后随即再channel.register to the same selector,
在cancel和register之间,如果没有线程(包括当前线程)进行select操作的话,
那么 throws java.nio.channels.CancelledKeyException.
所以 cancel-->select-->re-register.
3.if don't remove the current selectedKey from selector.selectedKeys()[Set] 将导致 selector.select(...) not block [may be cpu 100%,specially when client cut the current channel(connection)].
e.g:
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
...for/while it.hasNext()...
it.remove();<------*****must do it. or Keys' Set.clear() finally;
if remove the current selectedKey from selector.selectedKeys()[Set] but don't sk.interestOps(sk.interestOps()& (~sk.readyOps()));将导致 selector.select(...) not block [select() not block several times, or excepted exception]
4.op_write should not be registered to the selector. &nbs
相关文档:
< type="text/javascript">
document.body.oncopy = function() {
if (window.clipboardData) {
setTimeout(function() {
......
JAVA四种基本排序,包括冒泡法,插入法,选择法,SHELL排序法.其中选择法是冒泡法的改进,SHELL排序法是 插入法的改进.所以从根本上来说可以归纳为两种不同的排序方法:即:插入法&冒泡法
一 插入法:遍历排序集合,每到一个元素时,都要将这个元素与所有它之前的元素遍历比较一遍,让符合排序顺序的元素挨个移动到当前范围内它最 ......
1.列举出 10个JAVA语言的优势
a:免费,开源,跨平台(平台独立性),简单易用,功能完善,面向对象,健壮性,多线程,结构中立,企业应用的成熟平台, 无线应用
2.列举出JAVA中10个面向对象编程的术语
a:包,类,接口,对象,属性,方法,构造器,继承,封装,多态,抽象,范型
3.列举出JAVA中6个比较常用的包
Java. ......
MSSQL中提供了个datediff函数用来对两个时间进行减法操作,但在Java中却没有,如果我们想知道两个日期间相隔了多少天,或是相隔了多少个小时则要手工计算。下面代码模仿MSSQL的datediff函数提供了使用不同时间间隔来计算两个时间相差的时间间隔的数目,比如timeInterval为day则返回相差的天数,为month则返回相差的月数 ......
定义这个规范的目的是让项目中所有的文档都看起来像一个人写的,增加可读性,减少项目组中因为换人而带来的损失。(这些规范并不是一定要绝对遵守,但是一定要让程序有良好的可读性)
Package的命名
Package的名字应该都是由一个小写单词组成。
Class的命名
Class的名字必须由大写字母开头而其他字母都小写的单词组 ......