概述
SelectorProvider定義了創(chuàng)建selector、ServerSocketChannel、SocketChannel等方法马绝,采用Java的 Service Provider Interface (SPI) 方式實現(xiàn)嫂拴。
SelectorProvider創(chuàng)建過程
private static final Object lock = new Object();
private static SelectorProvider provider = null;
public static SelectorProvider provider() {
synchronized (lock) {
if (provider != null)
return provider;
return AccessController.doPrivileged(
new PrivilegedAction<SelectorProvider>() {
public SelectorProvider run() {
if (loadProviderFromProperty())
return provider;
if (loadProviderAsService())
return provider;
provider = sun.nio.ch.DefaultSelectorProvider.create();
return provider;
}
});
}
}
public abstract DatagramChannel openDatagramChannel()
throws IOException;
public abstract DatagramChannel openDatagramChannel(ProtocolFamily family)
throws IOException;
public abstract Pipe openPipe() throws IOException;
public abstract AbstractSelector openSelector()
throws IOException;
public abstract ServerSocketChannel openServerSocketChannel()
throws IOException;
public abstract SocketChannel openSocketChannel()
throws IOException;
SelectorProvide中定義了私有的成員變量provider,提供了provider方法進行創(chuàng)建杠园;從代碼可以看到顾瞪,創(chuàng)建的過程為:
- 如果provider已經(jīng)創(chuàng)建,直接返回;
- 如果定義了java.nio.channels.spi.SelectorProvider屬性抛蚁,則采用該屬性定義的類創(chuàng)建SelectorProvider并返回陈醒;如果失敗,則繼續(xù)瞧甩;
- 采用SPI方法創(chuàng)建SelectorProvider并返回钉跷;如果實現(xiàn),則通過DefaultSelectorProvider創(chuàng)建肚逸;
關于SPI機制爷辙,有興趣的可以自行查閱文檔彬坏,這邊簡單描述下:
SPI是提供給服務提供廠商與擴展框架功能的開發(fā)者使用的接口;例如java定義了方法數(shù)據(jù)庫的jdbc接口膝晾,而具體的實現(xiàn)由每家數(shù)據(jù)庫廠商自己實現(xiàn)栓始,它采用的就是SPI機制:
- 在META-INF/services/目錄中創(chuàng)建以接口全限定名命名的文件,內容為API具體實現(xiàn)類的全限定名;
- 使用ServiceLoader類動態(tài)加載META-INF中的實現(xiàn)類;
- 如SPI的實現(xiàn)類為Jar則需要放在主程序classPath中;
- API具體實現(xiàn)類必須有一個不帶參數(shù)的構造方法。
具體到NIO,一般都是采用DefaultSelectorProvider創(chuàng)建血当;
在Java的源碼里幻赚,對應不同操作系統(tǒng)平臺,由不同的實現(xiàn)臊旭,在Linux平臺下坯屿,源碼為:
public class DefaultSelectorProvider {
private DefaultSelectorProvider() { }
public static SelectorProvider create() {
String osname = AccessController.doPrivileged(
new GetPropertyAction("os.name"));
if ("SunOS".equals(osname)) {
return new sun.nio.ch.DevPollSelectorProvider();
}
// Linux內核2.6及以上版本,采用EPollSelectorProvider,
//低版本內核使用PollSelectorProvider
if ("Linux".equals(osname)) {
String osversion = AccessController.doPrivileged(
new GetPropertyAction("os.version"));
String[] vers = osversion.split("\\.", 0);
if (vers.length >= 2) {
try {
int major = Integer.parseInt(vers[0]);
int minor = Integer.parseInt(vers[1]);
if (major > 2 || (major == 2 && minor >= 6)) {
return new sun.nio.ch.EPollSelectorProvider();
}
} catch (NumberFormatException x) {
}
}
}
return new sun.nio.ch.PollSelectorProvider();
}
}
可以看到對應目前的主流Linux平臺而言巍扛,都是采用Epoll機制實現(xiàn)领跛;