Java Charset Create getEncoder()

Here you can find the source of getEncoder()

Description

get Encoder

License

Apache License

Declaration

public static CharsetEncoder getEncoder() 

Method Source Code


//package com.java2s;
/*/*from  w w w. j  a  v a 2 s.c  o  m*/
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */

import java.lang.ref.SoftReference;
import java.nio.charset.Charset;

import java.nio.charset.CharsetEncoder;

public class Main {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private static ThreadLocal<CharsetEncoder> encoderCache = new ThreadLocal<CharsetEncoder>();

    public static CharsetEncoder getEncoder() {
        CharsetEncoder encoder = (CharsetEncoder) getReference(encoderCache);
        if (encoder == null) {
            encoder = UTF8.newEncoder();
            setReference(encoderCache, encoder);
        }
        return encoder;
    }

    private static Object getReference(ThreadLocal threadLocal) {
        SoftReference reference = (SoftReference) threadLocal.get();
        if (reference == null)
            return null;
        return reference.get();
    }

    private static void setReference(ThreadLocal threadLocal, Object object) {
        threadLocal.set(new SoftReference(object));
    }
}

Related

  1. getDefaultCharset()
  2. getDefaultCharsetName()
  3. getDefaultSystemCharset()
  4. getEncodedStringLength(String str)
  5. getEncodedUrl(String unEncodedUrl)
  6. getEncoder()
  7. getEncoder()
  8. getEncoder(String encoding)
  9. getEncoding(byte[] htmlData)