[学习摘要] Effective java [EN 3rd version] (Item 6-9)

Item 6: Avoid creating unnecessary objects

 

1. 避免 String = new String (“124”)// 会导致在堆中创建对象,然而可能并不需要

避免 在循环中使用字符串拼接 // java 用 StringBuffer 的 append 方法拼接字符串,这导致很多中间对象创建操作。

 

2. 尽量使用静态工厂方法,单例模式。

 
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);

public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

 

3.While String.matches is the easiest way to check if a string matches a regular expression, it’s not suitable for repeated
use in performance-critical situations. // 正则表达式的创建浪费资源,可以重用的情况下应该尽量重用

// Reusing expensive object for improved performance
public class RomanNumerals {
private static final Pattern ROMAN = Pattern.compile(
"^(?=.)M*(C[MD]|D?C{0,3})"
+ "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
static boolean isRomanNumeral(String s) {
return ROMAN.matcher(s).matches();
}}

 

4. Autoboxing blurs but does not erase the distinction between primitive and boxed primitive types.// 循环中 不应该有频繁的自动类型转换。

 

 

Item 7: Eliminate obsolete object references

 

1. 不用的对象可以消除依赖引用 。但是 !! 这个方法不好(很累),应该让自己的变量们作用域尽量窄,一个变量失去了作用域,自然就被GC回收了。

elements[size] = null; // Eliminate obsolete reference

 

2.造成内存泄露的几种可能:

@1 whenever a class manages its own memory, the  programmer should be alert for memory leaks

@2 Another common source of memory leaks is caches。(很容易忘记,一般用后台线程去定期清空长久不用的缓存)

考虑 WeakHashMap 、java.lang.ref

@3 A third common source of memory leaks is listeners and other callbacks(记得 unregistered)

 

 

Item 8: Avoid finalizers and cleaners

 

1. 不确定什么时候执行,优先级非常低。

2. 很慢,而且没必要。不能做任何时延性操作。

3.Finalizers have a serious security problem: they open your class up to finalizer attacks.

解决:To protect nonfinal classes from finalizer attacks, write a final finalize method that does nothing.写一个什么都不做的final finalize

4. 好处:

@1 One is to act as a safety net in case the owner of a resource  neglects to call its close method. 关闭资源的最后一道保障

such as FileInputStream, FileOutputStream, ThreadPoolExecutor, and
java.sql.Connection, have finalizers that serve as safety nets.

@2 concerns objects with native peers

In summary, don’t use them !!!!

 

 

Item 9: Prefer try-with-resources to try-finally

 

try-finally 比用 finalizers 关闭资源要可靠得多,但是,当资源超过一个,格式就变得很复杂。

// try-finally is ugly when used with more than one resource!
static void copy(String src, String dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
            OutputStream out = new FileOutputStream(dst);
    try {
            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
        } finally {
            out.close();
        }
    }
    finally {
        in.close();
    }
}

而且,The code in both the try block and the finally block is capable of throwing exceptions.

Under these circumstances, the second exception completely obliterates the first one.

 

当resource 扩展了AutoCloseable接口时,我们可以使用try-with-resources ,此方法可以自动调用 void返回类型的 close 方法。

// try-with-resources - the the best way to close resources!
static String firstLineOfFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader( new FileReader(path))) 
    {
        return br.readLine();
    }
}

And here’s how our second example looks using try-with-resources:

// try-with-resources on multiple resources - short and sweet
static void copy(String src, String dst) throws IOException {
    try (InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dst)) 
    {
        byte[] buf = new byte[BUFFER_SIZE];
        int n;
        while ((n = in.read(buf)) >= 0)
        out.write(buf, 0, n);
    }
}

// try-with-resources with a catch clause
static String firstLineOfFile(String path, String defaultVal) {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) 
        {
            return br.readLine();
        } catch (IOException e) {
            return defaultVal;
        }
}

The lesson is clear: Always use try-with-resources in preference to try-finally when working with resources that must be closed.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值