Java Common Class

Exception

Error & Exception

  • error:致命系统错误,编辑器不检查
  • exception:程序可以处理的异常,可被捕获和恢复

exception

  • RuntimeException:不可预知的,程序应当避免
  • 非RuntimeException:可预知,从编译器校验的异常

Common Exception

commonexception

异常处理机制

  • 抛出异常:创建异常对象,交由运行时系统处理
  • 捕获异常:寻找合适的异常处理器处理异常,否则终止程序
package com.interview.javabasic.throwable;

public class ExceptionHandleMechanism {
    public static void doWork() {
        try {
            int i = 10 / 0;    //会抛出异常
            System.out.println("i=" + i);
        } catch (ArithmeticException e) {
            //捕获 Exception
            System.out.println("ArithmeticException: " + e);
        } finally {
            System.out.println("Finally");
        }
    }
    public static void main(String[] args) {
        doWork();
        System.out.println("Mission Complete");
    }
}
  • finally先于return执行
  • 尽量不要捕获通用异常
  • 异常一定要处理,不要生吞异常
  • 提早抛出,方便精确定位
  • 延时处理,用更大的信息域处理异常

异常统一处理

handler

try-catch

  • try-catch耗时大于if

Data Structure

listset

  • arraylist没有用到lock与synchronized,并发不安全
  • vector大量synchronized,效率低,并发性差,矛盾,弃用
  • 没有用到lock与synchronized

Set实现两种比较

  • 自然排序
package com.interview.javabasic.collection;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class Customer implements Comparable{
    private String name;

    private int age;

    public Customer(String name, int age) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!(obj instanceof Customer))
            return false;
        final Customer other = (Customer) obj;

        if (this.name.equals(other.getName()) && this.age == other.getAge())
            return true;
        else
            return false;
    }
    @Override
    public int compareTo(Object o) {
        Customer other = (Customer) o;

        // 先按照name属性排序
        if (this.name.compareTo(other.getName()) > 0)
            return 1;
        if (this.name.compareTo(other.getName()) < 0)
            return -1;

        // 在按照age属性排序
        if (this.age > other.getAge())
            return 1;
        if (this.age < other.getAge())
            return -1;
        return 0;

    }

    @Override
    public int hashCode() {
        int result;
        result = (name == null ? 0 : name.hashCode());
        result = 29 * result + age;
        return result;
    }
    public static void main(String[] args) {
        Set<Customer> set = new TreeSet<Customer>();
        Customer customer1 = new Customer("Tom", 16);
        Customer customer2 = new Customer("Tom", 15);
        set.add(customer1);
        set.add(customer2);
        for(Customer c : set){
            System.out.println(c.name + " " + c.age);
        }
    }
}
  • 客户化排序(共存优先)
package com.interview.javabasic.collection;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class CustomerComparator implements Comparator<Customer> {
    @Override
    public int compare(Customer c1, Customer c2) {
        if(c1.getName().compareTo(c2.getName())>0)return -1;
        if(c1.getName().compareTo(c2.getName())<0)return 1;
        return 0;
    }

    public static void main(String args[]){
        Set<Customer> set = new TreeSet<Customer>(new CustomerComparator());

        Customer customer1= new Customer("Tom",5);
        Customer customer2= new Customer("Tom",9);
        Customer customer3= new Customer("Tom",2);
        set.add(customer1);
        set.add(customer2);
        set.add(customer3);
        Iterator<Customer> it = set.iterator();
        while(it.hasNext()){
            Customer customer = it.next();
            System.out.println(customer.getName()+" "+customer.getAge());
        }
    }
}

Map

map

HashMap

  • 散列表

hash

  • 性能恶化O(1)-O(N)

hash2

  • put

put

  • hashmap :减少碰撞
  • 扰动函数
  • 使用final对象,采用合适的equals,hashcode方法
  • 多线程下,调整大小可能造成死锁

HashTable

  • 线程安全
  • 涉及到修改hashtable的方法synchronized实现
  • 串行化运行,效率低

ConcurrentHashMap

  • 曾经:segment分段锁
  • 当前

cmap

cput

csum

sum

IO

AIO,BIO,NIO

  • BIO

bio

package com.interview.javabasic.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOPlainEchoServer {
    public void serve(int port) throws IOException {
        //将ServerSocket绑定到指定的端口里
        final ServerSocket socket = new ServerSocket(port);
        while (true) {
            //阻塞直到收到新的客户端连接
            final Socket clientSocket = socket.accept();
            System.out.println("Accepted connection from " + clientSocket);
            //创建一个子线程去处理客户端的请求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
                        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                        //从客户端读取数据并原封不动回写回去
                        while (true) {
                            writer.println(reader.readLine());
                            writer.flush();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    public void improvedServe(int port) throws IOException {
        //将ServerSocket绑定到指定的端口里
        final ServerSocket socket = new ServerSocket(port);
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        while (true) {
            //阻塞直到收到新的客户端连接
            final Socket clientSocket = socket.accept();
            System.out.println("Accepted connection from " + clientSocket);
            //将请求提交给线程池去执行
            executorService.execute(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
                    PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                    //从客户端读取数据并原封不动回写回去
                    while (true) {
                        writer.println(reader.readLine());
                        writer.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
  • NIO

nio

核心:

  • channels
  • buffers
  • selectors

selector

package com.interview.javabasic.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOPlainEchoServer {
    public void serve(int port) throws IOException {
        System.out.println("Listening for connections on port " + port);
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        ServerSocket ss = serverChannel.socket();
        InetSocketAddress address = new InetSocketAddress(port);
        //将ServerSocket绑定到指定的端口里
        ss.bind(address);
        serverChannel.configureBlocking(false);
        Selector selector = Selector.open();
        //将channel注册到Selector里,并说明让Selector关注的点,这里是关注建立连接这个事件
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            try {
                //阻塞等待就绪的Channel,即没有与客户端建立连接前就一直轮询
                selector.select();
            } catch (IOException ex) {
                ex.printStackTrace();
                //代码省略的部分是结合业务,正确处理异常的逻辑
                break;
            }
            //获取到Selector里所有就绪的SelectedKey实例,每将一个channel注册到一个selector就会产生一个SelectedKey
            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readyKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = (SelectionKey) iterator.next();
                //将就绪的SelectedKey从Selector中移除,因为马上就要去处理它,防止重复执行
                iterator.remove();
                try {
                    //若SelectedKey处于Acceptable状态
                    if (key.isAcceptable()) {
                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        //接受客户端的连接
                        SocketChannel client = server.accept();
                        System.out.println("Accepted connection from " + client);
                        client.configureBlocking(false);
                        //像selector注册socketchannel,主要关注读写,并传入一个ByteBuffer实例供读写缓存
                        client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, ByteBuffer.allocate(100));
                    }
                    //若SelectedKey处于可读状态
                    if (key.isReadable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer output = (ByteBuffer) key.attachment();
                        //从channel里读取数据存入到ByteBuffer里面
                        client.read(output);
                    }
                    //若SelectedKey处于可写状态
                    if (key.isWritable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer output = (ByteBuffer) key.attachment();
                        output.flip();
                        //将ByteBuffer里的数据写入到channel里
                        client.write(output);
                        output.compact();
                    }
                } catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    } catch (IOException cex) {
                    }
                }
            }
        }
    }
}
  • AIO

aio

实现:

  • 基于回调,实现completionhandler,触发回调函数
  • 返回future

compare

  • Copyrights © 2019-2020 Rex