Base64工具类并发问题!

为减少对象创建次数,一般会做如下编码:

public class EncodeUtils {
	private static BASE64Encoder encoder;
	private static BASE64Decoder decoder;
	
	public static boolean isNULLorEmpty(String str){
	  if(str==null||str.trim().equals(""))
		return true;
	  else
		return false;
	}
	
	/**
	 * 
	 * 方法名称:encode
	 * 功能说明:字符串数据进行BASE64加密
	 * @param str
	 * @return
	 */
	public static String encode(String str){
		if(encoder == null) encoder = new BASE64Encoder();
		return encoder.encode(str.getBytes());
	}
	
	/**
	 * 
	 * 方法名称:decode
	 * 功能说明:字符串数据进行BASE64解密
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public static String decode(String str) throws IOException {
		if(decoder==null) decoder = new BASE64Decoder();
		return new String(decoder.decodeBuffer(str));
	}
   
}

  这样写,看似没问题,但是在高并发下会存在问题,同一字符串解码出来的信息不一致,BASE64Encoder、BASE64Decoder 不是线程安全的类

所以可以按如下修改,有两种方案,一种是每次都重新创建个对象,另外一种是替换jra包,不用jre带的,用org.apache.commons.codec下的base64,这个是线程安全的类

修改如下:

	/**
	 * 
	 * 方法名称:decode
	 * 功能说明:字符串数据进行BASE64解密
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public static String decode(String str) throws IOException {
		return new String(new BASE64Decoder().decodeBuffer(str));
	}

  或者换jar包

public class EncodeUtils {

    private static Base64 base64 = new Base64();
    
    
/**
     * 
     * 方法名称:decode
     * 功能说明:字符串数据进行BASE64解密
     * @param str
     * @return
     * @throws IOException
     */
    public static String decode(String str) throws IOException {
        return new String (base64.decode(str));
    }
   
}

原文地址:https://www.cnblogs.com/foreverYoungCoder/p/9166416.html