有哪位jdk使用教程过jdk1.7

在jdk7的新特性方面主要有下面几方面的增强:
1.1二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。
& & 所有整数int、short、long、byte都可以用二进制表示:
byte aByte = (byte) 0b;
1.2 Switch语句支持String类型。
1.3 Try-with-resource语句:
& 参考博客:&
try-with-resources语句是一种声明了一种或多种资源的try语句。资源是指在程序用完了之后必须要关闭的对象。try-with-resources语句保证了每个声明了的资源在语句结束的时候都会被关闭。任何实现了java.lang.AutoCloseable接口的对象,和实现了java.io.Closeable接口的对象,都可以当做资源使用。
&1.4 Catch多个异常:
在Java 7中,catch代码块得到了升级,用以在单个catch块中处理多个异常。如果你要捕获多个异常并且它们包含相似的代码,使用这一特性将会减少代码重复度。下面用一个例子来理解。
catch(IOException | SQLException | Exception ex){
logger.error(ex);
throw new MyException(ex.getMessage());
1.5 数字类型的下划线表示 更友好的表示方式,不过要注意下划线添加的一些标准。
字面常量数字里加下划线的规则:下划线只能在数字之间,在数字的开始或结束一定不能使用下划线。
public class UsingUnderscoreInNumericLiterals {
public static void main(String[] args) {
int int_num = 1_00_00_000;
System.out.println("int num:" + int_num);
long long_num = 1_00_00_000;
System.out.println("long num:" + long_num);
float float_num = 2.10_001F;
System.out.println("float num:" + float_num);
double double_num = 2.10_12_001;
System.out.println("double num:" + double_num);
1.6 泛型实例的创建可以通过类型推断来简化 可以去掉后面new部分的泛型类型,只用&&就可以了。
1.7 并发工具增强: fork-join框架最大的增强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu可以同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,然后调用fork计算,最后用join合并结果。
参考自己写的例子:
JDK1.8的新特性:
&2.1 接口的默认和静态方法:
Java 8允许我们给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法。
public interface JDK8Interface {
// static修饰符定义静态方法
static void staticMethod() {
System.out.println("接口中的静态方法");
// default修饰符定义默认方法
default void defaultMethod() {
System.out.println("接口中的默认方法");
2.2 Lambda 表达式:(例如:&(x, y) -& { return x + } ;&表达式有三部分组成:参数列表,箭头(-&),以及一个表达式或语句块。)
参考博客:&;&
在Java 8 中你就没必要使用这种传统的匿名对象的方式了,Java 8提供了更简洁的语法,lambda表达式:
Collections.sort(names, (String a, String b) -& {
return b.compareTo(a);
2.3 方法与构造函数引用:
Java 8 允许你使用 :: 关键字来传递方法或者构造函数引用,上面的代码展示了如何引用一个静态方法,我们也可以引用一个对象的方法:
converter = something::startsW
String converted = converter.convert("Java");
System.out.println(converted);
2.4 函数式接口:
所谓的函数式接口,当然首先是一个接口,然后就是在这个接口里面只能有一个抽象方法。
2.5 Annotation 注解:支持多重注解:
很多时候一个注解需要在某一位置多次使用。
@YourAnnotation
@YourAnnotation
public void test(){
2.6 新的日期时间 API:
Java 8新的Date-Time API (JSR 310)受Joda-Time的影响,提供了新的java.time包,可以用来替代
java.util.Date和java.util.Calendar。一般会用到Clock、LocaleDate、LocalTime、LocaleDateTime、ZonedDateTime、Duration这些类,对于时间日期的改进还是非常不错的。
2.7 Base64编码:
Base64编码是一种常见的字符编码,可以用来作为电子邮件或Web Service附件的传输编码。
在Java 8中,Base64编码成为了Java类库的标准。Base64类同时还提供了对URL、MIME友好的编码器与解码器。
2.8 JavaScript引擎Nashorn:
Nashorn允许在JVM上开发运行JavaScript应用,允许Java与JavaScript相互调用。
2.9 Stream的使用:
Stream API是把真正的函数式编程风格引入到Java中。其实简单来说可以把Stream理解为MapReduce,当然Google的MapReduce的灵感也是来自函数式编程。她其实是一连串支持连续、并行聚集操作的元素。从语法上看,也很像linux的管道、或者链式编程,代码写起来简洁明了,非常酷帅!
2.10 Optional:
Java 8引入Optional类来防止空指针异常,Optional类最先是由Google的Guava项目引入的。Optional类实际上是个容器:它可以保存类型T的值,或者保存null。使用Optional类我们就不用显式进行空指针检查了。
2.11 扩展注解的支持:
Java 8扩展了注解的上下文,几乎可以为任何东西添加注解,包括局部变量、泛型类、父类与接口的实现,连方法的异常也能添加注解。
2.12 并行(parallel)数组:
支持对数组进行并行处理,主要是parallelSort()方法,它可以在多核机器上极大提高数组排序的速度。
2.13 编译器优化:
Java 8将方法的参数名加入了字节码中,这样在运行时通过反射就能获取到参数名,只需要在编译时使用-parameters参数。
新的Java1.8对IO做了升级:
关于IO/NIO 新IO的对比,请参考:
还对CurrentHashMap做了升级,请参考:
阅读(...) 评论()在线文档-jdk_7u4
开源中国在线工具
热门文档:> 博客详情
好长时间没更新了,水一篇吧,先说下遇到的问题吧,老项目迁移,迁移到新的服务器,之前用的是resin-4.0.47+JDK1.7环境,而新服务器使用的则是tomcat8.5+JDK1.8,因为有别的项目必须使用1.8版本的,在迁移的时候我就怕有问题,果然没让我失望,还真出问题了,运行不起来,框架太老了,如果改框架很麻烦,换成resin+jdk1.7?那以前的项目就不能用了,哈哈,所以现在要做一件事情,想要的结果是tomcat8.5继续使用jdk1.8,新装resin使用jdk1.7,它们并存,并且互相之间没有任何影响,下面是解决方法,开撸。
1.添加resin用户,并设置密码
[root@iZ2ze97u5340x51jvn8yx1Z ~]# useradd resin
[root@iZ2ze97u5340x51jvn8yx1Z ~]# passwd resin
Changing password for user resin.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
用户名随意,你看着办,总之是要添加一个用户。
2.上传应用软件,配置JDK变量
上传我就不说了,直接配置开始。
[root@iZ2ze97u5340x51jvn8yx1Z ~]# su - resin
[resin@iZ2ze97u5340x51jvn8yx1Z ~]$ cd soft/
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ tar zxf jdk-7u79-linux-x64.tar.gz
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ tar zxf resin-pro-4.0.47.tar.gz
//解压resin
位置随意,放哪都行,然后修改resin用的环境变量。
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ vim ~/.bashrc
//编辑文件
export JAVA_HOME=/home/resin/soft/jdk1.7.0_79/
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
//添加如下内容
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ source ~/.bashrc
//source 一下
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ java -version
//查看结果
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
3.编译安装resin
[resin@iZ2ze97u5340x51jvn8yx1Z soft]$ cd resin-pro-4.0.47
[resin@iZ2ze97u5340x51jvn8yx1Z resin-pro-4.0.47]$ ./configure --prefix=/home/resin/
.bash_logout
.bash_profile
[resin@iZ2ze97u5340x51jvn8yx1Z resin-pro-4.0.47]$ ./configure --prefix=/home/resin/soft/resin
看这里,确保没错,主要是JAVA_HOME那里,最后make && make install
4.修改resin配置文件
这个不多说了,有需要的去翻一下我之前写的文档,主要改的就是resin的运行属主属组,改为resin即可。
[resin@iZ2ze97u5340x51jvn8yx1Z ~]$ vim soft/resin/conf/resin.properties
setuid_user
setuid_group
5.启动resin
使用resin自带脚本启动即可。
[resin@iZ2ze97u5340x51jvn8yx1Z ~]$ soft/resin/bin/resinctl start-all
Resin/4.0.47 launching watchdog at 127.0.0.1:6600
Resin/4.0.47 start-all with watchdog at 127.0.0.1:6600
[resin@iZ2ze97u5340x51jvn8yx1Z ~]$ tail -100 soft/resin/log/jvm-app-0.log
可以正常启动,说明没有问题,接下来就是把项目文件放进来,resin配置一下域名,nginx配一下域名进行upstream即可,结束。
支付宝支付
微信扫码支付
打赏金额: ¥
已支付成功
打赏金额: ¥博客分类:
java程序使用https方式调用nessus接口时,使用jdk1.7返回如下内容:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
使用jdk1.8返回正常
{"token":"fd964ed916fe206a3d1b1c1b41"}
使用浏览器访问正常,debug发现发现:
协议版本:TLSv1.2
密码组合:TLS_RSA_WITH_AES_128_CBC_SHA
百度后发现
原因很明显 因为jdk1.7默认支持的TLS是V1 ,jdk1.8默认支持的是v1.2
解决方案使用第三方的Bouncy Castle
代码如下:
建立一个TLSSocketConnectionFactory
import java.io.ByteArrayInputS
import java.io.ByteArrayOutputS
import java.io.DataOutputS
import java.io.FileInputS
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.net.InetA
import java.net.InetSocketA
import java.net.S
import java.net.UnknownHostE
import java.security.KeyS
import java.security.P
import java.security.SecureR
import java.security.S
import java.security.cert.CertificateExpiredE
import java.security.cert.CertificateF
import java.util.H
import java.util.LinkedL
import java.util.L
import javax.net.ssl.HandshakeCompletedL
import javax.net.ssl.SSLPeerUnverifiedE
import javax.net.ssl.SSLS
import javax.net.ssl.SSLSessionC
import javax.net.ssl.SSLS
import javax.net.ssl.SSLSocketF
import javax.security.cert.X509C
import org.bouncycastle.crypto.tls.*;
import org.bouncycastle.crypto.tls.C
import org.bouncycastle.jce.provider.BouncyCastleP
* Created by hzlizhou on .
public class TLSSocketConnectionFactory extends SSLSocketFactory {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
public Socket createSocket(Socket socket, final String host, int port,
boolean arg3) throws IOException {
if (socket == null) {
socket = new Socket();
if (!socket.isConnected()) {
socket.connect(new InetSocketAddress(host, port));
final TlsClientProtocol tlsClientProtocol = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream(), new SecureRandom());
return _createSSLSocket(host, tlsClientProtocol);
public String[] getDefaultCipherSuites() {
public String[] getSupportedCipherSuites() {
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
throw new UnsupportedOperationException();
public Socket createSocket(InetAddress host, int port) throws IOException {
throw new UnsupportedOperationException();
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
throw new UnsupportedOperationException();
private SSLSocket _createSSLSocket(final String host, final TlsClientProtocol tlsClientProtocol) {
return new SSLSocket() {
private java.security.cert.Certificate[] peertC
public InputStream getInputStream() throws IOException {
return tlsClientProtocol.getInputStream();
public OutputStream getOutputStream() throws IOException {
return tlsClientProtocol.getOutputStream();
public synchronized void close() throws IOException {
tlsClientProtocol.close();
public void addHandshakeCompletedListener(HandshakeCompletedListener arg0) {
public boolean getEnableSessionCreation() {
public String[] getEnabledCipherSuites() {
public String[] getEnabledProtocols() {
public boolean getNeedClientAuth() {
public SSLSession getSession() {
return new SSLSession() {
public int getApplicationBufferSize() {
public String getCipherSuite() {
throw new UnsupportedOperationException();
public long getCreationTime() {
throw new UnsupportedOperationException();
public byte[] getId() {
throw new UnsupportedOperationException();
public long getLastAccessedTime() {
throw new UnsupportedOperationException();
public java.security.cert.Certificate[] getLocalCertificates() {
throw new UnsupportedOperationException();
public Principal getLocalPrincipal() {
throw new UnsupportedOperationException();
public int getPacketBufferSize() {
throw new UnsupportedOperationException();
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
return peertC
public String getPeerHost() {
throw new UnsupportedOperationException();
public int getPeerPort() {
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
public String getProtocol() {
throw new UnsupportedOperationException();
public SSLSessionContext getSessionContext() {
throw new UnsupportedOperationException();
public Object getValue(String arg0) {
throw new UnsupportedOperationException();
public String[] getValueNames() {
throw new UnsupportedOperationException();
public void invalidate() {
throw new UnsupportedOperationException();
public boolean isValid() {
throw new UnsupportedOperationException();
public void putValue(String arg0, Object arg1) {
throw new UnsupportedOperationException();
public void removeValue(String arg0) {
throw new UnsupportedOperationException();
public String[] getSupportedProtocols() {
public boolean getUseClientMode() {
public boolean getWantClientAuth() {
public void removeHandshakeCompletedListener(HandshakeCompletedListener arg0) {
public void setEnableSessionCreation(boolean arg0) {
public void setEnabledCipherSuites(String[] arg0) {
public void setEnabledProtocols(String[] arg0) {
public void setNeedClientAuth(boolean arg0) {
public void setUseClientMode(boolean arg0) {
public void setWantClientAuth(boolean arg0) {
public String[] getSupportedCipherSuites() {
public void startHandshake() throws IOException {
tlsClientProtocol.connect(new DefaultTlsClient() {
@SuppressWarnings("unchecked")
public Hashtable&Integer, byte[]& getClientExtensions() throws IOException {
Hashtable&Integer, byte[]& clientExtensions = super.getClientExtensions();
if (clientExtensions == null) {
clientExtensions = new Hashtable&Integer, byte[]&();
//Add host_name
byte[] host_name = host.getBytes();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos);
dos.writeShort(host_name.length + 3);
dos.writeByte(0);
dos.writeShort(host_name.length);
dos.write(host_name);
dos.close();
clientExtensions.put(ExtensionType.server_name, baos.toByteArray());
return clientE
public TlsAuthentication getAuthentication() throws IOException {
return new TlsAuthentication() {
public void notifyServerCertificate(Certificate serverCertificate) throws IOException {
KeyStore ks = _loadKeyStore();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List&java.security.cert.Certificate& certs = new LinkedList&java.security.cert.Certificate&();
boolean trustedCertificate =
for (org.bouncycastle.asn1.x509.Certificate c : ((org.bouncycastle.crypto.tls.Certificate) serverCertificate).getCertificateList()) {
java.security.cert.Certificate cert = cf.generateCertificate(new ByteArrayInputStream(c.getEncoded()));
certs.add(cert);
String alias = ks.getCertificateAlias(cert);
if (alias != null) {
if (cert instanceof java.security.cert.X509Certificate) {
((java.security.cert.X509Certificate) cert).checkValidity();
trustedCertificate =
} catch (CertificateExpiredException cee) {
// Accept all the certs!
// Accept all the certs!
if (!trustedCertificate) {
// Accept all the certs!
peertCerts = certs.toArray(new java.security.cert.Certificate[0]);
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException(ex);
public TlsCredentials getClientCredentials(CertificateRequest certificateRequest) throws IOException {
private KeyStore _loadKeyStore() throws Exception {
FileInputStream trustStoreFis =
KeyStore localKeyStore =
String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType") != null ? System.getProperty("javax.net.ssl.trustStoreType") : KeyStore.getDefaultType();
String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider") != null ? System.getProperty("javax.net.ssl.trustStoreProvider") : "";
if (trustStoreType.length() != 0) {
if (trustStoreProvider.length() == 0) {
localKeyStore = KeyStore.getInstance(trustStoreType);
localKeyStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
char[] keyStorePass =
String str5 = System.getProperty("javax.net.ssl.trustStorePassword") != null ? System.getProperty("javax.net.ssl.trustStorePassword") : "";
if (str5.length() != 0) {
keyStorePass = str5.toCharArray();
localKeyStore.load(trustStoreFis, keyStorePass);
if (keyStorePass != null) {
for (int i = 0; i & keyStorePass. i++) {
keyStorePass[i] = 0;
return localKeyS
} finally {
if (trustStoreFis != null) {
trustStoreFis.close();
} // startHandshake
发送一个map格式的post请求
import javax.net.ssl.HttpsURLC
import com.alibaba.fastjson.JSON;
import java.io.BufferedR
import java.io.DataOutputS
import java.io.IOE
import java.io.InputS
import java.io.InputStreamR
import java.io.OutputStreamW
import java.net.HttpURLC
import java.net.URI;
import java.net.URISyntaxE
import java.net.URL;
import java.net.URLC
public class HttpsUrlConnectionForTLS {
public HttpURLConnection createConnection(URI uri) throws IOException {
URL url = uri.toURL();
URLConnection connection = url.openConnection();
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)
httpsURLConnection.setSSLSocketFactory(new TLSSocketConnectionFactory());
return httpsURLC
public static void main(String[] args) {
HttpsUrlConnectionForTLS httpsUrlConnectionMessageSender = new HttpsUrlConnectionForTLS();
String loginUrl = "https://192.168.186.73/session";
String data = "username=xiaomi&password=Ultrasafe_123";
connection = httpsUrlConnectionMessageSender.createConnection(new URI(loginUrl ));
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
//POST请求
OutputStreamWriter os =
String json="";
os = new OutputStreamWriter(connection.getOutputStream());
os.write(data);
os.flush();
json=getResponse(connection);
System.out.println(json);
if (connection != null) {
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static String getResponse(HttpURLConnection Conn) throws IOException {
if (Conn.getResponseCode() &= 400) {
is = Conn.getErrorStream();
is = Conn.getInputStream();
String response = "";
byte buff[] = new byte[512];
int b = 0;
while ((b = is.read(buff, 0, buff.length)) != -1) {
response += new String(buff, 0, b);
is.close();
System.out.println(response);
下载次数: 72
论坛回复 /
(0 / 4151)
浏览: 355249 次
来自: 北京
谢谢,很好解决我们的问题
PageOffice插件,挺好使得,可以试试
需要用哪些jar,可以说下吗
哈哈哈,是啊。不用解压,我傻傻的解压出来搞半天。。。
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'转自:http://www.2cto.com/kf/968.html
本文是我学习了解了jdk7和jdk8的一些新特性的一些资料,有兴趣的大家可以浏览下下面的内容。
官方文档:http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html&在jdk7的新特性方面主要有下面几方面的增强:&1.jdk7语法上&&& 1.1二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。&&& // 所有整数 int, short,long,byte都可以用二进制表示&&& // An 8-bit 'byte' value:&&& byte aByte = (byte) 0b;&&&& // A 16-bit 'short' value:&&& short aShort = (short) 0b0101;&&&& // Some 32-bit 'int' values:&&& intanInt1 = 0b;&&& intanInt2 = 0b101;&&& intanInt3 = 0B101; // The B can be upper or lower case.&&&& // A 64-bit 'long' value. Note the "L" suffix:&&& long aLong = 0b0101L;&&&& // 二进制在数组等的使用&&& final int[] phases = { 0bbbb,&&& 0bbbb };&1.2& Switch语句支持string类型&&&&&&&& public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {&&&&&&&& String typeOfD&&&&&&&& switch (dayOfWeekArg) {&&&&&&&&&&&& case "Monday":&&&&&&&&&&&&&&&& typeOfDay = "Start of work week";&&&&&&&&&&&&&&&&&&&&&&&&&&&& case "Tuesday":&&&&&&&&&&&& case "Wednesday":&&&&&&&&&&&& case "Thursday":&&&&&&&&&&&&&&&& typeOfDay = "Midweek";&&&&&&&&&&&&&&&&&&&&&&&&&&&& case "Friday":&&&&&&&&&&&&&&&& typeOfDay = "End of work week";&&&&&&&&&&&&&&&&&&&&&&&&&&&& case "Saturday":&&&&&&&&&&&& case "Sunday":&&&&&&&&&&&&&&&& typeOfDay = "Weekend";&&&&&&&&&&&&&&&&&&&&&&&&&&&& default:&&&&&&&&&&&&&&&& throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);&&&&&&&& }&&&&&&&& return typeOfD&&& }&&1.3 Try-with-resource语句&& && 注意:实现java.lang.AutoCloseable接口的资源都可以放到try中,跟final里面的关闭资源类似; 按照声明逆序关闭资源 ;Try块抛出的异常通过Throwable.getSuppressed获取&&&&& try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);&&& java.io.BufferedWriter writer = java.nio.file.Files&&&& .newBufferedWriter(outputFilePath, charset)) {&&& // Enumerate each entry&&& for (java.util.Enumeration entries = zf.entries(); entries&&& .hasMoreElements();) {&&& // Get the entry name and write it to the output file&&& String newLine = System.getProperty("line.separator");&&& String zipEntryName = ((java.util.zip.ZipEntry) entries&&& .nextElement()).getName() + newL&&& writer.write(zipEntryName, 0, zipEntryName.length());&&& }&&& }&1.4 Catch多个异常 说明:Catch异常类型为final; 生成Bytecode 会比多个catch小; Rethrow时保持异常类型&&&&& public static void main(String[] args) throws Exception {&&& try {&&& testthrows();&&& } catch (IOException | SQLException ex) {&&&&&& }&&& }&&& public static void testthrows() throws IOException, SQLException {&&& }&1.5 数字类型的下划线表示 更友好的表示方式,不过要注意下划线添加的一些标准,可以参考下面的示例&&&& long creditCardNumber = 12_3456L;&&& long socialSecurityNumber = 999_99_9999L;&&& float pi = 3.14_15F;&&& long hexBytes = 0xFF_EC_DE_5E;&&& long hexWords = 0xCAFE_BABE;&&& long maxLong = 0x7fff_ffff_ffff_ffffL;&&& byte nybbles = 0b;&&& long bytes = 0b00_;&&&& //float pi1 = 3_.1415F;&&&&& // I cannot put underscores adjacent to a decimal point&&& //float pi2 = 3._1415F;&&&&& // I cannot put underscores adjacent to a decimal point&&& //long socialSecurityNumber1= 999_99_9999_L;&&&&&&&& // I cannot put underscores prior to an L suffix&&&& //int x1 = _52;&&&&&&&&&&&&& // This is an identifier, not a numeric literal&&& int x2 = 5_2;&&&&&&&&&&&&& // OK (decimal literal)&&& //int x3 = 52_;&&&&&&&&&&&&& // I cannot put underscores at the end of a literal&&& int x4 = 5_______2;&&&&&&& // OK (decimal literal)&&&& //int x5 = 0_x52;&&&&&&&&&&& // I cannot put underscores in the 0x radix prefix&&& //int x6 = 0x_52;&&&&&&&&&&& // I cannot put underscores at the beginning of a number&&& int x7 = 0x5_2;&&&&&&&&&&& // OK (hexadecimal literal)&&& //int x8 = 0x52_;&&&&&&&&&&& // I cannot put underscores at the end of a number&&&& int x9 = 0_52;&&&&&&&&&&&& // OK (octal literal)&&& int x10 = 05_2;&&&&&&&&&&& // OK (octal literal)&&& //int x11 = 052_;&&&&&&&&&&& // I cannot put underscores at the end of a number&&&& 1.6 泛型实例的创建可以通过类型推断来简化 可以去掉后面new部分的泛型类型,只用&&就可以了。&&&&& //使用泛型前&&&& List strList = new ArrayList();&&&& List&String& strList4 = new ArrayList&String&();&&&& List&Map&String, List&String&&& strList5 =& new ArrayList&Map&String, List&String&&&();&&&&& &&&& //编译器使用尖括号 (&&) 推断类型&&&& List&String& strList0 = new ArrayList&String&();&&&& List&Map&String, List&String&&& strList1 =& new ArrayList&Map&String, List&String&&&();&&&& List&String& strList2 = new ArrayList&&();&&&& List&Map&String, List&String&&& strList3 = new ArrayList&&();&&& List&String& list = new ArrayList&&();&&& list.add("A");&&&&& // The following statement should fail since addAll expects&&&&& // Collection&? extends String&&&& //list.addAll(new ArrayList&&());&&1.7在可变参数方法中传递非具体化参数,改进编译警告和错误&&Heap pollution 指一个变量被指向另外一个不是相同类型的变量。例如&&&& List l = new ArrayList&Number&();&&& List&String& ls =&&&&&& // unchecked warning&&& l.add(0, new Integer(42)); // another unchecked warning&&& String s = ls.get(0);&&&&& // ClassCastException is thrown&&& Jdk7:&&& public static &T& void addToList (List&T& listArg, T... elements) {&&& for (T x : elements) {&&& listArg.add(x);&&& }&&& }&&& 你会得到一个warning&&& warning: [varargs] Possible heap pollution from parameterized vararg type&&& 要消除警告,可以有三种方式&&& 1.加 annotation @SafeVarargs&&& 2.加 annotation @SuppressWarnings({"unchecked", "varargs"})&&& 3.使用编译器参数 –Xlint:&& 1.8 信息更丰富的回溯追踪 就是上面try中try语句和里面的语句同时抛出异常时,异常栈的信息&&&& java.io.IOException &&&& §?&&&&& at Suppress.write(Suppress.java:19) &&&& §?&&&&& at Suppress.main(Suppress.java:8) &&&& §?&&&&& Suppressed:& java.io.IOException&&&& §?&&&&&&&&& at Suppress.close(Suppress.java:24)&&&& §?&&&&&&&&& at Suppress.main(Suppress.java:9) &&&& §?&&&&& Suppressed:& java.io.IOException&&&& §?&&&&&&&&& at& Suppress.close(Suppress.java:24) &&&& §?&&&&&&&&& at& Suppress.main(Suppress.java:9)&&&&& &&2. NIO2的一些新特性&&& &&&& 1.java.nio.file 和java.nio.file.attribute包 支持更详细属性,比如权限,所有者&&&& 2.& symbolic and hard links支持&&&& 3. Path访问文件系统,Files支持各种文件操作&&&& 4.高效的访问metadata信息&&&& 5.递归查找文件树,文件扩展搜索&&&& 6.文件系统修改通知机制&&&& 7.File类操作API兼容&&&& 8.文件随机访问增强 mapping a region,locl a region,绝对位置读取&&&& 9. AIO Reactor(基于事件)和Proactor&&& 下面列一些示例:&2.1IO and New IO 监听文件系统变化通知&&通过FileSystems.getDefault().newWatchService()获取watchService,然后将需要监听的path目录注册到这个watchservice中,对于这个目录的文件修改,新增,删除等实践可以配置,然后就自动能监听到响应的事件。&&&& private WatchS&&&& public TestWatcherService(Path path) throws IOException {&&& watcher = FileSystems.getDefault().newWatchService();&&& path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);&&& }&&&& public void handleEvents() throws InterruptedException {&&& while (true) {&&& WatchKey key = watcher.take();&&& for (WatchEvent&?& event : key.pollEvents()) {&&& WatchEvent.Kind kind = event.kind();&&& if (kind == OVERFLOW) {// 事件可能lost or discarded&&&&&& }&&& WatchEvent&Path& e = (WatchEvent&Path&)&&& Path fileName = e.context();&&& System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);&&& }&&& if (!key.reset()) {&&&&&& }&2.2 IO and New IO遍历文件树 ,通过继承SimpleFileVisitor类,实现事件遍历目录树的操作,然后通过Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);这个API来遍历目录树&&&& private void workFilePath() {&&& 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&Path& {// 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&Future&ByteBuffer&& 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&ByteBuffer& worker = new Callable&ByteBuffer&() { &&&&&&&&&&&&&&&&&&&&&&&& @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&Integer& {&&&&&& Fibonacci(int n) {&&& this.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() -&&& 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&Runnable& 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();&&& }&&5. Networking增强&&新增URLClassLoader close方法,可以及时关闭资源,后续重新加载class文件时不会导致资源被占用或者无法释放问题URLClassLoader.newInstance(new URL[]{}).close();新增Sockets Direct Protocol绕过操作系统的数据拷贝,将数据从一台机器的内存数据通过网络直接传输到另外一台机器的内存中&&6. Multithreaded Custom Class Loaders &&&& &&&& 解决并发下加载class可能导致的死锁问题,这个是jdk1.6的一些新版本就解决了,jdk7也做了一些优化。有兴趣可以仔细从官方文档详细了解&jdk7前:& &&&& Class Hierarchy:&&&&&&&&&& &&&&&& class A extends B&&&&& class C extends D&&& ClassLoader Delegation Hierarchy:&&& Custom Classloader CL1:&&&&& directly loads class A&&&&&& delegates to custom ClassLoader CL2 for class B&&& Custom Classloader CL2:&&&&& directly loads class C&&&&& delegates to custom ClassLoader CL1 for class D&&& Thread 1:&&&&& Use CL1 to load class A (locks CL1)&&&&&&& defineClass A triggers&&&&&&&&& loadClass B (try to lock CL2)&&& Thread 2:&&&&& Use CL2 to load class C (locks CL2)&&&&&&& defineClass C triggers&&&&&&&&& loadClass D (try to lock CL1)&&& Synchronization in the ClassLoader class wa&&jdk7&&&& Thread 1:&&&&& Use CL1 to load class A (locks CL1+A)&&&&&&& defineClass A triggers&&&&&&&&& loadClass B (locks CL2+B)&&& Thread 2:&&&&& Use CL2 to load class C (locks CL2+C)&&&&&&& defineClass C triggers&&&&&&&&& loadClass D (locks CL1+D)&&&7. Security 增强&&&&& 7.1.提供几种 ECC-based algorithms (ECDSA/ECDH) Elliptic Curve Cryptography (ECC)&&& 7.2.禁用CertPath Algorithm Disabling&&& 7.3. JSSE (SSL/TLS)的一些增强&&8. Internationalization 增强 增加了对一些编码的支持和增加了一些显示方面的编码设置等&&& &&&& 1. New Scripts and Characters from Unicode 6.0.0&&& 2. Extensible Support for ISO 4217 Currency Codes&&& Currency类添加:&&&& &&&&&&&&&&& getAvailableCurrencies&&&&&&&&&&& getNumericCode&&&&&&&&&&& getDisplayName&&&&&&&&&&& getDisplayName(Locale)&&& 3. Category Locale Support&&&& getDefault(Locale.Category)FORMAT& DISPLAY&&&& 4. Locale Class Supports BCP47 and UTR35&&&&&&&&&& UNICODE_LOCALE_EXTENSION&&&&&&&&&& PRIVATE_USE_EXTENSION&&&&&&&&&& Locale.Builder&&&&&&&&&&& getExtensionKeys()&&&&&&&&&& getExtension(char)&&&&&&&&&& getUnicodeLocaleType(String&&&&&&&&&&& ……&&& 5. New NumericShaper Methods&&& NumericShaper.Range&&&& getShaper(NumericShaper.Range)&&&& getContextualShaper(Set&NumericShaper.Range&)……&&&9.jvm方面的一些特性增强,下面这些特性有些在jdk6中已经存在,这里做了一些优化和增强。&1.Jvm支持非java的语言 invokedynamic 指令&&2. Garbage-First Collector 适合server端,多处理器下大内存,将heap分成大小相等的多个区域,mark阶段检测每个区域的存活对象,compress阶段将存活对象最小的先做回收,这样会腾出很多空闲区域,这样并发回收其他区域就能减少停止时间,提高吞吐量。&&3. HotSpot性能增强&&&& Tiered Compilation& -XX:+UseTieredCompilation 多层编译,对于经常调用的代码会直接编译程本地代码,提高效率&& Compressed Oops& 压缩对象指针,减少空间使用& Zero-Based Compressed Ordinary Object Pointers (oops) 进一步优化零基压缩对象指针,进一步压缩空间&4. Escape Analysis& 逃逸分析,对于只是在一个方法使用的一些变量,可以直接将对象分配到栈上,方法执行完自动释放内存,而不用通过栈的对象引用引用堆中的对象,那么对于对象的回收可能不是那么及时。&5. NUMA Collector Enhancements &&NUMA(Non Uniform Memory Access),NUMA在多种计算机系统中都得到实现,简而言之,就是将内存分段访问,类似于硬盘的RAID,Oracle中的分簇&&10. Java 2D Enhancements&&&& 1. XRender-Based Rendering Pipeline -Dsun.java2d.xrender=True&&& 2. Support for OpenType/CFF Fonts GraphicsEnvironment.getAvailableFontFamilyNames&&&& 3. TextLayout Support for Tibetan Script&&& 4. Support for Linux Fonts&11. Swing Enhancements&&&& 1.& JLayer&&&& 2.& Nimbus Look & Feel&&& 3.& Heavyweight and Lightweight Components&&& 4.& Shaped and Translucent Windows&&& 5.& Hue-Saturation-Luminance (HSL) Color Selection in JColorChooser Class&&&12. Jdk8 lambda表达式 最大的新增的特性,不过在很多动态语言中都已经原生支持。&原来这么写:&&&& btn.setOnAction(new EventHandler&ActionEvent&() {&&&&&&&& @Override&&&&&&& public void handle(ActionEvent event) {&&&&&&&&&&&& System.out.println("Hello World!");&&&&&&&& }&&&& });&&&&&&& &jdk8直接可以这么写:&&&& btn.setOnAction(&&&&&&&& event -& System.out.println("Hello World!")&&&& );& &&&&&&& &更多示例:&& &&&& public class Utils {&&&&&&&& public static int compareByLength(String in, String out){&&&&&&&&&&&& return in.length() - out.length();&&&&&&&& }&&&& }&&&&& public class MyClass {&&&&&&&& public void doSomething() {&&&&&&&&&&&& String[] args = new String[] {"microsoft","apple","linux","oracle"}&&&&&&&&&&&& Arrays.sort(args, Utils::compareByLength);&&&&&&&& } &&&& } &&13.jdk8的一些其他特性,当然jdk8的增强功能还有很多,大家可以参考http://openjdk.java.net/projects/jdk8/&用Metaspace代替PermGen&动态扩展,可以设置最大值,限制于本地内存的大小&Parallel array sorting 新APIArrays#parallelSort.&&&& New Date & Time API&&& Clock clock = Clock.systemUTC(); //return the current time based on your system clock and set to UTC.&&&& Clock clock = Clock.systemDefaultZone(); //return time based on system clock zone&&&&& long time = clock.millis(); //time in milliseconds from January 1st, 1970
阅读(...) 评论()

我要回帖

更多关于 查看tomcat使用的jdk 的文章

 

随机推荐