美文网首页
Java编程常见问题汇总(四)

Java编程常见问题汇总(四)

作者: java部落 | 来源:发表于2017-12-06 21:21 被阅读0次

    用浮点数来保存money

    错误的写法:

    float total = 0.0f;   
    for (OrderLine line : lines) {   
    total += line.price * line.count;   
    }   
    double a = 1.14 * 75; // 85.5 将表示为 85.4999...   
    System.out.println(Math.round(a)); // 输出值为85   
    BigDecimal d = new BigDecimal(1.14); //造成精度丢失
    

    这个也是一个老生常谈的错误. 比如计算100笔订单, 每笔0.3元, 最终的计算结果是29.9999971. 如果将float类型改为double类型, 得到的结果将是30.000001192092896. 出现这种情况的原因是, 人类和计算的计数方式不同. 人类采用的是十进制, 而计算机是二进制.二进制对于计算机来说非常好使, 但是对于涉及到精确计算的场景就会带来误差. 比如银行金融中的应用。

    因此绝不要用浮点类型来保存money数据. 采用浮点数得到的计算结果是不精确的. 即使与int类型做乘法运算也会产生一个不精确的结果.那是因为在用二进制存储一个浮点数时已经出现了精度丢失. 最好的做法就是用一个string或者固定点数来表示. 为了精确, 这种表示方式需要指定相应的精度值.

    BigDecimal就满足了上面所说的需求. 如果在计算的过程中精度的丢失超出了给定的范围, 将抛出runtime exception.

    正确的写法:

    BigDecimal total = BigDecimal.ZERO;   
    for (OrderLine line : lines) {   
    BigDecimal price = new BigDecimal(line.price);   
    BigDecimal count = new BigDecimal(line.count);   
    total = total.add(price.multiply(count)); // BigDecimal is immutable!   
    }   
    total = total.setScale(2, RoundingMode.HALF_UP);   
    BigDecimal a = (new BigDecimal("1.14")).multiply(new BigDecimal(75)); // 85.5 exact   
    a = a.setScale(0, RoundingMode.HALF_UP); // 86   
    System.out.println(a); // correct output: 86   
    BigDecimal a = new BigDecimal("1.14");
    

    不使用finally块释放资源

    错误的写法:

    public void save(File f) throws IOException {   
    OutputStream out = new BufferedOutputStream(new FileOutputStream(f));   
    out.write(...);   
    out.close();   
    }   
    public void load(File f) throws IOException {   
    InputStream in = new BufferedInputStream(new FileInputStream(f));   
    in.read(...);   
    in.close();   
    }
    

    上面的代码打开一个文件输出流, 操作系统为其分配一个文件句柄, 但是文件句柄是一种非常稀缺的资源, 必须通过调用相应的close方法来被正确的释放回收. 而为了保证在异常情况下资源依然能被正确回收, 必须将其放在finally block中. 上面的代码中使用了BufferedInputStream将file stream包装成了一个buffer stream, 这样将导致在调用close方法时才会将buffer stream写入磁盘. 如果在close的时候失败, 将导致写入数据不完全. 而对于FileInputStream在finally block的close操作这里将直接忽略。

    如果BufferedOutputStream.close()方法执行顺利则万事大吉, 如果失败这里有一个潜在的bug(http://bugs.sun.com/view_bug.do?bug_id=6335274): 在close方法内部调用flush操作的时候, 如果出现异常, 将直接忽略. 因此为了尽量减少数据丢失, 在执行close之前显式的调用flush操作。

    下面的代码有一个小小的瑕疵: 如果分配file stream成功, 但是分配buffer stream失败(OOM这种场景), 将导致文件句柄未被正确释放. 不过这种情况一般不用担心, 因为JVM的gc将帮助我们做清理。

    // code for your cookbook   
    public void save() throws IOException {   
    File f = ...   
    OutputStream out = new BufferedOutputStream(new FileOutputStream(f));   
    try {   
    out.write(...);   
    out.flush(); // don't lose exception by implicit flush on close   
    } finally {   
    out.close();   
    }   
    }   
    public void load(File f) throws IOException {   
    InputStream in = new BufferedInputStream(new FileInputStream(f));   
    try {   
    in.read(...);   
    } finally {   
    try { in.close(); } catch (IOException e) { }   
    }   
    }
    

    数据库访问也涉及到类似的情况:

    Car getCar(DataSource ds, String plate) throws SQLException {   
    Car car = null;   
    Connection c = null;   
    PreparedStatement s = null;   
    ResultSet rs = null;   
    try {   
    c = ds.getConnection();   
    s = c.prepareStatement("select make, color from cars where plate=?");   
    s.setString(1, plate);   
    rs = s.executeQuery();   
    if (rs.next()) {   
    car = new Car();   
    car.make = rs.getString(1);   
    car.color = rs.getString(2);   
    }   
    } finally {   
    if (rs != null) try { rs.close(); } catch (SQLException e) { }   
    if (s != null) try { s.close(); } catch (SQLException e) { }   
    if (c != null) try { c.close(); } catch (SQLException e) { }   
    }   
    return car;   
    }
    

    finalize方法误用

    错误的写法:

    public class FileBackedCache {   
    private File backingStore;   
    
    ...   
    
    protected void finalize() throws IOException {   
    if (backingStore != null) {   
    backingStore.close();   
    backingStore = null;   
    }   
    }   
    }
    

    这个问题Effective Java这本书有详细的说明. 主要是finalize方法依赖于GC的调用, 其调用时机可能是立马也可能是几天以后, 所以是不可预知的. 而JDK的API文档中对这一点有误导:建议在该方法中来释放I/O资源。

    正确的做法是定义一个close方法, 然后由外部的容器来负责调用释放资源。

    public class FileBackedCache {   
    private File backingStore;   
    
    ...   
    
    public void close() throws IOException {   
    if (backingStore != null) {   
    backingStore.close();   
    backingStore = null;   
    }   
    }   
    }
    

    在JDK 1.7 (Java 7)中已经引入了一个AutoClosable接口. 当变量(不是对象)超出了try-catch的资源使用范围, 将自动调用close方法。

    try (Writer w = new FileWriter(f)) { // implements Closable   
    w.write("abc");   
    // w goes out of scope here: w.close() is called automatically in ANY case   
    } catch (IOException e) {   
    throw new RuntimeException(e.getMessage(), e);   
    }
    

    Thread.interrupted方法误用

    错误的写法:

    try {   
    Thread.sleep(1000);   
    } catch (InterruptedException e) {   
    // ok   
    }   
    or   
    while (true) {   
    if (Thread.interrupted()) break;   
    }
    

    这里主要是interrupted静态方法除了返回当前线程的中断状态, 还会将当前线程状态复位。

    正确的写法:

    try {   
    Thread.sleep(1000);   
    } catch (InterruptedException e) {   
    Thread.currentThread().interrupt();   
    }   
    or   
    while (true) {   
    if (Thread.currentThread().isInterrupted()) break;   
    }
    

    在静态变量初始化时创建线程

    错误的写法:

    class Cache {   
    private static final Timer evictor = new Timer();   
    }
    

    Timer构造器内部会new一个thread, 而该thread会从它的父线程(即当前线程)中继承各种属性。比如context classloader,

    ThreadLocal

    以及其他的安全属性(访问权限)。 而加载当前类的线程可能是不确定的,比如一个线程池中随机的一个线程。如果你需要控制线程的属性,最好的做法就是将其初始化操作放在一个静态方法中,这样初始化将由它的调用者来决定。

    正确的做法:

    class Cache {   
    private static Timer evictor;   
    public static setupEvictor() {   
    evictor = new Timer();   
    }   
    }
    

    已取消的定时器任务依然持有状态

    错误的写法:

    final MyClass callback = this;   
    TimerTask task = new TimerTask() {   
    public void run() {   
    callback.timeout();   
    }   
    };   
    timer.schedule(task, 300000L);   
    try {   
    doSomething();   
    } finally {   
    task.cancel();   
    }final MyClass callback = this;   
    TimerTask task = new TimerTask() {   
    public void run() {   
    callback.timeout();   
    }   
    };   
    timer.schedule(task, 300000L);   
    try {   
    doSomething();   
    } finally {   
    task.cancel();   
    }
    

    上面的task内部包含一个对外部类实例的应用, 这将导致该引用可能不会被GC立即回收. 因为Timer将保留TimerTask在指定的时间之后才被释放. 因此task对应的外部类实例将在5分钟后被回收。

    正确的写法:

    TimerTask task = new Job(this);   
    timer.schedule(task, 300000L);   
    try {   
    doSomething();   
    } finally {   
    task.cancel();   
    }   
    
    static class Job extends TimerTask {   
    private MyClass callback;   
    public Job(MyClass callback) {   
    this.callback = callback;   
    }   
    public boolean cancel() {   
    callback = null;   
    return super.cancel();   
    }   
    public void run() {   
    if (callback == null) return;   
    callback.timeout();   
    }   
    }
    

    欢迎加入学习交流群569772982,大家一起学习交流。

    相关文章

      网友评论

          本文标题:Java编程常见问题汇总(四)

          本文链接:https://www.haomeiwen.com/subject/zvzlixtx.html