java 零散知识点总结(不断更新贴)

这些知识点都是在看公司代码漏洞中发现的,很零散,所以mark下,以免自己遗忘。

1.

As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.

理解:在javaDoc中,Dateformat对于多线程使用来说本质上是不安全的。在没有适当同步的情况下跨线程边界共享一个实例将导致应用程序的不稳定行为。

建议:

1.需要的时候创建新实例(方法内) 局部变量可以避免线程安全问题,虽然对gc会有影响,但性能下降总比程序出错好

2.同步使用,加锁,保障线程安全,但多线程较多时,也会对性能造成影响。

3.使用ThreadLocal变量,用空间换时间,这样每个线程就会独立享有一个本地的SimpleDateFormat变量(百度方法)

4..JDK的日期API是非常逆天难用的(至少在Java8之前,公司用的jdk1.5),可以考虑使用优秀的第三方库,例如joda-time。(百度方法)

2.避免空指针异常在判断时。

3.

This code compares java.lang.String objects for reference equality using the == or != operators. Unless both strings are either constants in a source file, or have been interned using the String.intern() method, the same string value may be represented by two different String objects. Consider using the equals(Object) method instead.

理解:对于string对象 ==与!= 除非两个都是源文件的常量,或者是String缓冲池的引用对象(同一字符串),考虑使用equals方法。

举例:

        String s0="hello";
        String s1="hello";
        String s2=new String("hello");
        String s3=new String("hello");
        String s4=new String("hello").intern();

        s0==s1
        s1!=s2
        s2!=s3
        s3!=s4
        s4==s0

猜你喜欢

转载自blog.csdn.net/lin_rongwu/article/details/81562292
今日推荐