看JDK的代码会发现JDK源码很多会用到位运算符来计算,比如HashMap中根据hashcode的值计算元素在数组的位置的时候,没有用%模运算,因为模运算很浪费资源,很慢,如果每次插入,获取都做模运算会很耗时,很慢。HashMap巧妙的利用与运算,HashMap每次扩充数组的长度都为2^n,利用(2^n-1)与hashcode的值做与运算,结果正好与取模运算结果相同,而按位与运算效率是非常之高的。
最近看NIO的时候Selector注册Channel感兴趣的事件的时候可以同时注册多个事件,但事件的参数是个int类型,怎么做到呢?
看事件常量的值
// -- Operation bits and bit-testing convenience methods --
/**
* Operation-set bit for read operations.
*
* <p> Suppose that a selection key's interest set contains
* <tt>OP_READ</tt> at the start of a <a
* href="Selector.html#selop">selection operation</a>. If the selector
* detects that the corresponding channel is ready for reading, has reached
* end-of-stream, has been remotely shut down for further reading, or has
* an error pending, then it will add <tt>OP_READ</tt> to the key's
* ready-operation set and add the key to its selected-key set. </p>
*/
public static final int OP_READ = 1 << 0;
/**
* Operation-set bit for write operations.
*
* <p> Suppose that a selection key's interest set contains
* <tt>OP_WRITE</tt> at the start of a <a
* href="Selector.html#selop">selection operation</a>. If the selector
* detects that the corresponding channel is ready for writing, has been
* remotely shut down for further writing, or has an error pending, then it
* will add <tt>OP_WRITE</tt> to the key's ready set and add the key to its
* selected-key set. </p>
*/
public static final int OP_WRITE = 1 << 2;
/**
* Operation-set bit for socket-connect operations.
*
* <p> Suppose that a selection key's interest set contains
* <tt>OP_CONNECT</tt> at the start of a <a
* href="Selector.html#selop">selection operation</a>. If the selector
* detects that the corresponding socket channel is ready to complete its
* connection sequence, or has an error pending, then it will add
* <tt>OP_CONNECT</tt> to the key's ready set and add the key to its
* selected-key set. </p>
*/
public static final int OP_CONNECT = 1 << 3;
/**
* Operation-set bit for socket-accept operations.
*
* <p> Suppose that a selection key's interest set contains
* <tt>OP_ACCEPT</tt> at the start of a <a
* href="Selector.html#selop">selection operation</a>. If the selector
* detects that the corresponding server-socket channel is ready to accept
* another connection, or has an error pending, then it will add
* <tt>OP_ACCEPT</tt> to the key's ready set and add the key to its
* selected-key set. </p>
*/
public static final int OP_ACCEPT = 1 << 4;
"<<"表示向左移几位,看这4个常量正好把每一位都错开。
所以注册多个感兴趣的事件只要把多个感兴趣的事件取或运算就可以了。
例如:
channel.register(selector,Selectionkey.OP_READ | Selectionkey.OP_CONNECT)//同时注册读就绪和连接就绪事件