Java

Java. 1

1.     Source. 1

2.     java.lang. 1

2.1 java.lang.Class. 1

2.1.1 Atomic. 1

2.1.2 AnnotationData. 1

2.1.3 ReflectionData. 1

2.2 java.lang. Object 1

2.3 java.lang.Runnable. 1

2.4 java.lang.Thread. 1

2.4.1 thread. 1

2.4.2 init 1

2.4.3 State. 1

2.4.4 start 1

2.4.5 run. 1

2.4.6 join. 1

2.4.7 yield. 1

2.4.8 resume. 1

2.4.9 sleep. 1

2.4.10 interrupt 1

2.4.11 suspend. 1

2.4.12 stop. 1

2.5 java.lang.annotation. 1

2.6 java.lang.reflect 1

2.6.1 java.lang.reflect.Member 1

2.6.2 java.lang.reflect.GenericDeclaration. 1

2.6.3 java.lang.reflect.AnnotatedElement 1

2.6.4 java.lang.reflect.Executable. 1

2.6.5 java.lang.reflect.AccessibleObject 1

2.6.6 java.lang.reflect.Constructor 1

2.6.7 java.lang.reflect.Field. 1

2.6.8 java.lang.reflect.Mehod. 1

2.6.9 java.lang.reflect.Parameter 1

2.6.10 java.lang.reflect.Proxy. 1

2.6.11 java.lang.reflect.WeakCache. 1

2.7 java.lang.Comparable. 1

2.8 java.lang. CharSequence. 1

2.9 java.lang.String. 1

2.10 Java.lang. Appendable. 1

2.11 java.lang. AbstractStringBuilder 1

2.12 java.lang.StringBuilder 1

2.13 java.lang.StringBuffer 1

3.     java.io. 1

3.1 java.io. DataInput 1

3.2 java.io. ObjectInput 1

3.3 java.io. DataOutput 1

3.4 java.io. ObjectOutput 1

3.5 java.lang. AutoCloseable. 1

3.6 java.io. FilterInputStream.. 1

3.7 java.io. DataInputStream.. 1

3.8 java.io. SocketInputStream.. 1

3.9 java.io. ObjectOutputStream.. 1

3.9.1 java.io. ObjectOutputStream. BlockDataOutputStream.. 1

3.10 java.io. File. 1

3.11 java.io. FileDescriptor 1

3.12 java.io. FileSystem.. 1

3.13 java.io. DefaultFileSystem.. 1

3.14 java.io.WinNTFileSystem.. 1

3.15 java.io. FileOutputStream.. 1

4.     java.net 1

4.1 java.io.Closeable. 1

4.2 java.net. SocketOptions. 1

4.3 java.net. SocketImpl 1

4.4 java.net. AbstractPlainSocketImpl 1

4.5 java.net. Socket 1

4.6 java.net. ServerSocket 1

4.7 java.net. proxy. 1

5.     java.nio. 1

5.1 java.nio.channels.Channel 1

5.2 java.nio.channels. SelectableChannel 1

5.3 java.nio.channels. AbstractSelectableChannel 1

5.4 java.nio.channels. ServerSocketChannel 1

5.5 java.nio.channels.SelectionKey. 1

5.6 sun.nio.ch.WindowsSelectorImpl 1

5.7 sun.nio.ch.WindowsSelectorImpl. SubSelector 1

6.     java.util 1

6.1 java.util.Iterable. 1

6.2 java.util.Collection. 1

6.3 java.util.List 1

6.4 java.util. Queue. 1

6.5 java.util. Deque. 1

6.6 java.util. AbstractCollection. 1

6.7 java.util. AbstractList 1

6.8 java.util. AbstractSequentialList 1

6.9 Java.util.LinkedList 1

6.9.1 Node. 1

6.9.2 DescendingIterator 1

6.9.3 LLSpliterator 1

6.10 java.util.ArrayList 1

6.11 java.util.Map. 1

6.11.1 Entry. 1

6.12 java.util. AbstractMap. 1

6.13 java.util. SortedMap. 1

6.14 java.util. NavigableMap. 1

6.15 java.util.HashMap. 1

6.15.1 KeySet 1

6.15.2 EntrySet 1

6.15.3 Node. 1

6.15.4 TreeNode. 1

6.16 java.util.TreeMap. 1

6.17 Java.util.Set 1

6.18 java.util. AbstractSet 1

6.19 java.util. HashSet 1

6.20 java.util. TreeSet 1

6.21 Java.util. ServiceLoader 1

6.22 java.util.concurrent 1

6.22.1 java.util.concurrent. Semaphore. 1

6.22.1.1 java.util.concurrent. Semaphore. FairSync. 1

6.22.1.2 java.util.concurrent. Semaphore. NonfairSync. 1

6.22.2 java.util.concurrent. CyclicBarrier 1

6.22.3 java.util.concurrent. CountDownLatch. 1

6.22.4 java.util.concurrent. Executor 1

6.22.5 java.util.concurrent. Executors. 1

6.22.6 java.util.concurrent. AbstractExecutorService. 1

6.22.7 java.util.concurrent. Future. 1

6.22.8 java.util.concurrent. ForkJoinTask. 1

6.22.9 java.util.concurrent. ForkJoinPool 1

6.22.10 java.util.concurrent.locks. 1

6.22.10.1 java.util.concurrent.locks.lock. 1

6.22.10.2 java.util.concurrent.locks. LockSupport 1

6.22.10.3 java.util.concurrent.locks. AbstractOwnableSynchronizer 1

6.22.10.4 java.util.concurrent.locks. AbstractQueuedSynchronizer 1

6.22.10.5 java.util.concurrent.locks. ReentrantLock. 1

6.22.10.6 java.util.concurrent.locks. Condition. 1

6.22.10.7 java.util.concurrent.locks. ReentrantReadWriteLock. 1

6.22.11 java.util.concurrent.atomic. 1

6.22.11.1 java.util.concurrent.atomic. AtomicInteger 1

6.22.11.2 java.util.concurrent.atomic. AtomicReference. 1

7.     References. 1

 

1.    Source

Java Version jdk1.8

 

2.    java.lang

2.1 java.lang.Class

java.lang.Class

 

public final class Class<T> implements java.io.Serializable,

                              GenericDeclaration,

                              Type,

                              AnnotatedElement {

    private static final int ANNOTATION= 0x00002000;

    private static final int ENUM      = 0x00004000;

    private static final int SYNTHETIC = 0x00001000;

 

private Class(ClassLoader loader) {

        classLoader = loader;

    }

   @CallerSensitive

    public static Class<?> forName(String className)

                throws ClassNotFoundException {

        Class<?> caller = Reflection.getCallerClass();

        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);

    }

  @CallerSensitive

    public Constructor<T> getConstructor(Class<?>... parameterTypes)

        throws NoSuchMethodException, SecurityException {

        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);

        return getConstructor0(parameterTypes, Member.PUBLIC);

    }

   @Override

    @SuppressWarnings("unchecked")

    public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {

        Objects.requireNonNull(annotationClass);

 

        return (A) annotationData().declaredAnnotations.get(annotationClass);

    }

    @CallerSensitive

    public Field getDeclaredField(String name)

        throws NoSuchFieldException, SecurityException {

        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);

        Field field = searchFields(privateGetDeclaredFields(false), name);

        if (field == null) {

            throw new NoSuchFieldException(name);

        }

        return field;

    }

@CallerSensitive

    public Method getDeclaredMethod(String name, Class<?>... parameterTypes)

        throws NoSuchMethodException, SecurityException {

        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);

        Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);

        if (method == null) {

            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));

        }

        return method;

    }

 

2.1.1 Atomic

java.lang.Class.Atomic

private static class Atomic {

        // initialize Unsafe machinery here, since we need to call Class.class instance method

        // and have to avoid calling it in the static initializer of the Class class...

        private static final Unsafe unsafe = Unsafe.getUnsafe();

        // offset of Class.reflectionData instance field

        private static final long reflectionDataOffset;

        // offset of Class.annotationType instance field

        private static final long annotationTypeOffset;

        // offset of Class.annotationData instance field

        private static final long annotationDataOffset;

 

        static {

            Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches

            reflectionDataOffset = objectFieldOffset(fields, "reflectionData");

            annotationTypeOffset = objectFieldOffset(fields, "annotationType");

            annotationDataOffset = objectFieldOffset(fields, "annotationData");

        }

 

        private static long objectFieldOffset(Field[] fields, String fieldName) {

            Field field = searchFields(fields, fieldName);

            if (field == null) {

                throw new Error("No " + fieldName + " field found in java.lang.Class");

            }

            return unsafe.objectFieldOffset(field);

        }

 

        static <T> boolean casReflectionData(Class<?> clazz,

                                             SoftReference<ReflectionData<T>> oldData,

                                             SoftReference<ReflectionData<T>> newData) {

            return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);

        }

 

        static <T> boolean casAnnotationType(Class<?> clazz,

                                             AnnotationType oldType,

                                             AnnotationType newType) {

            return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);

        }

 

        static <T> boolean casAnnotationData(Class<?> clazz,

                                             AnnotationData oldData,

                                             AnnotationData newData) {

            return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);

        }

    }

2.1.2 AnnotationData

java.lang. Class. AnnotationData的主要属性

 

private static class AnnotationData {

        final Map<Class<? extends Annotation>, Annotation> annotations;

        final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;

 

        // Value of classRedefinedCount when we created this AnnotationData instance

        final int redefinedCount;

 

        AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,

                       Map<Class<? extends Annotation>, Annotation> declaredAnnotations,

                       int redefinedCount) {

            this.annotations = annotations;

            this.declaredAnnotations = declaredAnnotations;

            this.redefinedCount = redefinedCount;

        }

    }

 

    // Annotations cache

    @SuppressWarnings("UnusedDeclaration")

    private volatile transient AnnotationData annotationData;

 

    private AnnotationData annotationData() {

        while (true) { // retry loop

            AnnotationData annotationData = this.annotationData;

            int classRedefinedCount = this.classRedefinedCount;

            if (annotationData != null &&

                annotationData.redefinedCount == classRedefinedCount) {

                return annotationData;

            }

            // null or stale annotationData -> optimistically create new instance

            AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);

            // try to install it

            if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {

                // successfully installed new AnnotationData

                return newAnnotationData;

            }

        }

}

private AnnotationData createAnnotationData(int classRedefinedCount) {

        Map<Class<? extends Annotation>, Annotation> declaredAnnotations =

            AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);

        Class<?> superClass = getSuperclass();

        Map<Class<? extends Annotation>, Annotation> annotations = null;

        if (superClass != null) {

            Map<Class<? extends Annotation>, Annotation> superAnnotations =

                superClass.annotationData().annotations;

            for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {

                Class<? extends Annotation> annotationClass = e.getKey();

                if (AnnotationType.getInstance(annotationClass).isInherited()) {

                    if (annotations == null) { // lazy construction

                        annotations = new LinkedHashMap<>((Math.max(

                                declaredAnnotations.size(),

                                Math.min(12, declaredAnnotations.size() + superAnnotations.size())

                            ) * 4 + 2) / 3

                        );

                    }

                    annotations.put(annotationClass, e.getValue());

                }

            }

        }

        if (annotations == null) {

            // no inherited annotations -> share the Map with declaredAnnotations

            annotations = declaredAnnotations;

        } else {

            // at least one inherited annotation -> declared may override inherited

            annotations.putAll(declaredAnnotations);

        }

        return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);

    }

 

 

2.1.3 ReflectionData

java.lang. Class. ReflectionData

 

  private static class ReflectionData<T> {

        volatile Field[] declaredFields;

        volatile Field[] publicFields;

        volatile Method[] declaredMethods;

        volatile Method[] publicMethods;

        volatile Constructor<T>[] declaredConstructors;

        volatile Constructor<T>[] publicConstructors;

        // Intermediate results for getFields and getMethods

        volatile Field[] declaredPublicFields;

        volatile Method[] declaredPublicMethods;

        volatile Class<?>[] interfaces;

 

        // Cached names

        String simpleName;

        String canonicalName;

        static final String NULL_SENTINEL = new String();

 

        // Value of classRedefinedCount when we created this ReflectionData instance

        final int redefinedCount;

 

        ReflectionData(int redefinedCount) {

            this.redefinedCount = redefinedCount;

        }

    }

 

    private transient volatile SoftReference<ReflectionData<T>> reflectionData;

 

    // Incremented by the VM on each call to JVM TI RedefineClasses()

    // that redefines this class or a superclass.

    private transient volatile int classRedefinedCount;

 

    // Lazily create and cache ReflectionData

    private ReflectionData<T> reflectionData() {

        SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;

        int classRedefinedCount = this.classRedefinedCount;

        ReflectionData<T> rd;

        if (reflectionData != null &&

            (rd = reflectionData.get()) != null &&

            rd.redefinedCount == classRedefinedCount) {

            return rd;

        }

        // else no SoftReference or cleared SoftReference or stale ReflectionData

        // -> create and replace new instance

        return newReflectionData(reflectionData, classRedefinedCount);

    }

 

    private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,

                                                int classRedefinedCount) {

        while (true) {

            ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);

            // try to CAS it...

            if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {

                return rd;

            }

            // else retry

            oldReflectionData = this.reflectionData;

            classRedefinedCount = this.classRedefinedCount;

            if (oldReflectionData != null &&

                (rd = oldReflectionData.get()) != null &&

                rd.redefinedCount == classRedefinedCount) {

                return rd;

            }

        }

}

 

2.2 java.lang. Object

java.lang. Object

public class Object {

    private static native void registerNatives();

    static {

        registerNatives();

    }

    public final native Class<?> getClass();

    public native int hashCode();

    public boolean equals(Object obj) {

        return (this == obj);

    }

    protected native Object clone() throws CloneNotSupportedException;

    public String toString() {

        return getClass().getName() + "@" + Integer.toHexString(hashCode());

    }

    public final native void notify();

    public final native void notifyAll();

    public final native void wait(long timeout) throws InterruptedException;

    public final void wait(long timeout, int nanos) throws InterruptedException {

        if (timeout < 0) {

            throw new IllegalArgumentException("timeout value is negative");

        }

 

        if (nanos < 0 || nanos > 999999) {

            throw new IllegalArgumentException(

                                "nanosecond timeout value out of range");

        }

 

        if (nanos > 0) {

            timeout++;

        }

        wait(timeout);

    }

    public final void wait() throws InterruptedException {

        wait(0);

    }

    protected void finalize() throws Throwable { }

}

 

 

 

2.3 java.lang.Runnable

线程java.lang.Runnable

 

@FunctionalInterface

public interface Runnable {

    public abstract void run();

}

 

 

2.4 java.lang.Thread

2.4.1 thread

 

线程java.lang.Thread的主要属性

Public class Thread implements Runnable {

    private volatile String name;

    private boolean     daemon = false;

    private ThreadGroup group;

    private ClassLoader contextClassLoader;

    ThreadLocal.ThreadLocalMap threadLocals = null;

    private long stackSize;

private long tid;// Thread ID

    /* For generating thread ID */

private static long threadSeqNumber;

}

2.4.2 init

 

线程java.lang.Thread的主要init方法

 

    public Thread(ThreadGroup group, Runnable target) {

        init(group, target, "Thread-" + nextThreadNum(), 0);

    }

    private void init(ThreadGroup g, Runnable target, String name,

                      long stackSize, AccessControlContext acc,

                      boolean inheritThreadLocals) {

        if (name == null) {

            throw new NullPointerException("name cannot be null");

        }

 

        this.name = name;

 

        Thread parent = currentThread();

        SecurityManager security = System.getSecurityManager();

        if (g == null) {

            /* Determine if it's an applet or not */

 

            /* If there is a security manager, ask the security manager

               what to do. */

            if (security != null) {

                g = security.getThreadGroup();

            }

 

            /* If the security doesn't have a strong opinion of the matter

               use the parent thread group. */

            if (g == null) {

                g = parent.getThreadGroup();

            }

        }

 

        /* checkAccess regardless of whether or not threadgroup is

           explicitly passed in. */

        g.checkAccess();

 

        /*

         * Do we have the required permissions?

         */

        if (security != null) {

            if (isCCLOverridden(getClass())) {

                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);

            }

        }

 

        g.addUnstarted();

 

        this.group = g;

        this.daemon = parent.isDaemon();

        this.priority = parent.getPriority();

        if (security == null || isCCLOverridden(parent.getClass()))

            this.contextClassLoader = parent.getContextClassLoader();

        else

            this.contextClassLoader = parent.contextClassLoader;

        this.inheritedAccessControlContext =

                acc != null ? acc : AccessController.getContext();

        this.target = target;

        setPriority(priority);

        if (inheritThreadLocals && parent.inheritableThreadLocals != null)

            this.inheritableThreadLocals =

                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

        /* Stash the specified stack size in case the VM cares */

        this.stackSize = stackSize;

 

        /* Set thread ID */

        tid = nextThreadID();

    }

 

2.4.3 State

 

线程java.lang.Thread .Statestate

 

  public enum State {

        /**

         * Thread state for a thread which has not yet started.

         */

        NEW,

 

        /**

         * Thread state for a runnable thread.  A thread in the runnable

         * state is executing in the Java virtual machine but it may

         * be waiting for other resources from the operating system

         * such as processor.

         */

        RUNNABLE,

 

        /**

         * Thread state for a thread blocked waiting for a monitor lock.

         * A thread in the blocked state is waiting for a monitor lock

         * to enter a synchronized block/method or

         * reenter a synchronized block/method after calling

         * {@link Object#wait() Object.wait}.

         */

        BLOCKED,

 

        /**

         * Thread state for a waiting thread.

         * A thread is in the waiting state due to calling one of the

         * following methods:

         * <ul>

         *   <li>{@link Object#wait() Object.wait} with no timeout</li>

         *   <li>{@link #join() Thread.join} with no timeout</li>

         *   <li>{@link LockSupport#park() LockSupport.park}</li>

         * </ul>

         *

         * <p>A thread in the waiting state is waiting for another thread to

         * perform a particular action.

         *

         * For example, a thread that has called <tt>Object.wait()</tt>

         * on an object is waiting for another thread to call

         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on

         * that object. A thread that has called <tt>Thread.join()</tt>

         * is waiting for a specified thread to terminate.

         */

        WAITING,

 

        /**

         * Thread state for a waiting thread with a specified waiting time.

         * A thread is in the timed waiting state due to calling one of

         * the following methods with a specified positive waiting time:

         * <ul>

         *   <li>{@link #sleep Thread.sleep}</li>

         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>

         *   <li>{@link #join(long) Thread.join} with timeout</li>

         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>

         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>

         * </ul>

         */

        TIMED_WAITING,

 

        /**

         * Thread state for a terminated thread.

         * The thread has completed execution.

         */

        TERMINATED;

    }

 

2.4.4 start

 

线程java.lang.Thread start

 

public synchronized void start() {

        if (threadStatus != 0)

            throw new IllegalThreadStateException();

        group.add(this);

 

        boolean started = false;

        try {

            start0();

            started = true;

        } finally {

            try {

                if (!started) {

                    group.threadStartFailed(this);

                }

            } catch (Throwable ignore) {

            }

        }

    }

 

    private native void start0();

 

2.4.5 run

 

线程java.lang.Thread run

public void run() {

        if (target != null) {

            target.run();

        }

    }

2.4.6 join

 

线程java.lang.Thread join

public final synchronized void join(long millis)

    throws InterruptedException {

        long base = System.currentTimeMillis();

        long now = 0;

 

        if (millis < 0) {

            throw new IllegalArgumentException("timeout value is negative");

        }

 

        if (millis == 0) {

            while (isAlive()) {

                wait(0);

            }

        } else {

            while (isAlive()) {

                long delay = millis - now;

                if (delay <= 0) {

                    break;

                }

                wait(delay);

                now = System.currentTimeMillis() - base;

            }

        }

    }

 

2.4.7 yield

线程java.lang.Thread yield

    public static native void yield();

2.4.8 resume

线程java.lang.Thread resume

  @Deprecated

    public final void resume() {

        checkAccess();

        resume0();

    }

    private native void resume0();

 

2.4.9 sleep

线程java.lang.Thread sleep

  public static native void sleep(long millis) throws InterruptedException;

 

2.4.10 interrupt

线程java.lang.Thread interrupt

    public void interrupt() {

        if (this != Thread.currentThread())

            checkAccess();

 

        synchronized (blockerLock) {

            Interruptible b = blocker;

            if (b != null) {

                interrupt0();           // Just to set the interrupt flag

                b.interrupt(this);

                return;

            }

        }

        interrupt0();

    }

private native void interrupt0();

2.4.11 suspend

线程java.lang.Thread suspend

  @Deprecated

    public final void suspend() {

        checkAccess();

        suspend0();

}

  private native void suspend0();

2.4.12 stop

 

线程java.lang.Thread stop

public final void stop() {

        SecurityManager security = System.getSecurityManager();

        if (security != null) {

            checkAccess();

            if (this != Thread.currentThread()) {

                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);

            }

        }

        // A zero status value corresponds to "NEW", it can't change to

        // not-NEW because we hold the lock.

        if (threadStatus != 0) {

            resume(); // Wake up thread if it was suspended; no-op otherwise

        }

 

        // The VM can handle all thread states

        stop0(new ThreadDeath());

    }

   private native void stop0(Object o);

 

2.5 java.lang.annotation

 

 

 

 

 

2.6 java.lang.reflect

2.6.1 java.lang.reflect.Member

java.lang.reflect.Member

public interface Member {

    public static final int PUBLIC = 0;

    public static final int DECLARED = 1;

    public Class<?> getDeclaringClass();

    public String getName();

    public int getModifiers();

    public boolean isSynthetic();

}

 

2.6.2 java.lang.reflect.GenericDeclaration

java.lang.reflect. GenericDeclaration

 

public interface GenericDeclaration extends AnnotatedElement {

    public TypeVariable<?>[] getTypeParameters();

}

 

2.6.3 java.lang.reflect.AnnotatedElement

java.lang.reflect. AnnotatedElement

 

 

public interface AnnotatedElement {

    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {

        return getAnnotation(annotationClass) != null;

    }

    <T extends Annotation> T getAnnotation(Class<T> annotationClass);

    Annotation[] getAnnotations();

    Annotation[] getDeclaredAnnotations();

}

 

 

2.6.4 java.lang.reflect.Executable

java.lang.reflect. Executable

public abstract class Executable extends AccessibleObject

    implements Member, GenericDeclaration {

    Executable() {}

    private native Parameter[] getParameters0();

    native byte[] getTypeAnnotationBytes0();

}

 

 

2.6.5 java.lang.reflect.AccessibleObject

java.lang.reflect. AccessibleObject

 

public class AccessibleObject implements AnnotatedElement {

    static final private java.security.Permission ACCESS_PERMISSION =

        new ReflectPermission("suppressAccessChecks");

    public static void setAccessible(AccessibleObject[] array, boolean flag)

        throws SecurityException {

        SecurityManager sm = System.getSecurityManager();

        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);

        for (int i = 0; i < array.length; i++) {

            setAccessible0(array[i], flag);

        }

    }

    public void setAccessible(boolean flag) throws SecurityException {

        SecurityManager sm = System.getSecurityManager();

        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);

        setAccessible0(this, flag);

    }

    private static void setAccessible0(AccessibleObject obj, boolean flag)

        throws SecurityException

    {

        if (obj instanceof Constructor && flag == true) {

            Constructor<?> c = (Constructor<?>)obj;

            if (c.getDeclaringClass() == Class.class) {

                throw new SecurityException("Cannot make a java.lang.Class" +

                                            " constructor accessible");

            }

        }

        obj.override = flag;

    }

    public boolean isAccessible() {

        return override;

    }

    protected AccessibleObject() {}

}

 

2.6.6 java.lang.reflect.Constructor

java.lang.reflect. Constructor

 

public final class Constructor<T> extends Executable {

    private Class<T>            clazz;

    private int                 slot;

    private Class<?>[]          parameterTypes;

    private Class<?>[]          exceptionTypes;

    private int                 modifiers;

    // Generics and annotations support

    private transient String    signature;

    // generic info repository; lazily initialized

    private transient ConstructorRepository genericInfo;

    private byte[]              annotations;

    private byte[]              parameterAnnotations;

    public T newInstance(Object ... initargs)

        throws InstantiationException, IllegalAccessException,

               IllegalArgumentException, InvocationTargetException

    {

        if (!override) {

            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {

                Class<?> caller = Reflection.getCallerClass();

                checkAccess(caller, clazz, null, modifiers);

            }

        }

        if ((clazz.getModifiers() & Modifier.ENUM) != 0)

            throw new IllegalArgumentException("Cannot reflectively create enum objects");

        ConstructorAccessor ca = constructorAccessor;   // read volatile

        if (ca == null) {

            ca = acquireConstructorAccessor();

        }

        @SuppressWarnings("unchecked")

        T inst = (T) ca.newInstance(initargs);

        return inst;

    }

}

 

 

2.6.7 java.lang.reflect.Field

java.lang.reflect.Field

 

public final

class Field extends AccessibleObject implements Member {

 

    private Class<?>            clazz;

    private int                 slot;

    private String              name;

    private Class<?>            type;

    private int                 modifiers;

    // Generics and annotations support

    private transient String    signature;

    // generic info repository; lazily initialized

    private transient FieldRepository genericInfo;

    private byte[]              annotations;

    // Cached field accessor created without override

    private FieldAccessor fieldAccessor;

    // Cached field accessor created with override

    private FieldAccessor overrideFieldAccessor;

private Field               root;

   Field(Class<?> declaringClass,

          String name,

          Class<?> type,

          int modifiers,

          int slot,

          String signature,

          byte[] annotations)

    {

        this.clazz = declaringClass;

        this.name = name;

        this.type = type;

        this.modifiers = modifiers;

        this.slot = slot;

        this.signature = signature;

        this.annotations = annotations;

}

  private void setFieldAccessor(FieldAccessor accessor, boolean overrideFinalCheck) {

        if (overrideFinalCheck)

            overrideFieldAccessor = accessor;

        else

            fieldAccessor = accessor;

        // Propagate up

        if (root != null) {

            root.setFieldAccessor(accessor, overrideFinalCheck);

        }

    }

 

}

 

2.6.8 java.lang.reflect.Mehod

java.lang.reflect. Method

 

 

public final class Method extends Executable {

    private Class<?>            clazz;

    private int                 slot;

    // This is guaranteed to be interned by the VM in the 1.4

    // reflection implementation

    private String              name;

    private Class<?>            returnType;

    private Class<?>[]          parameterTypes;

    private Class<?>[]          exceptionTypes;

    private int                 modifiers;

    // Generics and annotations support

    private transient String              signature;

    // generic info repository; lazily initialized

    private transient MethodRepository genericInfo;

    private byte[]              annotations;

    private byte[]              parameterAnnotations;

    private byte[]              annotationDefault;

    private volatile MethodAccessor methodAccessor;

    private Method              root;

 

    // Generics infrastructure

    private String getGenericSignature() {return signature;}

 

    // Accessor for factory

    private GenericsFactory getFactory() {

        // create scope and factory

        return CoreReflectionFactory.make(this, MethodScope.make(this));

    }

 

    // Accessor for generic info repository

    @Override

    MethodRepository getGenericInfo() {

        // lazily initialize repository if necessary

        if (genericInfo == null) {

            // create and cache generic info repository

            genericInfo = MethodRepository.make(getGenericSignature(),

                                                getFactory());

        }

        return genericInfo; //return cached repository

    }

    Method(Class<?> declaringClass,

           String name,

           Class<?>[] parameterTypes,

           Class<?> returnType,

           Class<?>[] checkedExceptions,

           int modifiers,

           int slot,

           String signature,

           byte[] annotations,

           byte[] parameterAnnotations,

           byte[] annotationDefault) {

        this.clazz = declaringClass;

        this.name = name;

        this.parameterTypes = parameterTypes;

        this.returnType = returnType;

        this.exceptionTypes = checkedExceptions;

        this.modifiers = modifiers;

        this.slot = slot;

        this.signature = signature;

        this.annotations = annotations;

        this.parameterAnnotations = parameterAnnotations;

        this.annotationDefault = annotationDefault;

}

    void setMethodAccessor(MethodAccessor accessor) {

        methodAccessor = accessor;

        // Propagate up

        if (root != null) {

            root.setMethodAccessor(accessor);

        }

    }

}

 

2.6.9 java.lang.reflect.Parameter

java.lang.reflect. Parameter

 

public final class Parameter implements AnnotatedElement {

 

    private final String name;

    private final int modifiers;

    private final Executable executable;

    private final int index;

    Parameter(String name,

              int modifiers,

              Executable executable,

              int index) {

        this.name = name;

        this.modifiers = modifiers;

        this.executable = executable;

        this.index = index;

    }

    public String getName() {

        // Note: empty strings as paramete names are now outlawed.

        // The .equals("") is for compatibility with current JVM

        // behavior.  It may be removed at some point.

        if(name == null || name.equals(""))

            return "arg" + index;

        else

            return name;

    }

 

    // Package-private accessor to the real name field.

    String getRealName() {

        return name;

    }

    public Type getParameterizedType() {

        Type tmp = parameterTypeCache;

        if (null == tmp) {

            tmp = executable.getAllGenericParameterTypes()[index];

            parameterTypeCache = tmp;

        }

 

        return tmp;

    }

 

    private transient volatile Type parameterTypeCache = null;

    public Class<?> getType() {

        Class<?> tmp = parameterClassCache;

        if (null == tmp) {

            tmp = executable.getParameterTypes()[index];

            parameterClassCache = tmp;

        }

        return tmp;

    }

 

}

 

2.6.10 java.lang.reflect.Proxy

java.lang.reflect. Proxy

 

public class Proxy implements java.io.Serializable {

 

    private static final long serialVersionUID = -2222568056686623797L;

    private static final Class<?>[] constructorParams =

        { InvocationHandler.class };

    private static final WeakCache<ClassLoader, Class<?>[], Class<?>>

        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    protected InvocationHandler h;

    private Proxy() {

    }

 

  protected Proxy(InvocationHandler h) {

        Objects.requireNonNull(h);

        this.h = h;

    }

}

 

 

java.lang.reflect. Proxy生成实例对象newProxyInstance方法

 

 

 

  @CallerSensitive

    public static Object newProxyInstance(ClassLoader loader,

                                          Class<?>[] interfaces,

                                          InvocationHandler h)

        throws IllegalArgumentException

    {

        Objects.requireNonNull(h);

 

        final Class<?>[] intfs = interfaces.clone();

        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {

            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);

        }

 

        /*

         * Look up or generate the designated proxy class.

         */

        Class<?> cl = getProxyClass0(loader, intfs);

 

        /*

         * Invoke its constructor with the designated invocation handler.

         */

        try {

            if (sm != null) {

                checkNewProxyPermission(Reflection.getCallerClass(), cl);

            }

 

            final Constructor<?> cons = cl.getConstructor(constructorParams);

            final InvocationHandler ih = h;

            if (!Modifier.isPublic(cl.getModifiers())) {

                AccessController.doPrivileged(new PrivilegedAction<Void>() {

                    public Void run() {

                        cons.setAccessible(true);

                        return null;

                    }

                });

            }

            return cons.newInstance(new Object[]{h});

        } catch (IllegalAccessException|InstantiationException e) {

            throw new InternalError(e.toString(), e);

        } catch (InvocationTargetException e) {

            Throwable t = e.getCause();

            if (t instanceof RuntimeException) {

                throw (RuntimeException) t;

            } else {

                throw new InternalError(t.toString(), t);

            }

        } catch (NoSuchMethodException e) {

            throw new InternalError(e.toString(), e);

        }

    }

 

    private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {

        SecurityManager sm = System.getSecurityManager();

        if (sm != null) {

            if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {

                ClassLoader ccl = caller.getClassLoader();

                ClassLoader pcl = proxyClass.getClassLoader();

 

                // do permission check if the caller is in a different runtime package

                // of the proxy class

                int n = proxyClass.getName().lastIndexOf('.');

                String pkg = (n == -1) ? "" : proxyClass.getName().substring(0, n);

 

                n = caller.getName().lastIndexOf('.');

                String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n);

 

                if (pcl != ccl || !pkg.equals(callerPkg)) {

                    sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));

                }

            }

        }

    }

 

2.6.11 java.lang.reflect.WeakCache

java.lang.reflect. WeakCache

 

final class WeakCache<K, P, V> {

 

    private final ReferenceQueue<K> refQueue

        = new ReferenceQueue<>();

    // the key type is Object for supporting null key

    private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map

        = new ConcurrentHashMap<>();

    private final ConcurrentMap<Supplier<V>, Boolean> reverseMap

        = new ConcurrentHashMap<>();

    private final BiFunction<K, P, ?> subKeyFactory;

    private final BiFunction<K, P, V> valueFactory;

    public WeakCache(BiFunction<K, P, ?> subKeyFactory,

                     BiFunction<K, P, V> valueFactory) {

        this.subKeyFactory = Objects.requireNonNull(subKeyFactory);

        this.valueFactory = Objects.requireNonNull(valueFactory);

    }

    public V get(K key, P parameter) {

        Objects.requireNonNull(parameter);

 

        expungeStaleEntries();

 

        Object cacheKey = CacheKey.valueOf(key, refQueue);

 

        // lazily install the 2nd level valuesMap for the particular cacheKey

        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);

        if (valuesMap == null) {

            ConcurrentMap<Object, Supplier<V>> oldValuesMap

                = map.putIfAbsent(cacheKey,

                                  valuesMap = new ConcurrentHashMap<>());

            if (oldValuesMap != null) {

                valuesMap = oldValuesMap;

            }

        }

 

        // create subKey and retrieve the possible Supplier<V> stored by that

        // subKey from valuesMap

        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));

        Supplier<V> supplier = valuesMap.get(subKey);

        Factory factory = null;

 

        while (true) {

            if (supplier != null) {

                // supplier might be a Factory or a CacheValue<V> instance

                V value = supplier.get();

                if (value != null) {

                    return value;

                }

            }

            // else no supplier in cache

            // or a supplier that returned null (could be a cleared CacheValue

            // or a Factory that wasn't successful in installing the CacheValue)

 

            // lazily construct a Factory

            if (factory == null) {

                factory = new Factory(key, parameter, subKey, valuesMap);

            }

 

            if (supplier == null) {

                supplier = valuesMap.putIfAbsent(subKey, factory);

                if (supplier == null) {

                    // successfully installed Factory

                    supplier = factory;

                }

                // else retry with winning supplier

            } else {

                if (valuesMap.replace(subKey, supplier, factory)) {

                    // successfully replaced

                    // cleared CacheEntry / unsuccessful Factory

                    // with our Factory

                    supplier = factory;

                } else {

                    // retry with current supplier

                    supplier = valuesMap.get(subKey);

                }

            }

        }

    }

    public boolean containsValue(V value) {

        Objects.requireNonNull(value);

 

        expungeStaleEntries();

        return reverseMap.containsKey(new LookupValue<>(value));

    }

    public int size() {

        expungeStaleEntries();

        return reverseMap.size();

    }

 

    private void expungeStaleEntries() {

        CacheKey<K> cacheKey;

        while ((cacheKey = (CacheKey<K>)refQueue.poll()) != null) {

            cacheKey.expungeFrom(map, reverseMap);

        }

    }

    private final class Factory implements Supplier<V> {

 

        private final K key;

        private final P parameter;

        private final Object subKey;

        private final ConcurrentMap<Object, Supplier<V>> valuesMap;

 

        Factory(K key, P parameter, Object subKey,

                ConcurrentMap<Object, Supplier<V>> valuesMap) {

            this.key = key;

            this.parameter = parameter;

            this.subKey = subKey;

            this.valuesMap = valuesMap;

        }

 

        @Override

        public synchronized V get() { // serialize access

            // re-check

            Supplier<V> supplier = valuesMap.get(subKey);

            if (supplier != this) {

                return null;

            }

            // else still us (supplier == this)

 

            // create new value

            V value = null;

            try {

                value = Objects.requireNonNull(valueFactory.apply(key, parameter));

            } finally {

                if (value == null) { // remove us on failure

                    valuesMap.remove(subKey, this);

                }

            }

            // the only path to reach here is with non-null value

            assert value != null;

 

            // wrap value with CacheValue (WeakReference)

            CacheValue<V> cacheValue = new CacheValue<>(value);

 

            // put into reverseMap

            reverseMap.put(cacheValue, Boolean.TRUE);

 

            // try replacing us with CacheValue (this should always succeed)

            if (!valuesMap.replace(subKey, this, cacheValue)) {

                throw new AssertionError("Should not reach here");

            }

 

            // successfully replaced us with new CacheValue -> return the value

            // wrapped by it

            return value;

        }

    }

    private interface Value<V> extends Supplier<V> {}

    private static final class LookupValue<V> implements Value<V> {

        private final V value;

 

        LookupValue(V value) {

            this.value = value;

        }

 

        @Override

        public V get() {

            return value;

        }

 

        @Override

        public int hashCode() {

            return System.identityHashCode(value); // compare by identity

        }

 

        @Override

        public boolean equals(Object obj) {

            return obj == this ||

                   obj instanceof Value &&

                   this.value == ((Value<?>) obj).get();  // compare by identity

        }

    }

    private static final class CacheValue<V>

        extends WeakReference<V> implements Value<V>

    {

        private final int hash;

 

        CacheValue(V value) {

            super(value);

            this.hash = System.identityHashCode(value); // compare by identity

        }

 

        @Override

        public int hashCode() {

            return hash;

        }

 

        @Override

        public boolean equals(Object obj) {

            V value;

            return obj == this ||

                   obj instanceof Value &&

                   // cleared CacheValue is only equal to itself

                   (value = get()) != null &&

                   value == ((Value<?>) obj).get(); // compare by identity

        }

    }

    private static final class CacheKey<K> extends WeakReference<K> {

 

        // a replacement for null keys

        private static final Object NULL_KEY = new Object();

 

        static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {

            return key == null

                   // null key means we can't weakly reference it,

                   // so we use a NULL_KEY singleton as cache key

                   ? NULL_KEY

                   // non-null key requires wrapping with a WeakReference

                   : new CacheKey<>(key, refQueue);

        }

 

        private final int hash;

 

        private CacheKey(K key, ReferenceQueue<K> refQueue) {

            super(key, refQueue);

            this.hash = System.identityHashCode(key);  // compare by identity

        }

 

        @Override

        public int hashCode() {

            return hash;

        }

 

        @Override

        public boolean equals(Object obj) {

            K key;

            return obj == this ||

                   obj != null &&

                   obj.getClass() == this.getClass() &&

                   // cleared CacheKey is only equal to itself

                   (key = this.get()) != null &&

                   // compare key by identity

                   key == ((CacheKey<K>) obj).get();

        }

 

        void expungeFrom(ConcurrentMap<?, ? extends ConcurrentMap<?, ?>> map,

                         ConcurrentMap<?, Boolean> reverseMap) {

            ConcurrentMap<?, ?> valuesMap = map.remove(this);

            // remove also from reverseMap if needed

            if (valuesMap != null) {

                for (Object cacheValue : valuesMap.values()) {

                    reverseMap.remove(cacheValue);

                }

            }

        }

    }

}

 

2.7 java.lang.Comparable

 

java.lang. ComparablecompareTo

public interface Comparable<T> {

    public int compareTo(T o);

}

 

2.8 java.lang. CharSequence

java.lang. CharSequence

public interface CharSequence {

    int length();

    char charAt(int index);

    CharSequence subSequence(int start, int end);

}

 

 

2.9 java.lang.String

 

java.lang.String的主要方法

public final class String

    implements java.io.Serializable, Comparable<String>, CharSequence {

    private final char value[];

    private int hash; // Default to 0

    private static final long serialVersionUID = -6849794470754667710L;

    private static final ObjectStreamField[] serialPersistentFields =

        new ObjectStreamField[0];

    public String() {

        this.value = "".value;

}

   public String(String original) {

        this.value = original.value;

        this.hash = original.hash;

    }

  public String(char value[]) {

        this.value = Arrays.copyOf(value, value.length);

    }

 

  public String(char value[], int offset, int count) {

        if (offset < 0) {

            throw new StringIndexOutOfBoundsException(offset);

        }

        if (count <= 0) {

            if (count < 0) {

                throw new StringIndexOutOfBoundsException(count);

            }

            if (offset <= value.length) {

                this.value = "".value;

                return;

            }

        }

        // Note: offset or count might be near -1>>>1.

        if (offset > value.length - count) {

            throw new StringIndexOutOfBoundsException(offset + count);

        }

        this.value = Arrays.copyOfRange(value, offset, offset+count);

       }

public boolean isEmpty() {

        return value.length == 0;

    }

       public int hashCode() {

        int h = hash;

        if (h == 0 && value.length > 0) {

            char val[] = value;

            for (int i = 0; i < value.length; i++) {

                h = 31 * h + val[i];

            }

            hash = h;

        }

        return h;

}

public boolean equals(Object anObject) {

        if (this == anObject) {

            return true;

        }

        if (anObject instanceof String) {

            String anotherString = (String)anObject;

            int n = value.length;

            if (n == anotherString.value.length) {

                char v1[] = value;

                char v2[] = anotherString.value;

                int i = 0;

                while (n-- != 0) {

                    if (v1[i] != v2[i])

                        return false;

                    i++;

                }

                return true;

            }

        }

        return false;

    }

 

2.10 Java.lang. Appendable

Java.lang. Appendable

 

public interface Appendable {

    Appendable append(CharSequence csq) throws IOException;

    Appendable append(CharSequence csq, int start, int end) throws IOException;

    Appendable append(char c) throws IOException;

}

 

2.11 java.lang. AbstractStringBuilder

java.lang. AbstractStringBuilder的主要方法

abstract class AbstractStringBuilder implements Appendable, CharSequence {

    char[] value;

    int count;

    AbstractStringBuilder() {

    }

    AbstractStringBuilder(int capacity) {

        value = new char[capacity];

    }

    @Override

    public int length() {

        return count;

    }

    public int capacity() {

        return value.length;

    }

  @Override

    public AbstractStringBuilder append(char c) {

        ensureCapacityInternal(count + 1);

        value[count++] = c;

        return this;

    }

  private int newCapacity(int minCapacity) {

        // overflow-conscious code

        int newCapacity = (value.length << 1) + 2;

        if (newCapacity - minCapacity < 0) {

            newCapacity = minCapacity;

        }

        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)

            ? hugeCapacity(minCapacity)

            : newCapacity;

}

 

2.12 java.lang.StringBuilder

java.lang. StringBuilder的主要方法

 

public final class StringBuilder

    extends AbstractStringBuilder

    implements java.io.Serializable, CharSequence

{

    static final long serialVersionUID = 4383685877147921099L;

    public StringBuilder() {

        super(16);

    }

    public StringBuilder(int capacity) {

        super(capacity);

    }

 

    public StringBuilder(String str) {

        super(str.length() + 16);

        append(str);

    }

    public StringBuilder(CharSequence seq) {

        this(seq.length() + 16);

        append(seq);

    }

 

    @Override

    public StringBuilder append(Object obj) {

        return append(String.valueOf(obj));

    }

 

    @Override

    public StringBuilder append(String str) {

        super.append(str);

        return this;

    }

}

 

2.13 java.lang.StringBuffer

java.lang. StringBuffer的主要方法

 

public final class StringBuffer

    extends AbstractStringBuilder

    implements java.io.Serializable, CharSequence

{

    private transient char[] toStringCache;

    static final long serialVersionUID = 3388685877147921107L;

    public StringBuffer() {

        super(16);

    }

    public StringBuffer(int capacity) {

        super(capacity);

    }

    public StringBuffer(String str) {

        super(str.length() + 16);

        append(str);

    }

    public StringBuffer(CharSequence seq) {

        this(seq.length() + 16);

        append(seq);

    }

 

    @Override

    public synchronized int length() {

        return count;

    }

    @Override

    public synchronized int capacity() {

        return value.length;

    }

    @Override

    public synchronized void ensureCapacity(int minimumCapacity) {

        super.ensureCapacity(minimumCapacity);

    }

    @Override

    public synchronized void trimToSize() {

        super.trimToSize();

    }

    @Override

    public synchronized void setLength(int newLength) {

        toStringCache = null;

        super.setLength(newLength);

    }

    @Override

    public synchronized char charAt(int index) {

        if ((index < 0) || (index >= count))

            throw new StringIndexOutOfBoundsException(index);

        return value[index];

    }

    @Override

    public synchronized int codePointAt(int index) {

        return super.codePointAt(index);

    }

    @Override

    public synchronized int codePointBefore(int index) {

        return super.codePointBefore(index);

    }

    @Override

    public synchronized int codePointCount(int beginIndex, int endIndex) {

        return super.codePointCount(beginIndex, endIndex);

    }

    @Override

    public synchronized int offsetByCodePoints(int index, int codePointOffset) {

        return super.offsetByCodePoints(index, codePointOffset);

    }

    @Override

    public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,

                                      int dstBegin)

    {

        super.getChars(srcBegin, srcEnd, dst, dstBegin);

    }

    @Override

    public synchronized void setCharAt(int index, char ch) {

        if ((index < 0) || (index >= count))

            throw new StringIndexOutOfBoundsException(index);

        toStringCache = null;

        value[index] = ch;

    }

    @Override

    public synchronized StringBuffer append(Object obj) {

        toStringCache = null;

        super.append(String.valueOf(obj));

        return this;

    }

    @Override

    public synchronized StringBuffer append(String str) {

        toStringCache = null;

        super.append(str);

        return this;

    }

    public synchronized StringBuffer append(StringBuffer sb) {

        toStringCache = null;

        super.append(sb);

        return this;

    }

    @Override

    synchronized StringBuffer append(AbstractStringBuilder asb) {

        toStringCache = null;

        super.append(asb);

        return this;

    }

    @Override

    public synchronized StringBuffer append(CharSequence s) {

        toStringCache = null;

        super.append(s);

        return this;

    }

    @Override

    public synchronized StringBuffer append(CharSequence s, int start, int end)

    {

        toStringCache = null;

        super.append(s, start, end);

        return this;

    }

 

    @Override

    public synchronized StringBuffer append(char[] str) {

        toStringCache = null;

        super.append(str);

        return this;

    }

 

 

3.    java.io

3.1 java.io. DataInput

 

java.io. DataInput

 

 

public interface DataInput {

    void readFully(byte b[]) throws IOException;

    void readFully(byte b[], int off, int len) throws IOException;

    int skipBytes(int n) throws IOException;

    boolean readBoolean() throws IOException;

    byte readByte() throws IOException;

    int readUnsignedByte() throws IOException;

    short readShort() throws IOException;

    int readUnsignedShort() throws IOException;

    char readChar() throws IOException;

    int readInt() throws IOException;

    long readLong() throws IOException;

    float readFloat() throws IOException;

    double readDouble() throws IOException;

    String readLine() throws IOException;

    String readUTF() throws IOException;

}

 

3.2 java.io. ObjectInput

 

java.io. ObjectInput

 

 

public interface ObjectInput extends DataInput, AutoCloseable {

    public Object readObject()

        throws ClassNotFoundException, IOException;

    public int read() throws IOException;

    public int read(byte b[]) throws IOException;

    public int read(byte b[], int off, int len) throws IOException;

    public long skip(long n) throws IOException;

    public int available() throws IOException;

    public void close() throws IOException;

}

 

 

3.3 java.io. DataOutput

 

java.io. DataOutput

 

 

public interface DataOutput {

    void write(int b) throws IOException;

    void write(byte b[]) throws IOException;

    void write(byte b[], int off, int len) throws IOException;

    void writeBoolean(boolean v) throws IOException;

    void writeByte(int v) throws IOException;

    void writeShort(int v) throws IOException;

    void writeChar(int v) throws IOException;

    void writeInt(int v) throws IOException;

    void writeLong(long v) throws IOException;

    void writeFloat(float v) throws IOException;

    void writeDouble(double v) throws IOException;

    void writeBytes(String s) throws IOException;

    void writeChars(String s) throws IOException;

    void writeUTF(String s) throws IOException;

}

 

 

3.4 java.io. ObjectOutput

 

java.io. ObjectOutput

 

 

public interface ObjectOutput extends DataOutput, AutoCloseable {

    public void writeObject(Object obj)

      throws IOException;

    public void write(int b) throws IOException;

    public void write(byte b[]) throws IOException;

    public void write(byte b[], int off, int len) throws IOException;

    public void flush() throws IOException;

    public void close() throws IOException;

}

 

3.5 java.lang. AutoCloseable

 

java.lang. AutoCloseable

 

 

public interface AutoCloseable {

    void close() throws Exception;

}

 

3.6 java.io. FilterInputStream

 

java.io. FilterInputStream

 

 

public class FilterInputStream extends InputStream {

    protected volatile InputStream in;

    protected FilterInputStream(InputStream in) {

        this.in = in;

    }

    public int read() throws IOException {

        return in.read();

    }

    public int read(byte b[]) throws IOException {

        return read(b, 0, b.length);

    }

    public int read(byte b[], int off, int len) throws IOException {

        return in.read(b, off, len);

    }

    public long skip(long n) throws IOException {

        return in.skip(n);

    }

    public int available() throws IOException {

        return in.available();

    }

    public void close() throws IOException {

        in.close();

    }

    public synchronized void mark(int readlimit) {

        in.mark(readlimit);

    }

    public synchronized void reset() throws IOException {

        in.reset();

    }

    public boolean markSupported() {

        return in.markSupported();

    }

}

 

 

3.7 java.io. DataInputStream

 

java.io. DataInputStream

 

 

public class DataInputStream extends FilterInputStream implements DataInput {

    public DataInputStream(InputStream in) {

        super(in);

    }

    private byte bytearr[] = new byte[80];

    private char chararr[] = new char[80];

    public final int read(byte b[]) throws IOException {

        return in.read(b, 0, b.length);

    }

    public final int read(byte b[], int off, int len) throws IOException {

        return in.read(b, off, len);

    }

    public final void readFully(byte b[]) throws IOException {

        readFully(b, 0, b.length);

    }

    public final void readFully(byte b[], int off, int len) throws IOException {

        if (len < 0)

            throw new IndexOutOfBoundsException();

        int n = 0;

        while (n < len) {

            int count = in.read(b, off + n, len - n);

            if (count < 0)

                throw new EOFException();

            n += count;

        }

    }

    public final int skipBytes(int n) throws IOException {

        int total = 0;

        int cur = 0;

 

        while ((total<n) && ((cur = (int) in.skip(n-total)) > 0)) {

            total += cur;

        }

 

        return total;

    }

    public final boolean readBoolean() throws IOException {

        int ch = in.read();

        if (ch < 0)

            throw new EOFException();

        return (ch != 0);

    }

    public final byte readByte() throws IOException {

        int ch = in.read();

        if (ch < 0)

            throw new EOFException();

        return (byte)(ch);

    }

    public final int readUnsignedByte() throws IOException {

        int ch = in.read();

        if (ch < 0)

            throw new EOFException();

        return ch;

    }

    public final short readShort() throws IOException {

        int ch1 = in.read();

        int ch2 = in.read();

        if ((ch1 | ch2) < 0)

            throw new EOFException();

        return (short)((ch1 << 8) + (ch2 << 0));

    }

    public final int readUnsignedShort() throws IOException {

        int ch1 = in.read();

        int ch2 = in.read();

        if ((ch1 | ch2) < 0)

            throw new EOFException();

        return (ch1 << 8) + (ch2 << 0);

    }

    public final char readChar() throws IOException {

        int ch1 = in.read();

        int ch2 = in.read();

        if ((ch1 | ch2) < 0)

            throw new EOFException();

        return (char)((ch1 << 8) + (ch2 << 0));

    }

    public final int readInt() throws IOException {

        int ch1 = in.read();

        int ch2 = in.read();

        int ch3 = in.read();

        int ch4 = in.read();

        if ((ch1 | ch2 | ch3 | ch4) < 0)

            throw new EOFException();

        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));

    }

 

    private byte readBuffer[] = new byte[8];

    public final long readLong() throws IOException {

        readFully(readBuffer, 0, 8);

        return (((long)readBuffer[0] << 56) +

                ((long)(readBuffer[1] & 255) << 48) +

                ((long)(readBuffer[2] & 255) << 40) +

                ((long)(readBuffer[3] & 255) << 32) +

                ((long)(readBuffer[4] & 255) << 24) +

                ((readBuffer[5] & 255) << 16) +

                ((readBuffer[6] & 255) <<  8) +

                ((readBuffer[7] & 255) <<  0));

    }

    public final float readFloat() throws IOException {

        return Float.intBitsToFloat(readInt());

    }

    public final double readDouble() throws IOException {

        return Double.longBitsToDouble(readLong());

    }

 

    private char lineBuffer[];

    @Deprecated

    public final String readLine() throws IOException {

        char buf[] = lineBuffer;

 

        if (buf == null) {

            buf = lineBuffer = new char[128];

        }

 

        int room = buf.length;

        int offset = 0;

        int c;

 

loop:   while (true) {

            switch (c = in.read()) {

              case -1:

              case '\n':

                break loop;

 

              case '\r':

                int c2 = in.read();

                if ((c2 != '\n') && (c2 != -1)) {

                    if (!(in instanceof PushbackInputStream)) {

                        this.in = new PushbackInputStream(in);

                    }

                    ((PushbackInputStream)in).unread(c2);

                }

                break loop;

 

              default:

                if (--room < 0) {

                    buf = new char[offset + 128];

                    room = buf.length - offset - 1;

                    System.arraycopy(lineBuffer, 0, buf, 0, offset);

                    lineBuffer = buf;

                }

                buf[offset++] = (char) c;

                break;

            }

        }

        if ((c == -1) && (offset == 0)) {

            return null;

        }

        return String.copyValueOf(buf, 0, offset);

    }

    public final String readUTF() throws IOException {

        return readUTF(this);

    }

    public final static String readUTF(DataInput in) throws IOException {

        int utflen = in.readUnsignedShort();

        byte[] bytearr = null;

        char[] chararr = null;

        if (in instanceof DataInputStream) {

            DataInputStream dis = (DataInputStream)in;

            if (dis.bytearr.length < utflen){

                dis.bytearr = new byte[utflen*2];

                dis.chararr = new char[utflen*2];

            }

            chararr = dis.chararr;

            bytearr = dis.bytearr;

        } else {

            bytearr = new byte[utflen];

            chararr = new char[utflen];

        }

 

        int c, char2, char3;

        int count = 0;

        int chararr_count=0;

 

        in.readFully(bytearr, 0, utflen);

 

        while (count < utflen) {

            c = (int) bytearr[count] & 0xff;

            if (c > 127) break;

            count++;

            chararr[chararr_count++]=(char)c;

        }

 

        while (count < utflen) {

            c = (int) bytearr[count] & 0xff;

            switch (c >> 4) {

                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:

                    /* 0xxxxxxx*/

                    count++;

                    chararr[chararr_count++]=(char)c;

                    break;

                case 12: case 13:

                    /* 110x xxxx   10xx xxxx*/

                    count += 2;

                    if (count > utflen)

                        throw new UTFDataFormatException(

                            "malformed input: partial character at end");

                    char2 = (int) bytearr[count-1];

                    if ((char2 & 0xC0) != 0x80)

                        throw new UTFDataFormatException(

                            "malformed input around byte " + count);

                    chararr[chararr_count++]=(char)(((c & 0x1F) << 6) |

                                                    (char2 & 0x3F));

                    break;

                case 14:

                    /* 1110 xxxx  10xx xxxx  10xx xxxx */

                    count += 3;

                    if (count > utflen)

                        throw new UTFDataFormatException(

                            "malformed input: partial character at end");

                    char2 = (int) bytearr[count-2];

                    char3 = (int) bytearr[count-1];

                    if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))

                        throw new UTFDataFormatException(

                            "malformed input around byte " + (count-1));

                    chararr[chararr_count++]=(char)(((c     & 0x0F) << 12) |

                                                    ((char2 & 0x3F) << 6)  |

                                                    ((char3 & 0x3F) << 0));

                    break;

                default:

                    /* 10xx xxxx,  1111 xxxx */

                    throw new UTFDataFormatException(

                        "malformed input around byte " + count);

            }

        }

        // The number of chars produced may be less than utflen

        return new String(chararr, 0, chararr_count);

    }

}

 

3.8 java.io. SocketInputStream

 

java.io. SocketInputStream

class SocketInputStream extends FileInputStream

{

    static {

        init();

    }

    private boolean eof;

    private AbstractPlainSocketImpl impl = null;

    private byte temp[];

private Socket socket = null;   

    private native int socketRead0(FileDescriptor fd,

                                   byte b[], int off, int len,

                                   int timeout)

        throws IOException;

    private int socketRead(FileDescriptor fd,

                           byte b[], int off, int len,

                           int timeout)

        throws IOException {

        return socketRead0(fd, b, off, len, timeout);

    }

    public int read(byte b[]) throws IOException {

        return read(b, 0, b.length);

    }

    public int read(byte b[], int off, int length) throws IOException {

        return read(b, off, length, impl.getTimeout());

    }

 

    int read(byte b[], int off, int length, int timeout) throws IOException {

        int n;

 

        // EOF already encountered

        if (eof) {

            return -1;

        }

        if (impl.isConnectionReset()) {

            throw new SocketException("Connection reset");

        }

        if (length <= 0 || off < 0 || length > b.length - off) {

            if (length == 0) {

                return 0;

            }

            throw new ArrayIndexOutOfBoundsException("length == " + length

                    + " off == " + off + " buffer length == " + b.length);

        }

 

        boolean gotReset = false;

        FileDescriptor fd = impl.acquireFD();

        try {

            n = socketRead(fd, b, off, length, timeout);

            if (n > 0) {

                return n;

            }

        } catch (ConnectionResetException rstExc) {

            gotReset = true;

        } finally {

            impl.releaseFD();

        }

 

 

 

3.9 java.io. ObjectOutputStream

 

java.io. ObjectOutputStream

 

public class ObjectOutputStream

    extends OutputStream implements ObjectOutput, ObjectStreamConstants

{

 

    private static class Caches {

        /** cache of subclass security audit results */

        static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =

            new ConcurrentHashMap<>();

 

        /** queue for WeakReferences to audited subclasses */

        static final ReferenceQueue<Class<?>> subclassAuditsQueue =

            new ReferenceQueue<>();

    }

 

    /** filter stream for handling block data conversion */

    private final BlockDataOutputStream bout;

    /** obj -> wire handle map */

    private final HandleTable handles;

    /** obj -> replacement obj map */

    private final ReplaceTable subs;

    /** stream protocol version */

    private int protocol = PROTOCOL_VERSION_2;

    /** recursion depth */

    private int depth;

 

    /** buffer for writing primitive field values */

    private byte[] primVals;

 

    /** if true, invoke writeObjectOverride() instead of writeObject() */

    private final boolean enableOverride;

    /** if true, invoke replaceObject() */

    private boolean enableReplace;

    private SerialCallbackContext curContext;

    /** current PutField object */

    private PutFieldImpl curPut;

    private final DebugTraceInfoStack debugInfoStack;

    private static final boolean extendedDebugInfo =

        java.security.AccessController.doPrivileged(

            new sun.security.action.GetBooleanAction(

                "sun.io.serialization.extendedDebugInfo")).booleanValue();

    public ObjectOutputStream(OutputStream out) throws IOException {

        verifySubclass();

        bout = new BlockDataOutputStream(out);

        handles = new HandleTable(10, (float) 3.00);

        subs = new ReplaceTable(10, (float) 3.00);

        enableOverride = false;

        writeStreamHeader();

        bout.setBlockDataMode(true);

        if (extendedDebugInfo) {

            debugInfoStack = new DebugTraceInfoStack();

        } else {

            debugInfoStack = null;

        }

}

 

3.9.1 java.io. ObjectOutputStream. BlockDataOutputStream

java.io. ObjectOutputStream. BlockDataOutputStream

 

 

   private static class BlockDataOutputStream

        extends OutputStream implements DataOutput

    {

        /** maximum data block length */

        private static final int MAX_BLOCK_SIZE = 1024;

        /** maximum data block header length */

        private static final int MAX_HEADER_SIZE = 5;

        /** (tunable) length of char buffer (for writing strings) */

        private static final int CHAR_BUF_SIZE = 256;

 

        /** buffer for writing general/block data */

        private final byte[] buf = new byte[MAX_BLOCK_SIZE];

        /** buffer for writing block data headers */

        private final byte[] hbuf = new byte[MAX_HEADER_SIZE];

        /** char buffer for fast string writes */

        private final char[] cbuf = new char[CHAR_BUF_SIZE];

 

        /** block data mode */

        private boolean blkmode = false;

        /** current offset into buf */

        private int pos = 0;

 

        /** underlying output stream */

        private final OutputStream out;

        /** loopback stream (for data writes that span data blocks) */

        private final DataOutputStream dout;

        BlockDataOutputStream(OutputStream out) {

            this.out = out;

            dout = new DataOutputStream(this);

        }

        boolean setBlockDataMode(boolean mode) throws IOException {

            if (blkmode == mode) {

                return blkmode;

            }

            drain();

            blkmode = mode;

            return !blkmode;

        }

        boolean getBlockDataMode() {

            return blkmode;

        }

 

        public void write(int b) throws IOException {

            if (pos >= MAX_BLOCK_SIZE) {

                drain();

            }

            buf[pos++] = (byte) b;

        }

 

        public void write(byte[] b) throws IOException {

            write(b, 0, b.length, false);

        }

 

        public void write(byte[] b, int off, int len) throws IOException {

            write(b, off, len, false);

        }

 

        public void flush() throws IOException {

            drain();

            out.flush();

        }

 

        public void close() throws IOException {

            flush();

            out.close();

        }

        void write(byte[] b, int off, int len, boolean copy)

            throws IOException

        {

            if (!(copy || blkmode)) {           // write directly

                drain();

                out.write(b, off, len);

                return;

            }

 

            while (len > 0) {

                if (pos >= MAX_BLOCK_SIZE) {

                    drain();

                }

                if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) {

                    // avoid unnecessary copy

                    writeBlockHeader(MAX_BLOCK_SIZE);

                    out.write(b, off, MAX_BLOCK_SIZE);

                    off += MAX_BLOCK_SIZE;

                    len -= MAX_BLOCK_SIZE;

                } else {

                    int wlen = Math.min(len, MAX_BLOCK_SIZE - pos);

                    System.arraycopy(b, off, buf, pos, wlen);

                    pos += wlen;

                    off += wlen;

                    len -= wlen;

                }

            }

        }

        void drain() throws IOException {

            if (pos == 0) {

                return;

            }

            if (blkmode) {

                writeBlockHeader(pos);

            }

            out.write(buf, 0, pos);

            pos = 0;

        }

        private void writeBlockHeader(int len) throws IOException {

            if (len <= 0xFF) {

                hbuf[0] = TC_BLOCKDATA;

                hbuf[1] = (byte) len;

                out.write(hbuf, 0, 2);

            } else {

                hbuf[0] = TC_BLOCKDATALONG;

                Bits.putInt(hbuf, 1, len);

                out.write(hbuf, 0, 5);

            }

        }

 

        public void writeBoolean(boolean v) throws IOException {

            if (pos >= MAX_BLOCK_SIZE) {

                drain();

            }

            Bits.putBoolean(buf, pos++, v);

        }

 

        public void writeByte(int v) throws IOException {

            if (pos >= MAX_BLOCK_SIZE) {

                drain();

            }

            buf[pos++] = (byte) v;

        }

 

        public void writeChar(int v) throws IOException {

            if (pos + 2 <= MAX_BLOCK_SIZE) {

                Bits.putChar(buf, pos, (char) v);

                pos += 2;

            } else {

                dout.writeChar(v);

            }

        }

 

        public void writeShort(int v) throws IOException {

            if (pos + 2 <= MAX_BLOCK_SIZE) {

                Bits.putShort(buf, pos, (short) v);

                pos += 2;

            } else {

                dout.writeShort(v);

            }

        }

 

        public void writeInt(int v) throws IOException {

            if (pos + 4 <= MAX_BLOCK_SIZE) {

                Bits.putInt(buf, pos, v);

                pos += 4;

            } else {

                dout.writeInt(v);

            }

        }

 

        public void writeFloat(float v) throws IOException {

            if (pos + 4 <= MAX_BLOCK_SIZE) {

                Bits.putFloat(buf, pos, v);

                pos += 4;

            } else {

                dout.writeFloat(v);

            }

        }

 

        public void writeLong(long v) throws IOException {

            if (pos + 8 <= MAX_BLOCK_SIZE) {

                Bits.putLong(buf, pos, v);

                pos += 8;

            } else {

                dout.writeLong(v);

            }

        }

 

        public void writeDouble(double v) throws IOException {

            if (pos + 8 <= MAX_BLOCK_SIZE) {

                Bits.putDouble(buf, pos, v);

                pos += 8;

            } else {

                dout.writeDouble(v);

            }

        }

 

        public void writeBytes(String s) throws IOException {

            int endoff = s.length();

            int cpos = 0;

            int csize = 0;

            for (int off = 0; off < endoff; ) {

                if (cpos >= csize) {

                    cpos = 0;

                    csize = Math.min(endoff - off, CHAR_BUF_SIZE);

                    s.getChars(off, off + csize, cbuf, 0);

                }

                if (pos >= MAX_BLOCK_SIZE) {

                    drain();

                }

                int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos);

                int stop = pos + n;

                while (pos < stop) {

                    buf[pos++] = (byte) cbuf[cpos++];

                }

                off += n;

            }

        }

 

        public void writeChars(String s) throws IOException {

            int endoff = s.length();

            for (int off = 0; off < endoff; ) {

                int csize = Math.min(endoff - off, CHAR_BUF_SIZE);

                s.getChars(off, off + csize, cbuf, 0);

                writeChars(cbuf, 0, csize);

                off += csize;

            }

        }

 

        public void writeUTF(String s) throws IOException {

            writeUTF(s, getUTFLength(s));

        }

 

        void writeBooleans(boolean[] v, int off, int len) throws IOException {

            int endoff = off + len;

            while (off < endoff) {

                if (pos >= MAX_BLOCK_SIZE) {

                    drain();

                }

                int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos));

                while (off < stop) {

                    Bits.putBoolean(buf, pos++, v[off++]);

                }

            }

        }

 

        void writeChars(char[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 2;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;

                    int stop = Math.min(endoff, off + avail);

                    while (off < stop) {

                        Bits.putChar(buf, pos, v[off++]);

                        pos += 2;

                    }

                } else {

                    dout.writeChar(v[off++]);

                }

            }

        }

 

        void writeShorts(short[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 2;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 1;

                    int stop = Math.min(endoff, off + avail);

                    while (off < stop) {

                        Bits.putShort(buf, pos, v[off++]);

                        pos += 2;

                    }

                } else {

                    dout.writeShort(v[off++]);

                }

            }

        }

 

        void writeInts(int[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 4;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;

                    int stop = Math.min(endoff, off + avail);

                    while (off < stop) {

                        Bits.putInt(buf, pos, v[off++]);

                        pos += 4;

                    }

                } else {

                    dout.writeInt(v[off++]);

                }

            }

        }

 

        void writeFloats(float[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 4;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 2;

                    int chunklen = Math.min(endoff - off, avail);

                    floatsToBytes(v, off, buf, pos, chunklen);

                    off += chunklen;

                    pos += chunklen << 2;

                } else {

                    dout.writeFloat(v[off++]);

                }

            }

        }

 

        void writeLongs(long[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 8;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;

                    int stop = Math.min(endoff, off + avail);

                    while (off < stop) {

                        Bits.putLong(buf, pos, v[off++]);

                        pos += 8;

                    }

                } else {

                    dout.writeLong(v[off++]);

                }

            }

        }

 

        void writeDoubles(double[] v, int off, int len) throws IOException {

            int limit = MAX_BLOCK_SIZE - 8;

            int endoff = off + len;

            while (off < endoff) {

                if (pos <= limit) {

                    int avail = (MAX_BLOCK_SIZE - pos) >> 3;

                    int chunklen = Math.min(endoff - off, avail);

                    doublesToBytes(v, off, buf, pos, chunklen);

                    off += chunklen;

                    pos += chunklen << 3;

                } else {

                    dout.writeDouble(v[off++]);

                }

            }

        }

        long getUTFLength(String s) {

            int len = s.length();

            long utflen = 0;

            for (int off = 0; off < len; ) {

                int csize = Math.min(len - off, CHAR_BUF_SIZE);

                s.getChars(off, off + csize, cbuf, 0);

                for (int cpos = 0; cpos < csize; cpos++) {

                    char c = cbuf[cpos];

                    if (c >= 0x0001 && c <= 0x007F) {

                        utflen++;

                    } else if (c > 0x07FF) {

                        utflen += 3;

                    } else {

                        utflen += 2;

                    }

                }

                off += csize;

            }

            return utflen;

        }

        void writeUTF(String s, long utflen) throws IOException {

            if (utflen > 0xFFFFL) {

                throw new UTFDataFormatException();

            }

            writeShort((int) utflen);

            if (utflen == (long) s.length()) {

                writeBytes(s);

            } else {

                writeUTFBody(s);

            }

        }

        void writeLongUTF(String s) throws IOException {

            writeLongUTF(s, getUTFLength(s));

        }

 

        /**

         * Writes given string in "long" UTF format, where the UTF encoding

         * length of the string is already known.

         */

        void writeLongUTF(String s, long utflen) throws IOException {

            writeLong(utflen);

            if (utflen == (long) s.length()) {

                writeBytes(s);

            } else {

                writeUTFBody(s);

            }

        }

        private void writeUTFBody(String s) throws IOException {

            int limit = MAX_BLOCK_SIZE - 3;

            int len = s.length();

            for (int off = 0; off < len; ) {

                int csize = Math.min(len - off, CHAR_BUF_SIZE);

                s.getChars(off, off + csize, cbuf, 0);

                for (int cpos = 0; cpos < csize; cpos++) {

                    char c = cbuf[cpos];

                    if (pos <= limit) {

                        if (c <= 0x007F && c != 0) {

                            buf[pos++] = (byte) c;

                        } else if (c > 0x07FF) {

                            buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));

                            buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));

                            buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));

                            pos += 3;

                        } else {

                            buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));

                            buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));

                            pos += 2;

                        }

                    } else {    // write one byte at a time to normalize block

                        if (c <= 0x007F && c != 0) {

                            write(c);

                        } else if (c > 0x07FF) {

                            write(0xE0 | ((c >> 12) & 0x0F));

                            write(0x80 | ((c >> 6) & 0x3F));

                            write(0x80 | ((c >> 0) & 0x3F));

                        } else {

                            write(0xC0 | ((c >> 6) & 0x1F));

                            write(0x80 | ((c >> 0) & 0x3F));

                        }

                    }

                }

                off += csize;

            }

        }

   

3.10 java.io. File

 

java.io.File

public class File implements Serializable, Comparable<File>{

    private static final FileSystem fs = DefaultFileSystem.getFileSystem();

    private final String path;

    public File(String pathname) {

        if (pathname == null) {

            throw new NullPointerException();

        }

        this.path = fs.normalize(pathname);

        this.prefixLength = fs.prefixLength(this.path);

    }

}

 

 

3.11 java.io. FileDescriptor

java.io. FileDescriptor

 

public final class FileDescriptor {

 

    private int fd;

 

    private long handle;

 

    private Closeable parent;

    private List<Closeable> otherParents;

    private boolean closed;

 

    /**

     * Constructs an (invalid) FileDescriptor

     * object.

     */

    public /**/ FileDescriptor() {

        fd = -1;

        handle = -1;

    }

 

    static {

        initIDs();

}

    private static native void initIDs();

 

private static native long set(int d);

}

 

 

3.12 java.io. FileSystem

 

java.io. FileSystem

 

abstract class FileSystem {

    public abstract char getSeparator();

    public abstract char getPathSeparator();

    public abstract String normalize(String path);

    public abstract int prefixLength(String path);

    public abstract String resolve(String parent, String child);

    public abstract String getDefaultParent();

    public abstract String fromURIPath(String path);

    public abstract boolean isAbsolute(File f);

    public abstract String resolve(File f);

    public abstract String canonicalize(String path) throws IOException;

    @Native public static final int BA_EXISTS    = 0x01;

    @Native public static final int BA_REGULAR   = 0x02;

    @Native public static final int BA_DIRECTORY = 0x04;

    @Native public static final int BA_HIDDEN    = 0x08;

    public abstract int getBooleanAttributes(File f);

    @Native public static final int ACCESS_READ    = 0x04;

    @Native public static final int ACCESS_WRITE   = 0x02;

    @Native public static final int ACCESS_EXECUTE = 0x01;

    public abstract boolean checkAccess(File f, int access);

    public abstract boolean setPermission(File f, int access, boolean enable, boolean owneronly);

    public abstract long getLastModifiedTime(File f);

    public abstract long getLength(File f);

    public abstract boolean createFileExclusively(String pathname)

        throws IOException;

    public abstract boolean delete(File f);

    public abstract String[] list(File f);

 

}

3.13 java.io. DefaultFileSystem

 

java.io. DefaultFileSystem

class DefaultFileSystem {

    public static FileSystem getFileSystem() {

        return new WinNTFileSystem();

    }

}

 

3.14 java.io.WinNTFileSystem

java.io. WinNTFileSystem

class WinNTFileSystem extends FileSystem {

private final char slash;

    private final char altSlash;

    private final char semicolon;

    public WinNTFileSystem() {

        slash = AccessController.doPrivileged(

            new GetPropertyAction("file.separator")).charAt(0);

        semicolon = AccessController.doPrivileged(

            new GetPropertyAction("path.separator")).charAt(0);

        altSlash = (this.slash == '\\') ? '/' : '\\';

    }

    @Override

    public native boolean setPermission(File f, int access, boolean enable,

            boolean owneronly);

    @Override

    public native boolean createFileExclusively(String path)

            throws IOException;

    @Override

    public native String[] list(File f);

    @Override

    public native boolean createDirectory(File f);

    @Override

    public native boolean setLastModifiedTime(File f, long time);

    @Override

    public native boolean setReadOnly(File f);

    @Override

    public boolean delete(File f) {

        cache.clear();

        prefixCache.clear();

        return delete0(f);

    }

    private native boolean delete0(File f);

    @Override

    public boolean rename(File f1, File f2) {

        cache.clear();

        prefixCache.clear();

        return rename0(f1, f2);

    }

    private native boolean rename0(File f1, File f2);

}

 

 

3.15 java.io. FileOutputStream

java.io. FileOutputStream

 

 

public

class FileOutputStream extends OutputStream

{

    private final FileDescriptor fd;

    private final boolean append;

    private FileChannel channel;

    private final String path;

 

    private final Object closeLock = new Object();

    private volatile boolean closed = false;

    public FileOutputStream(String name) throws FileNotFoundException {

        this(name != null ? new File(name) : null, false);

    }

    public FileOutputStream(String name, boolean append)

        throws FileNotFoundException

    {

        this(name != null ? new File(name) : null, append);

    }

    public FileOutputStream(File file) throws FileNotFoundException {

        this(file, false);

    }

    public FileOutputStream(File file, boolean append)

        throws FileNotFoundException

    {

        String name = (file != null ? file.getPath() : null);

        SecurityManager security = System.getSecurityManager();

        if (security != null) {

            security.checkWrite(name);

        }

        if (name == null) {

            throw new NullPointerException();

        }

        if (file.isInvalid()) {

            throw new FileNotFoundException("Invalid file path");

        }

        this.fd = new FileDescriptor();

        fd.attach(this);

        this.append = append;

        this.path = name;

        open(name, append);

    }

   private void open(String name, boolean append)

        throws FileNotFoundException {

        open0(name, append);

    }

    private native void open0(String name, boolean append)

        throws FileNotFoundException;

}

 

4.    java.net

4.1 java.io.Closeable

 

java.io.Closeable

public interface Closeable extends AutoCloseable {

    public void close() throws IOException;

}

 

 

 

4.2 java.net. SocketOptions

java.net. SocketOptions

 

 

public interface SocketOptions {

    public void   setOption(int optID, Object value) throws SocketException;

    public Object getOption(int optID) throws SocketException;

    @Native public final static int TCP_NODELAY = 0x0001;

    @Native public final static int SO_BINDADDR = 0x000F;

    @Native public final static int SO_REUSEADDR = 0x04;

    @Native public final static int SO_BROADCAST = 0x0020;

    @Native public final static int IP_MULTICAST_IF = 0x10;

    @Native public final static int IP_MULTICAST_IF2 = 0x1f;

    @Native public final static int IP_MULTICAST_LOOP = 0x12;

    @Native public final static int IP_TOS = 0x3;

    @Native public final static int SO_LINGER = 0x0080;

    @Native public final static int SO_TIMEOUT = 0x1006;

    @Native public final static int SO_SNDBUF = 0x1001;

    @Native public final static int SO_RCVBUF = 0x1002;

    @Native public final static int SO_KEEPALIVE = 0x0008;

    @Native public final static int SO_OOBINLINE = 0x1003;

}

 

4.3 java.net. SocketImpl

 

java.net. SocketImpl

public abstract class SocketImpl implements SocketOptions {

    Socket socket = null;

    ServerSocket serverSocket = null;

    protected FileDescriptor fd;

    protected InetAddress address;

    protected int port;

    protected int localport;

    protected abstract void create(boolean stream) throws IOException;

    protected abstract void connect(String host, int port) throws IOException;

    protected abstract void connect(InetAddress address, int port) throws IOException;

    protected abstract void connect(SocketAddress address, int timeout) throws IOException;

    protected abstract void bind(InetAddress host, int port) throws IOException;

    protected abstract void listen(int backlog) throws IOException;

    protected abstract void accept(SocketImpl s) throws IOException;

    protected abstract InputStream getInputStream() throws IOException;

    protected abstract OutputStream getOutputStream() throws IOException;

    protected abstract int available() throws IOException;

    protected abstract void close() throws IOException;

    protected void shutdownInput() throws IOException {

      throw new IOException("Method not implemented!");

    }

    protected void shutdownOutput() throws IOException {

      throw new IOException("Method not implemented!");

    }

    protected FileDescriptor getFileDescriptor() {

        return fd;

    }

    protected InetAddress getInetAddress() {

        return address;

    }

    protected int getPort() {

        return port;

    }

    protected boolean supportsUrgentData () {

        return false; // must be overridden in sub-class

    }

    protected abstract void sendUrgentData (int data) throws IOException;

    protected int getLocalPort() {

        return localport;

    }

 

    void setSocket(Socket soc) {

        this.socket = soc;

    }

 

    Socket getSocket() {

        return socket;

    }

 

    void setServerSocket(ServerSocket soc) {

        this.serverSocket = soc;

    }

 

    ServerSocket getServerSocket() {

        return serverSocket;

    }

    public String toString() {

        return "Socket[addr=" + getInetAddress() +

            ",port=" + getPort() + ",localport=" + getLocalPort()  + "]";

    }

 

    void reset() throws IOException {

        address = null;

        port = 0;

        localport = 0;

    }

    protected void setPerformancePreferences(int connectionTime,

                                          int latency,

                                          int bandwidth)

    {

        /* Not implemented yet */

    }

 

    <T> void setOption(SocketOption<T> name, T value) throws IOException {

        if (name == StandardSocketOptions.SO_KEEPALIVE) {

            setOption(SocketOptions.SO_KEEPALIVE, value);

        } else if (name == StandardSocketOptions.SO_SNDBUF) {

            setOption(SocketOptions.SO_SNDBUF, value);

        } else if (name == StandardSocketOptions.SO_RCVBUF) {

            setOption(SocketOptions.SO_RCVBUF, value);

        } else if (name == StandardSocketOptions.SO_REUSEADDR) {

            setOption(SocketOptions.SO_REUSEADDR, value);

        } else if (name == StandardSocketOptions.SO_LINGER) {

            setOption(SocketOptions.SO_LINGER, value);

        } else if (name == StandardSocketOptions.IP_TOS) {

            setOption(SocketOptions.IP_TOS, value);

        } else if (name == StandardSocketOptions.TCP_NODELAY) {

            setOption(SocketOptions.TCP_NODELAY, value);

        } else {

            throw new UnsupportedOperationException("unsupported option");

        }

    }

 

    <T> T getOption(SocketOption<T> name) throws IOException {

        if (name == StandardSocketOptions.SO_KEEPALIVE) {

            return (T)getOption(SocketOptions.SO_KEEPALIVE);

        } else if (name == StandardSocketOptions.SO_SNDBUF) {

            return (T)getOption(SocketOptions.SO_SNDBUF);

        } else if (name == StandardSocketOptions.SO_RCVBUF) {

            return (T)getOption(SocketOptions.SO_RCVBUF);

        } else if (name == StandardSocketOptions.SO_REUSEADDR) {

            return (T)getOption(SocketOptions.SO_REUSEADDR);

        } else if (name == StandardSocketOptions.SO_LINGER) {

            return (T)getOption(SocketOptions.SO_LINGER);

        } else if (name == StandardSocketOptions.IP_TOS) {

            return (T)getOption(SocketOptions.IP_TOS);

        } else if (name == StandardSocketOptions.TCP_NODELAY) {

            return (T)getOption(SocketOptions.TCP_NODELAY);

        } else {

            throw new UnsupportedOperationException("unsupported option");

        }

    }

}

 

4.4 java.net. AbstractPlainSocketImpl

 

java.net. AbstractPlainSocketImpl

abstract class AbstractPlainSocketImpl extends SocketImpl{

protected void accept(SocketImpl s) throws IOException {

        acquireFD();

        try {

            socketAccept(s);

        } finally {

            releaseFD();

        }

    }

    protected synchronized InputStream getInputStream() throws IOException {

        synchronized (fdLock) {

            if (isClosedOrPending())

                throw new IOException("Socket Closed");

            if (shut_rd)

                throw new IOException("Socket input is shutdown");

            if (socketInputStream == null)

                socketInputStream = new SocketInputStream(this);

        }

        return socketInputStream;

    }

 

    void setInputStream(SocketInputStream in) {

        socketInputStream = in;

    }

    protected synchronized OutputStream getOutputStream() throws IOException {

        synchronized (fdLock) {

            if (isClosedOrPending())

                throw new IOException("Socket Closed");

            if (shut_wr)

                throw new IOException("Socket output is shutdown");

            if (socketOutputStream == null)

                socketOutputStream = new SocketOutputStream(this);

        }

        return socketOutputStream;

    }

}

 

 

 

 

4.5 java.net. Socket

 

java.net. Socket

 

public class Socket implements java.io.Closeable {

  public Socket() {

        setImpl();

}

void setImpl() {

        if (factory != null) {

            impl = factory.createSocketImpl();

            checkOldImpl();

        } else {

            impl = new SocksSocketImpl();

        }

        if (impl != null)

            impl.setSocket(this);

    }

}

 

    public void connect(SocketAddress endpoint, int timeout) throws IOException {

        if (endpoint == null)

            throw new IllegalArgumentException("connect: The address can't be null");

 

        if (timeout < 0)

          throw new IllegalArgumentException("connect: timeout can't be negative");

 

        if (isClosed())

            throw new SocketException("Socket is closed");

 

        if (!oldImpl && isConnected())

            throw new SocketException("already connected");

 

        if (!(endpoint instanceof InetSocketAddress))

            throw new IllegalArgumentException("Unsupported address type");

 

        InetSocketAddress epoint = (InetSocketAddress) endpoint;

        InetAddress addr = epoint.getAddress ();

        int port = epoint.getPort();

        checkAddress(addr, "connect");

 

        SecurityManager security = System.getSecurityManager();

        if (security != null) {

            if (epoint.isUnresolved())

                security.checkConnect(epoint.getHostName(), port);

            else

                security.checkConnect(addr.getHostAddress(), port);

        }

        if (!created)

            createImpl(true);

        if (!oldImpl)

            impl.connect(epoint, timeout);

        else if (timeout == 0) {

            if (epoint.isUnresolved())

                impl.connect(addr.getHostName(), port);

            else

                impl.connect(addr, port);

        } else

            throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");

        connected = true;

        bound = true;

}

   public InputStream getInputStream() throws IOException {

        if (isClosed())

            throw new SocketException("Socket is closed");

        if (!isConnected())

            throw new SocketException("Socket is not connected");

        if (isInputShutdown())

            throw new SocketException("Socket input is shutdown");

        final Socket s = this;

        InputStream is = null;

        try {

            is = AccessController.doPrivileged(

                new PrivilegedExceptionAction<InputStream>() {

                    public InputStream run() throws IOException {

                        return impl.getInputStream();

                    }

                });

        } catch (java.security.PrivilegedActionException e) {

            throw (IOException) e.getException();

        }

        return is;

    }

public OutputStream getOutputStream() throws IOException {

        if (isClosed())

            throw new SocketException("Socket is closed");

        if (!isConnected())

            throw new SocketException("Socket is not connected");

        if (isOutputShutdown())

            throw new SocketException("Socket output is shutdown");

        final Socket s = this;

        OutputStream os = null;

        try {

            os = AccessController.doPrivileged(

                new PrivilegedExceptionAction<OutputStream>() {

                    public OutputStream run() throws IOException {

                        return impl.getOutputStream();

                    }

                });

        } catch (java.security.PrivilegedActionException e) {

            throw (IOException) e.getException();

        }

        return os;

    }

 

 

4.6 java.net. ServerSocket

 

java.net. ServerSocket

public class ServerSocket implements java.io.Closeable {

   public Socket accept() throws IOException {

        if (isClosed())

            throw new SocketException("Socket is closed");

        if (!isBound())

            throw new SocketException("Socket is not bound yet");

        Socket s = new Socket((SocketImpl) null);

        implAccept(s);

        return s;

}

  protected final void implAccept(Socket s) throws IOException {

        SocketImpl si = null;

        try {

            if (s.impl == null)

              s.setImpl();

            else {

                s.impl.reset();

            }

            si = s.impl;

            s.impl = null;

            si.address = new InetAddress();

            si.fd = new FileDescriptor();

            getImpl().accept(si);

 

            SecurityManager security = System.getSecurityManager();

            if (security != null) {

                security.checkAccept(si.getInetAddress().getHostAddress(),

                                     si.getPort());

            }

        } catch (IOException e) {

            if (si != null)

                si.reset();

            s.impl = si;

            throw e;

        } catch (SecurityException e) {

            if (si != null)

                si.reset();

            s.impl = si;

            throw e;

        }

        s.impl = si;

        s.postAccept();

    }

}

 

4.7 java.net. proxy

 

java.net. proxy

 

public class Proxy {

 

    /**

     * Represents the proxy type.

     *

     * @since 1.5

     */

    public enum Type {

        /**

         * Represents a direct connection, or the absence of a proxy.

         */

        DIRECT,

        /**

         * Represents proxy for high level protocols such as HTTP or FTP.

         */

        HTTP,

        /**

         * Represents a SOCKS (V4 or V5) proxy.

         */

        SOCKS

    };

 

    private Type type;

    private SocketAddress sa;

    public final static Proxy NO_PROXY = new Proxy();

 

    // Creates the proxy that represents a {@code DIRECT} connection.

    private Proxy() {

        type = Type.DIRECT;

        sa = null;

    }

    public Proxy(Type type, SocketAddress sa) {

        if ((type == Type.DIRECT) || !(sa instanceof InetSocketAddress))

            throw new IllegalArgumentException("type " + type + " is not compatible with address " + sa);

        this.type = type;

        this.sa = sa;

    }

 

}

5.    java.nio

 

 

nio demo

public class ServerConnect

{

    public static void main(String[] args)

    {

        selector();

    }

    public static void handleAccept(SelectionKey key) throws IOException{

        ServerSocketChannel ssChannel = (ServerSocketChannel)key.channel();

        SocketChannel sc = ssChannel.accept();

        sc.configureBlocking(false);

        sc.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocateDirect(1024));

    }

    public static void handleRead(SelectionKey key) throws IOException{

        SocketChannel sc = (SocketChannel)key.channel();

        ByteBuffer buf = (ByteBuffer)key.attachment();

        long bytesRead = sc.read(buf);

        while(bytesRead>0){

            buf.flip();

            while(buf.hasRemaining()){

                System.out.print((char)buf.get());

            }

            buf.clear();

            bytesRead = sc.read(buf);

        }

        if(bytesRead == -1){

            sc.close();

        }

    }

    public static void handleWrite(SelectionKey key) throws IOException{

        ByteBuffer buf = (ByteBuffer)key.attachment();

        buf.flip();

        SocketChannel sc = (SocketChannel) key.channel();

        while(buf.hasRemaining()){

            sc.write(buf);

        }

        buf.compact();

    }

    public static void selector() {

        Selector selector = null;

        ServerSocketChannel ssc = null;

        try{

            selector = Selector.open();

            ssc= ServerSocketChannel.open();

            ssc.socket().bind(new InetSocketAddress(8080));

            ssc.configureBlocking(false);

            ssc.register(selector, SelectionKey.OP_ACCEPT);

            while(true){

                if(selector.select(3000) == 0){

                    continue;

                }

                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();

                while(iter.hasNext()){

                    SelectionKey key = iter.next();

                    if(key.isAcceptable()){

                        handleAccept(key);

                    }

                    if(key.isReadable()){

                        handleRead(key);

                    }

                    if(key.isWritable() && key.isValid()){

                        handleWrite(key);

                    }

                    if(key.isConnectable()){

                        System.out.println("isConnectable = true");

                    }

                    iter.remove();

                }

            }

        }catch(IOException e){

            e.printStackTrace();

        }finally{

            try{

                if(selector!=null){

                    selector.close();

                }

                if(ssc!=null){

                    ssc.close();

                }

            }catch(IOException e){

                e.printStackTrace();

            }

        }

    }

}

 

 

 

5.1 java.nio.channels.Channel

 

 

java.nio.channels.Channel

 

 

public interface Channel extends Closeable {

    public boolean isOpen();

    public void close() throws IOException;

 

}

 

5.2 java.nio.channels. SelectableChannel

 

java.nio.channels. SelectableChannel

 

public abstract class SelectableChannel extends AbstractInterruptibleChannel implements Channel{

    protected SelectableChannel() { }

public abstract SelectorProvider provider();

    public abstract SelectionKey register(Selector sel, int ops, Object att)

        throws ClosedChannelException;

}

 

5.3 java.nio.channels. AbstractSelectableChannel

 

java.nio.channels. AbstractSelectableChannel

public abstract class AbstractSelectableChannel

    extends SelectableChannel

{

    private final SelectorProvider provider;

private SelectionKey[] keys = null;

  public final SelectionKey register(Selector sel, int ops,

                                       Object att)

        throws ClosedChannelException

    {

        synchronized (regLock) {

            if (!isOpen())

                throw new ClosedChannelException();

            if ((ops & ~validOps()) != 0)

                throw new IllegalArgumentException();

            if (blocking)

                throw new IllegalBlockingModeException();

            SelectionKey k = findKey(sel);

            if (k != null) {

                k.interestOps(ops);

                k.attach(att);

            }

            if (k == null) {

                // New registration

                synchronized (keyLock) {

                    if (!isOpen())

                        throw new ClosedChannelException();

                    k = ((AbstractSelector)sel).register(this, ops, att);

                    addKey(k);

                }

            }

            return k;

        }

    }

}

 

5.4 java.nio.channels. ServerSocketChannel

 

java.nio.channels. ServerSocketChannel

 

public abstract class ServerSocketChannel

    extends AbstractSelectableChannel

    implements NetworkChannel{

    public abstract SocketChannel accept() throws IOException;

}

 

5.5 java.nio.channels.SelectionKey

 

java.nio.channels.SelectionKey

 

public abstract class SelectionKey {

    protected SelectionKey() { }

    public abstract SelectableChannel channel();

public abstract Selector selector();

public static final int OP_READ = 1 << 0;

    public static final int OP_WRITE = 1 << 2;

    public static final int OP_CONNECT = 1 << 3;

public static final int OP_ACCEPT = 1 << 4;

    private volatile Object attachment = null;

}

 

5.6 sun.nio.ch.WindowsSelectorImpl

sun.nio.ch.WindowsSelectorImpldoselect

 

 

class WindowsSelectorImpl extends SelectorImpl {

private final SubSelector subSelector = new SubSelector();

 

  protected int doSelect(Consumer<SelectionKey> action, long timeout)

        throws IOException

    {

        assert Thread.holdsLock(this);

        this.timeout = timeout; // set selector timeout

        processUpdateQueue();

        processDeregisterQueue();

        if (interruptTriggered) {

            resetWakeupSocket();

            return 0;

        }

        // Calculate number of helper threads needed for poll. If necessary

        // threads are created here and start waiting on startLock

        adjustThreadsCount();

        finishLock.reset(); // reset finishLock

        // Wakeup helper threads, waiting on startLock, so they start polling.

        // Redundant threads will exit here after wakeup.

        startLock.startThreads();

        // do polling in the main thread. Main thread is responsible for

        // first MAX_SELECTABLE_FDS entries in pollArray.

        try {

            begin();

            try {

                subSelector.poll();

            } catch (IOException e) {

                finishLock.setException(e); // Save this exception

            }

            // Main thread is out of poll(). Wakeup others and wait for them

            if (threads.size() > 0)

                finishLock.waitForHelperThreads();

          } finally {

              end();

          }

        // Done with poll(). Set wakeupSocket to nonsignaled  for the next run.

        finishLock.checkForException();

        processDeregisterQueue();

        int updated = updateSelectedKeys(action);

        // Done with poll(). Set wakeupSocket to nonsignaled  for the next run.

        resetWakeupSocket();

        return updated;

    }

}

 

5.7 sun.nio.ch.WindowsSelectorImpl. SubSelector

sun.nio.ch.WindowsSelectorImpl. SubSelectorsubSelector.poll();

 

private final class SubSelector {

        private final int pollArrayIndex; // starting index in pollArray to poll

        // These arrays will hold result of native select().

        // The first element of each array is the number of selected sockets.

        // Other elements are file descriptors of selected sockets.

        private final int[] readFds = new int [MAX_SELECTABLE_FDS + 1];

        private final int[] writeFds = new int [MAX_SELECTABLE_FDS + 1];

        private final int[] exceptFds = new int [MAX_SELECTABLE_FDS + 1];

        // Buffer for readfds, writefds and exceptfds structs that are passed

        // to native select().

        private final long fdsBuffer = unsafe.allocateMemory(SIZEOF_FD_SET * 3);

 

        private SubSelector() {

            this.pollArrayIndex = 0; // main thread

        }

 

        private SubSelector(int threadIndex) { // helper threads

            this.pollArrayIndex = (threadIndex + 1) * MAX_SELECTABLE_FDS;

        }

 

       private int poll() throws IOException{ // poll for the main thread

            return poll0(pollWrapper.pollArrayAddress,

                         Math.min(totalChannels, MAX_SELECTABLE_FDS),

                         readFds, writeFds, exceptFds, timeout, fdsBuffer);

        }

 

        private int poll(int index) throws IOException {

            // poll for helper threads

            return  poll0(pollWrapper.pollArrayAddress +

                     (pollArrayIndex * PollArrayWrapper.SIZE_POLLFD),

                     Math.min(MAX_SELECTABLE_FDS,

                             totalChannels - (index + 1) * MAX_SELECTABLE_FDS),

                     readFds, writeFds, exceptFds, timeout, fdsBuffer);

        }

 

        private native int poll0(long pollAddress, int numfds,

             int[] readFds, int[] writeFds, int[] exceptFds, long timeout, long fdsBuffer);

 

        private int processSelectedKeys(long updateCount, Consumer<SelectionKey> action)

            throws IOException

        {

            int numKeysUpdated = 0;

            numKeysUpdated += processFDSet(updateCount, action, readFds,

                                           Net.POLLIN,

                                           false);

            numKeysUpdated += processFDSet(updateCount, action, writeFds,

                                           Net.POLLCONN |

                                           Net.POLLOUT,

                                           false);

            numKeysUpdated += processFDSet(updateCount, action, exceptFds,

                                           Net.POLLIN |

                                           Net.POLLCONN |

                                           Net.POLLOUT,

                                           true);

            return numKeysUpdated;

        }

  private int processFDSet(long updateCount,

                                 Consumer<SelectionKey> action,

                                 int[] fds, int rOps,

                                 boolean isExceptFds)

            throws IOException

        {

            int numKeysUpdated = 0;

            for (int i = 1; i <= fds[0]; i++) {

                int desc = fds[i];

                if (desc == wakeupSourceFd) {

                    synchronized (interruptLock) {

                        interruptTriggered = true;

                    }

                    continue;

                }

                MapEntry me = fdMap.get(desc);

                // If me is null, the key was deregistered in the previous

                // processDeregisterQueue.

                if (me == null)

                    continue;

                SelectionKeyImpl ski = me.ski;

 

                // The descriptor may be in the exceptfds set because there is

                // OOB data queued to the socket. If there is OOB data then it

                // is discarded and the key is not added to the selected set.

                SelectableChannel sc = ski.channel();

                if (isExceptFds && (sc instanceof SocketChannelImpl)

                        && ((SocketChannelImpl) sc).isNetSocket()

                        && Net.discardOOB(ski.getFD())) {

                    continue;

                }

 

                int updated = processReadyEvents(rOps, ski, action);

                if (updated > 0 && me.updateCount != updateCount) {

                    me.updateCount = updateCount;

                    numKeysUpdated++;

                }

            }

            return numKeysUpdated;

        }

 

}

6.    java.util

 

 

6.1 java.util.Iterable

 

java.lang. Iterable

 

public interface Iterable<T> {

    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {

        Objects.requireNonNull(action);

        for (T t : this) {

            action.accept(t);

        }

    }

    default Spliterator<T> spliterator() {

        return Spliterators.spliteratorUnknownSize(iterator(), 0);

    }

}

 

6.2 java.util.Collection

java.lang. Collection

 

public interface Collection<E> extends Iterable<E> {

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] a);

    boolean add(E e);

    boolean remove(Object o);

    boolean containsAll(Collection<?> c);

    boolean addAll(Collection<? extends E> c);

    boolean removeAll(Collection<?> c);

    default boolean removeIf(Predicate<? super E> filter) {

        Objects.requireNonNull(filter);

        boolean removed = false;

        final Iterator<E> each = iterator();

        while (each.hasNext()) {

            if (filter.test(each.next())) {

                each.remove();

                removed = true;

            }

        }

        return removed;

    }

    boolean retainAll(Collection<?> c);

    void clear();

    boolean equals(Object o);

    int hashCode();

    @Override

    default Spliterator<E> spliterator() {

        return Spliterators.spliterator(this, 0);

    }

    default Stream<E> stream() {

        return StreamSupport.stream(spliterator(), false);

    }

    default Stream<E> parallelStream() {

        return StreamSupport.stream(spliterator(), true);

    }

}

 

 

 

 

6.3 java.util.List

java.lang. List

 

 

public interface List<E> extends Collection<E> {

  

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] a);

    boolean add(E e);

    boolean remove(Object o);

    boolean containsAll(Collection<?> c);

    boolean addAll(Collection<? extends E> c);

    boolean addAll(int index, Collection<? extends E> c);

    boolean removeAll(Collection<?> c);

    boolean retainAll(Collection<?> c);

    default void replaceAll(UnaryOperator<E> operator) {

        Objects.requireNonNull(operator);

        final ListIterator<E> li = this.listIterator();

        while (li.hasNext()) {

            li.set(operator.apply(li.next()));

        }

    }

    @SuppressWarnings({"unchecked", "rawtypes"})

    default void sort(Comparator<? super E> c) {

        Object[] a = this.toArray();

        Arrays.sort(a, (Comparator) c);

        ListIterator<E> i = this.listIterator();

        for (Object e : a) {

            i.next();

            i.set((E) e);

        }

    }

    void clear();

    boolean equals(Object o);

    int hashCode();

    E get(int index);

    E set(int index, E element);

    void add(int index, E element);

    E remove(int index);

    int indexOf(Object o);

    int lastIndexOf(Object o);

    ListIterator<E> listIterator();

    ListIterator<E> listIterator(int index);

    List<E> subList(int fromIndex, int toIndex);

    @Override

    default Spliterator<E> spliterator() {

        return Spliterators.spliterator(this, Spliterator.ORDERED);

    }

}

 

 

 

6.4 java.util. Queue

 

java.util. Queue

 

public interface Queue<E> extends Collection<E> {

    boolean add(E e);

    boolean offer(E e);

    E remove();

    E poll();

    E element();

    E peek();

}

 

 

 

 

6.5 java.util. Deque

 

java.lang. Deque

 

public interface Deque<E> extends Queue<E> {

    void addFirst(E e);

    void addLast(E e);

    boolean offerFirst(E e);

    boolean offerLast(E e);

    E removeFirst();

    E removeLast();

    E pollFirst();

    E pollLast();

    E getFirst();

    E getLast();

    E peekFirst();

    E peekLast();

    boolean removeFirstOccurrence(Object o);

    boolean removeLastOccurrence(Object o);

    boolean add(E e);

    boolean offer(E e);

    E remove();

    E poll();

    E element();

    E peek();

    void push(E e);

    E pop();

    boolean remove(Object o);

    boolean contains(Object o);

    public int size();

    Iterator<E> iterator();

    Iterator<E> descendingIterator();

 

}

 

 

6.6 java.util. AbstractCollection

java.util. AbstractCollection

 

public abstract class AbstractCollection<E> implements Collection<E> {

    protected AbstractCollection() {

    }

    public abstract Iterator<E> iterator();

 

    public abstract int size();

    public boolean isEmpty() {

        return size() == 0;

    }

    public boolean contains(Object o) {

        Iterator<E> it = iterator();

        if (o==null) {

            while (it.hasNext())

                if (it.next()==null)

                    return true;

        } else {

            while (it.hasNext())

                if (o.equals(it.next()))

                    return true;

        }

        return false;

    }

    public Object[] toArray() {

        // Estimate size of array; be prepared to see more or fewer elements

        Object[] r = new Object[size()];

        Iterator<E> it = iterator();

        for (int i = 0; i < r.length; i++) {

            if (! it.hasNext()) // fewer elements than expected

                return Arrays.copyOf(r, i);

            r[i] = it.next();

        }

        return it.hasNext() ? finishToArray(r, it) : r;

    }

    @SuppressWarnings("unchecked")

    public <T> T[] toArray(T[] a) {

        // Estimate size of array; be prepared to see more or fewer elements

        int size = size();

        T[] r = a.length >= size ? a :

                  (T[])java.lang.reflect.Array

                  .newInstance(a.getClass().getComponentType(), size);

        Iterator<E> it = iterator();

 

        for (int i = 0; i < r.length; i++) {

            if (! it.hasNext()) { // fewer elements than expected

                if (a == r) {

                    r[i] = null; // null-terminate

                } else if (a.length < i) {

                    return Arrays.copyOf(r, i);

                } else {

                    System.arraycopy(r, 0, a, 0, i);

                    if (a.length > i) {

                        a[i] = null;

                    }

                }

                return a;

            }

            r[i] = (T)it.next();

        }

        // more elements than expected

        return it.hasNext() ? finishToArray(r, it) : r;

    }

}

 

 

6.7 java.util. AbstractList

java.util. AbstractList

 

 

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

    protected AbstractList() {

    }

 

  public Iterator<E> iterator() {

        return new Itr();

    }

    public ListIterator<E> listIterator() {

        return listIterator(0);

    }

    public ListIterator<E> listIterator(final int index) {

        rangeCheckForAdd(index);

 

        return new ListItr(index);

    }

 

    private class Itr implements Iterator<E> {

        int cursor = 0;

        int lastRet = -1;

        int expectedModCount = modCount;

 

        public boolean hasNext() {

            return cursor != size();

        }

 

        public E next() {

            checkForComodification();

            try {

                int i = cursor;

                E next = get(i);

                lastRet = i;

                cursor = i + 1;

                return next;

            } catch (IndexOutOfBoundsException e) {

                checkForComodification();

                throw new NoSuchElementException();

            }

        }

 

        public void remove() {

            if (lastRet < 0)

                throw new IllegalStateException();

            checkForComodification();

 

            try {

                AbstractList.this.remove(lastRet);

                if (lastRet < cursor)

                    cursor--;

                lastRet = -1;

                expectedModCount = modCount;

            } catch (IndexOutOfBoundsException e) {

                throw new ConcurrentModificationException();

            }

        }

 

        final void checkForComodification() {

            if (modCount != expectedModCount)

                throw new ConcurrentModificationException();

        }

    }

 

    private class ListItr extends Itr implements ListIterator<E> {

        ListItr(int index) {

            cursor = index;

        }

 

        public boolean hasPrevious() {

            return cursor != 0;

        }

 

        public E previous() {

            checkForComodification();

            try {

                int i = cursor - 1;

                E previous = get(i);

                lastRet = cursor = i;

                return previous;

            } catch (IndexOutOfBoundsException e) {

                checkForComodification();

                throw new NoSuchElementException();

            }

        }

 

        public int nextIndex() {

            return cursor;

        }

 

        public int previousIndex() {

            return cursor-1;

        }

 

        public void set(E e) {

            if (lastRet < 0)

                throw new IllegalStateException();

            checkForComodification();

 

            try {

                AbstractList.this.set(lastRet, e);

                expectedModCount = modCount;

            } catch (IndexOutOfBoundsException ex) {

                throw new ConcurrentModificationException();

            }

        }

 

        public void add(E e) {

            checkForComodification();

 

            try {

                int i = cursor;

                AbstractList.this.add(i, e);

                lastRet = -1;

                cursor = i + 1;

                expectedModCount = modCount;

            } catch (IndexOutOfBoundsException ex) {

                throw new ConcurrentModificationException();

            }

        }

    }

 

}

 

6.8 java.util. AbstractSequentialList

java.util. AbstractSequentialList

 

 

public abstract class AbstractSequentialList<E> extends AbstractList<E> {

    protected AbstractSequentialList() {

    }

    public E get(int index) {

        try {

            return listIterator(index).next();

        } catch (NoSuchElementException exc) {

            throw new IndexOutOfBoundsException("Index: "+index);

        }

    }

    public E set(int index, E element) {

        try {

            ListIterator<E> e = listIterator(index);

            E oldVal = e.next();

            e.set(element);

            return oldVal;

        } catch (NoSuchElementException exc) {

            throw new IndexOutOfBoundsException("Index: "+index);

        }

    }

    public void add(int index, E element) {

        try {

            listIterator(index).add(element);

        } catch (NoSuchElementException exc) {

            throw new IndexOutOfBoundsException("Index: "+index);

        }

    }

    public E remove(int index) {

        try {

            ListIterator<E> e = listIterator(index);

            E outCast = e.next();

            e.remove();

            return outCast;

        } catch (NoSuchElementException exc) {

            throw new IndexOutOfBoundsException("Index: "+index);

        }

    }

    public boolean addAll(int index, Collection<? extends E> c) {

        try {

            boolean modified = false;

            ListIterator<E> e1 = listIterator(index);

            Iterator<? extends E> e2 = c.iterator();

            while (e2.hasNext()) {

                e1.add(e2.next());

                modified = true;

            }

            return modified;

        } catch (NoSuchElementException exc) {

            throw new IndexOutOfBoundsException("Index: "+index);

        }

    }

    public Iterator<E> iterator() {

        return listIterator();

    }

    public abstract ListIterator<E> listIterator(int index);

}

 

 

6.9 Java.util.LinkedList

Java.util.LinkedList主要方法

 

 

 

public class LinkedList<E>

    extends AbstractSequentialList<E>

    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

{

    transient int size = 0;

    transient Node<E> first;

    transient Node<E> last;

    public LinkedList() {

    }

private void linkFirst(E e) {

        final Node<E> f = first;

        final Node<E> newNode = new Node<>(null, e, f);

        first = newNode;

        if (f == null)

            last = newNode;

        else

            f.prev = newNode;

        size++;

        modCount++;

    }

    void linkLast(E e) {

        final Node<E> l = last;

        final Node<E> newNode = new Node<>(l, e, null);

        last = newNode;

        if (l == null)

            first = newNode;

        else

            l.next = newNode;

        size++;

        modCount++;

    }

    void linkBefore(E e, Node<E> succ) {

        // assert succ != null;

        final Node<E> pred = succ.prev;

        final Node<E> newNode = new Node<>(pred, e, succ);

        succ.prev = newNode;

        if (pred == null)

            first = newNode;

        else

            pred.next = newNode;

        size++;

        modCount++;

    }

    private E unlinkFirst(Node<E> f) {

        // assert f == first && f != null;

        final E element = f.item;

        final Node<E> next = f.next;

        f.item = null;

        f.next = null; // help GC

        first = next;

        if (next == null)

            last = null;

        else

            next.prev = null;

        size--;

        modCount++;

        return element;

    }

    private E unlinkLast(Node<E> l) {

        // assert l == last && l != null;

        final E element = l.item;

        final Node<E> prev = l.prev;

        l.item = null;

        l.prev = null; // help GC

        last = prev;

        if (prev == null)

            first = null;

        else

            prev.next = null;

        size--;

        modCount++;

        return element;

    }

    public boolean add(E e) {

        linkLast(e);

        return true;

    }

}

 

 

6.9.1 Node

 

Java.util.LinkedList.Node

 

 

    private static class Node<E> {

        E item;

        Node<E> next;

        Node<E> prev;

 

        Node(Node<E> prev, E element, Node<E> next) {

            this.item = element;

            this.next = next;

            this.prev = prev;

        }

    }

 

6.9.2 DescendingIterator

Java.util.LinkedList.DescendingIterator

 

  private class DescendingIterator implements Iterator<E> {

        private final ListItr itr = new ListItr(size());

        public boolean hasNext() {

            return itr.hasPrevious();

        }

        public E next() {

            return itr.previous();

        }

        public void remove() {

            itr.remove();

        }

    }

 

 

6.9.3 LLSpliterator

Java.util.LinkedList.LLSpliterator

 

 

 

    static final class LLSpliterator<E> implements Spliterator<E> {

        static final int BATCH_UNIT = 1 << 10;  // batch array size increment

        static final int MAX_BATCH = 1 << 25;  // max batch array size;

        final LinkedList<E> list; // null OK unless traversed

        Node<E> current;      // current node; null until initialized

        int est;              // size estimate; -1 until first needed

        int expectedModCount; // initialized when est set

        int batch;            // batch size for splits

 

        LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {

            this.list = list;

            this.est = est;

            this.expectedModCount = expectedModCount;

        }

 

        final int getEst() {

            int s; // force initialization

            final LinkedList<E> lst;

            if ((s = est) < 0) {

                if ((lst = list) == null)

                    s = est = 0;

                else {

                    expectedModCount = lst.modCount;

                    current = lst.first;

                    s = est = lst.size;

                }

            }

            return s;

        }

 

        public long estimateSize() { return (long) getEst(); }

 

        public Spliterator<E> trySplit() {

            Node<E> p;

            int s = getEst();

            if (s > 1 && (p = current) != null) {

                int n = batch + BATCH_UNIT;

                if (n > s)

                    n = s;

                if (n > MAX_BATCH)

                    n = MAX_BATCH;

                Object[] a = new Object[n];

                int j = 0;

                do { a[j++] = p.item; } while ((p = p.next) != null && j < n);

                current = p;

                batch = j;

                est = s - j;

                return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);

            }

            return null;

        }

 

        public void forEachRemaining(Consumer<? super E> action) {

            Node<E> p; int n;

            if (action == null) throw new NullPointerException();

            if ((n = getEst()) > 0 && (p = current) != null) {

                current = null;

                est = 0;

                do {

                    E e = p.item;

                    p = p.next;

                    action.accept(e);

                } while (p != null && --n > 0);

            }

            if (list.modCount != expectedModCount)

                throw new ConcurrentModificationException();

        }

 

        public boolean tryAdvance(Consumer<? super E> action) {

            Node<E> p;

            if (action == null) throw new NullPointerException();

            if (getEst() > 0 && (p = current) != null) {

                --est;

                E e = p.item;

                current = p.next;

                action.accept(e);

                if (list.modCount != expectedModCount)

                    throw new ConcurrentModificationException();

                return true;

            }

            return false;

        }

 

        public int characteristics() {

            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;

        }

    }

 

}

 

6.10 java.util.ArrayList

java.util.ArrayList主要方法

 

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

{

    private static final long serialVersionUID = 8683452581122892189L;

    private static final int DEFAULT_CAPACITY = 10;

    private static final Object[] EMPTY_ELEMENTDATA = {};

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    transient Object[] elementData; // non-private to simplify nested class access

    private int size;

    public ArrayList(int initialCapacity) {

        if (initialCapacity > 0) {

            this.elementData = new Object[initialCapacity];

        } else if (initialCapacity == 0) {

            this.elementData = EMPTY_ELEMENTDATA;

        } else {

            throw new IllegalArgumentException("Illegal Capacity: "+

                                               initialCapacity);

        }

    }

public boolean add(E e) {

        ensureCapacityInternal(size + 1);  // Increments modCount!!

        elementData[size++] = e;

        return true;

    }

    public void add(int index, E element) {

        rangeCheckForAdd(index);

 

        ensureCapacityInternal(size + 1);  // Increments modCount!!

        System.arraycopy(elementData, index, elementData, index + 1,

                         size - index);

        elementData[index] = element;

        size++;

    }

private static int calculateCapacity(Object[] elementData, int minCapacity) {

        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {

            return Math.max(DEFAULT_CAPACITY, minCapacity);

        }

        return minCapacity;

    }

    private void ensureCapacityInternal(int minCapacity) {

        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));

    }

    private void ensureExplicitCapacity(int minCapacity) {

        modCount++;

 

        // overflow-conscious code

        if (minCapacity - elementData.length > 0)

            grow(minCapacity);

    }

    private void grow(int minCapacity) {

        // overflow-conscious code

        int oldCapacity = elementData.length;

        int newCapacity = oldCapacity + (oldCapacity >> 1);

        if (newCapacity - minCapacity < 0)

            newCapacity = minCapacity;

        if (newCapacity - MAX_ARRAY_SIZE > 0)

            newCapacity = hugeCapacity(minCapacity);

        // minCapacity is usually close to size, so this is a win:

        elementData = Arrays.copyOf(elementData, newCapacity);

    }

 

    private static int hugeCapacity(int minCapacity) {

        if (minCapacity < 0) // overflow

            throw new OutOfMemoryError();

        return (minCapacity > MAX_ARRAY_SIZE) ?

            Integer.MAX_VALUE :

            MAX_ARRAY_SIZE;

    }

}

 

6.11 java.util.Map

java.util.Map主要方法

public interface Map<K,V> {

    int size();

    boolean isEmpty();

    boolean containsKey(Object key);

    boolean containsValue(Object value);

    V get(Object key);

    V put(K key, V value);

    V remove(Object key);

    void putAll(Map<? extends K, ? extends V> m);

    void clear();

    Set<K> keySet();

    Collection<V> values();

    Set<Map.Entry<K, V>> entrySet();

 

    boolean equals(Object o);

    int hashCode();

    default V getOrDefault(Object key, V defaultValue) {

        V v;

        return (((v = get(key)) != null) || containsKey(key))

            ? v

            : defaultValue;

    }

    default void forEach(BiConsumer<? super K, ? super V> action) {

        Objects.requireNonNull(action);

        for (Map.Entry<K, V> entry : entrySet()) {

            K k;

            V v;

            try {

                k = entry.getKey();

                v = entry.getValue();

            } catch(IllegalStateException ise) {

                // this usually means the entry is no longer in the map.

                throw new ConcurrentModificationException(ise);

            }

            action.accept(k, v);

        }

    }

    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {

        Objects.requireNonNull(function);

        for (Map.Entry<K, V> entry : entrySet()) {

            K k;

            V v;

            try {

                k = entry.getKey();

                v = entry.getValue();

            } catch(IllegalStateException ise) {

                // this usually means the entry is no longer in the map.

                throw new ConcurrentModificationException(ise);

            }

 

            // ise thrown from function is not a cme.

            v = function.apply(k, v);

 

            try {

                entry.setValue(v);

            } catch(IllegalStateException ise) {

                // this usually means the entry is no longer in the map.

                throw new ConcurrentModificationException(ise);

            }

        }

    }

    default V putIfAbsent(K key, V value) {

        V v = get(key);

        if (v == null) {

            v = put(key, value);

        }

 

        return v;

    }

    default boolean remove(Object key, Object value) {

        Object curValue = get(key);

        if (!Objects.equals(curValue, value) ||

            (curValue == null && !containsKey(key))) {

            return false;

        }

        remove(key);

        return true;

    }

    default boolean replace(K key, V oldValue, V newValue) {

        Object curValue = get(key);

        if (!Objects.equals(curValue, oldValue) ||

            (curValue == null && !containsKey(key))) {

            return false;

        }

        put(key, newValue);

        return true;

    }

    default V replace(K key, V value) {

        V curValue;

        if (((curValue = get(key)) != null) || containsKey(key)) {

            curValue = put(key, value);

        }

        return curValue;

    }

    default V computeIfAbsent(K key,

            Function<? super K, ? extends V> mappingFunction) {

        Objects.requireNonNull(mappingFunction);

        V v;

        if ((v = get(key)) == null) {

            V newValue;

            if ((newValue = mappingFunction.apply(key)) != null) {

                put(key, newValue);

                return newValue;

            }

        }

 

        return v;

    }

    default V computeIfPresent(K key,

            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {

        Objects.requireNonNull(remappingFunction);

        V oldValue;

        if ((oldValue = get(key)) != null) {

            V newValue = remappingFunction.apply(key, oldValue);

            if (newValue != null) {

                put(key, newValue);

                return newValue;

            } else {

                remove(key);

                return null;

            }

        } else {

            return null;

        }

    }

    default V compute(K key,

            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {

        Objects.requireNonNull(remappingFunction);

        V oldValue = get(key);

 

        V newValue = remappingFunction.apply(key, oldValue);

        if (newValue == null) {

            // delete mapping

            if (oldValue != null || containsKey(key)) {

                // something to remove

                remove(key);

                return null;

            } else {

                // nothing to do. Leave things as they were.

                return null;

            }

        } else {

            // add or replace old mapping

            put(key, newValue);

            return newValue;

        }

    }

    default V merge(K key, V value,

            BiFunction<? super V, ? super V, ? extends V> remappingFunction) {

        Objects.requireNonNull(remappingFunction);

        Objects.requireNonNull(value);

        V oldValue = get(key);

        V newValue = (oldValue == null) ? value :

                   remappingFunction.apply(oldValue, value);

        if(newValue == null) {

            remove(key);

        } else {

            put(key, newValue);

        }

        return newValue;

    }

}

 

 

6.11.1 Entry

 

Java.util.Map.Entry

 

 

 

  interface Entry<K,V> {

        K getKey();

        V getValue();

        V setValue(V value);

        boolean equals(Object o);

        int hashCode();

        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {

            return (Comparator<Map.Entry<K, V>> & Serializable)

                (c1, c2) -> c1.getKey().compareTo(c2.getKey());

        }

        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {

            return (Comparator<Map.Entry<K, V>> & Serializable)

                (c1, c2) -> c1.getValue().compareTo(c2.getValue());

        }

        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {

            Objects.requireNonNull(cmp);

            return (Comparator<Map.Entry<K, V>> & Serializable)

                (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());

        }

        public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {

            Objects.requireNonNull(cmp);

            return (Comparator<Map.Entry<K, V>> & Serializable)

                (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());

        }

    }

 

 

6.12 java.util. AbstractMap

java.util. AbstractMap主要方法

public abstract class AbstractMap<K,V> implements Map<K,V> {

    public boolean containsKey(Object key) {

        Iterator<Map.Entry<K,V>> i = entrySet().iterator();

        if (key==null) {

            while (i.hasNext()) {

                Entry<K,V> e = i.next();

                if (e.getKey()==null)

                    return true;

            }

        } else {

            while (i.hasNext()) {

                Entry<K,V> e = i.next();

                if (key.equals(e.getKey()))

                    return true;

            }

        }

        return false;

    }

  public boolean containsValue(Object value) {

        Iterator<Entry<K,V>> i = entrySet().iterator();

        if (value==null) {

            while (i.hasNext()) {

                Entry<K,V> e = i.next();

                if (e.getValue()==null)

                    return true;

            }

        } else {

            while (i.hasNext()) {

                Entry<K,V> e = i.next();

                if (value.equals(e.getValue()))

                    return true;

            }

        }

        return false;

    }

   public int hashCode() {

        int h = 0;

        Iterator<Entry<K,V>> i = entrySet().iterator();

        while (i.hasNext())

            h += i.next().hashCode();

        return h;

    }

 

 

6.13 java.util. SortedMap

java.util. SortedMap主要方法

public interface SortedMap<K,V> extends Map<K,V> {

    Comparator<? super K> comparator();

    SortedMap<K,V> subMap(K fromKey, K toKey);

    SortedMap<K,V> headMap(K toKey);

    SortedMap<K,V> tailMap(K fromKey);

    K firstKey();

    K lastKey();

    Set<K> keySet();

    Collection<V> values();

    Set<Map.Entry<K, V>> entrySet();

}

 

 

6.14 java.util. NavigableMap

java.util. NavigableMap主要方法

 

 

public interface NavigableMap<K,V> extends SortedMap<K,V> {

    Map.Entry<K,V> lowerEntry(K key);

    K lowerKey(K key);

    Map.Entry<K,V> floorEntry(K key);

    K floorKey(K key);

    Map.Entry<K,V> ceilingEntry(K key);

    K ceilingKey(K key);

    Map.Entry<K,V> higherEntry(K key);

    K higherKey(K key);

    Map.Entry<K,V> firstEntry();

    Map.Entry<K,V> lastEntry();

    Map.Entry<K,V> pollFirstEntry();

    Map.Entry<K,V> pollLastEntry();

    NavigableMap<K,V> descendingMap();

    NavigableSet<K> navigableKeySet();

    NavigableSet<K> descendingKeySet();

    NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,

                             K toKey,   boolean toInclusive);

    NavigableMap<K,V> headMap(K toKey, boolean inclusive);

    NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);

    SortedMap<K,V> subMap(K fromKey, K toKey);

    SortedMap<K,V> headMap(K toKey);

    SortedMap<K,V> tailMap(K fromKey);

}

 

 

6.15 java.util.HashMap

java.util. HashMap主要方法

public class HashMap<K,V> extends AbstractMap<K,V>

    implements Map<K,V>, Cloneable, Serializable {

public V put(K key, V value) {

        return putVal(hash(key), key, value, false, true);

    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

                   boolean evict) {

        Node<K,V>[] tab; Node<K,V> p; int n, i;

        if ((tab = table) == null || (n = tab.length) == 0)

            n = (tab = resize()).length;

        if ((p = tab[i = (n - 1) & hash]) == null)

            tab[i] = newNode(hash, key, value, null);

        else {

            Node<K,V> e; K k;

            if (p.hash == hash &&

                ((k = p.key) == key || (key != null && key.equals(k))))

                e = p;

            else if (p instanceof TreeNode)

                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

            else {

                for (int binCount = 0; ; ++binCount) {

                    if ((e = p.next) == null) {

                        p.next = newNode(hash, key, value, null);

                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

                            treeifyBin(tab, hash);

                        break;

                    }

                    if (e.hash == hash &&

                        ((k = e.key) == key || (key != null && key.equals(k))))

                        break;

                    p = e;

                }

            }

            if (e != null) { // existing mapping for key

                V oldValue = e.value;

                if (!onlyIfAbsent || oldValue == null)

                    e.value = value;

                afterNodeAccess(e);

                return oldValue;

            }

        }

        ++modCount;

        if (++size > threshold)

            resize();

        afterNodeInsertion(evict);

        return null;

    }

public V get(Object key) {

        Node<K,V> e;

        return (e = getNode(hash(key), key)) == null ? null : e.value;

    }

    final Node<K,V> getNode(int hash, Object key) {

        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

        if ((tab = table) != null && (n = tab.length) > 0 &&

            (first = tab[(n - 1) & hash]) != null) {

            if (first.hash == hash && // always check first node

                ((k = first.key) == key || (key != null && key.equals(k))))

                return first;

            if ((e = first.next) != null) {

                if (first instanceof TreeNode)

                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);

                do {

                    if (e.hash == hash &&

                        ((k = e.key) == key || (key != null && key.equals(k))))

                        return e;

                } while ((e = e.next) != null);

            }

        }

        return null;

    }

 

 

}

 

java.util. HashMap超过8个时候扩容为红黑树treeifyBin

 

 

  final void treeifyBin(Node<K,V>[] tab, int hash) {

        int n, index; Node<K,V> e;

        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)

            resize();

        else if ((e = tab[index = (n - 1) & hash]) != null) {

            TreeNode<K,V> hd = null, tl = null;

            do {

                TreeNode<K,V> p = replacementTreeNode(e, null);

                if (tl == null)

                    hd = p;

                else {

                    p.prev = tl;

                    tl.next = p;

                }

                tl = p;

            } while ((e = e.next) != null);

            if ((tab[index] = hd) != null)

                hd.treeify(tab);

        }

}

 

 

 

 

 

6.15.1 KeySet

java.util. HashMap.KeySet

 

   final class KeySet extends AbstractSet<K> {

        public final int size()                 { return size; }

        public final void clear()               { HashMap.this.clear(); }

        public final Iterator<K> iterator()     { return new KeyIterator(); }

        public final boolean contains(Object o) { return containsKey(o); }

        public final boolean remove(Object key) {

            return removeNode(hash(key), key, null, false, true) != null;

        }

        public final Spliterator<K> spliterator() {

            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);

        }

        public final void forEach(Consumer<? super K> action) {

            Node<K,V>[] tab;

            if (action == null)

                throw new NullPointerException();

            if (size > 0 && (tab = table) != null) {

                int mc = modCount;

                for (int i = 0; i < tab.length; ++i) {

                    for (Node<K,V> e = tab[i]; e != null; e = e.next)

                        action.accept(e.key);

                }

                if (modCount != mc)

                    throw new ConcurrentModificationException();

            }

        }

    }

 

6.15.2 EntrySet

java.util. HashMap. EntrySet

 

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {

        public final int size()                 { return size; }

        public final void clear()               { HashMap.this.clear(); }

        public final Iterator<Map.Entry<K,V>> iterator() {

            return new EntryIterator();

        }

        public final boolean contains(Object o) {

            if (!(o instanceof Map.Entry))

                return false;

            Map.Entry<?,?> e = (Map.Entry<?,?>) o;

            Object key = e.getKey();

            Node<K,V> candidate = getNode(hash(key), key);

            return candidate != null && candidate.equals(e);

        }

        public final boolean remove(Object o) {

            if (o instanceof Map.Entry) {

                Map.Entry<?,?> e = (Map.Entry<?,?>) o;

                Object key = e.getKey();

                Object value = e.getValue();

                return removeNode(hash(key), key, value, true, true) != null;

            }

            return false;

        }

        public final Spliterator<Map.Entry<K,V>> spliterator() {

            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);

        }

        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {

            Node<K,V>[] tab;

            if (action == null)

                throw new NullPointerException();

            if (size > 0 && (tab = table) != null) {

                int mc = modCount;

                for (int i = 0; i < tab.length; ++i) {

                    for (Node<K,V> e = tab[i]; e != null; e = e.next)

                        action.accept(e);

                }

                if (modCount != mc)

                    throw new ConcurrentModificationException();

            }

        }

}

 

6.15.3 Node

java.util. HashMap. Node

 

static class Node<K,V> implements Map.Entry<K,V> {

        final int hash;

        final K key;

        V value;

        Node<K,V> next;

 

        Node(int hash, K key, V value, Node<K,V> next) {

            this.hash = hash;

            this.key = key;

            this.value = value;

            this.next = next;

        }

 

        public final K getKey()        { return key; }

        public final V getValue()      { return value; }

        public final String toString() { return key + "=" + value; }

 

        public final int hashCode() {

            return Objects.hashCode(key) ^ Objects.hashCode(value);

        }

 

        public final V setValue(V newValue) {

            V oldValue = value;

            value = newValue;

            return oldValue;

        }

 

        public final boolean equals(Object o) {

            if (o == this)

                return true;

            if (o instanceof Map.Entry) {

                Map.Entry<?,?> e = (Map.Entry<?,?>)o;

                if (Objects.equals(key, e.getKey()) &&

                    Objects.equals(value, e.getValue()))

                    return true;

            }

            return false;

        }

    }

 

 

 

 

 

6.15.4 TreeNode

java.util. HashMap. TreeNode

 

 

   static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {

        TreeNode<K,V> parent;  // red-black tree links

        TreeNode<K,V> left;

        TreeNode<K,V> right;

        TreeNode<K,V> prev;    // needed to unlink next upon deletion

        boolean red;

        TreeNode(int hash, K key, V val, Node<K,V> next) {

            super(hash, key, val, next);

        }

 

        /**

         * Returns root of tree containing this node.

         */

        final TreeNode<K,V> root() {

            for (TreeNode<K,V> r = this, p;;) {

                if ((p = r.parent) == null)

                    return r;

                r = p;

            }

        }

 

        /**

         * Ensures that the given root is the first node of its bin.

         */

        static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {

            int n;

            if (root != null && tab != null && (n = tab.length) > 0) {

                int index = (n - 1) & root.hash;

                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];

                if (root != first) {

                    Node<K,V> rn;

                    tab[index] = root;

                    TreeNode<K,V> rp = root.prev;

                    if ((rn = root.next) != null)

                        ((TreeNode<K,V>)rn).prev = rp;

                    if (rp != null)

                        rp.next = rn;

                    if (first != null)

                        first.prev = root;

                    root.next = first;

                    root.prev = null;

                }

                assert checkInvariants(root);

            }

        }

        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {

            TreeNode<K,V> p = this;

            do {

                int ph, dir; K pk;

                TreeNode<K,V> pl = p.left, pr = p.right, q;

                if ((ph = p.hash) > h)

                    p = pl;

                else if (ph < h)

                    p = pr;

                else if ((pk = p.key) == k || (k != null && k.equals(pk)))

                    return p;

                else if (pl == null)

                    p = pr;

                else if (pr == null)

                    p = pl;

                else if ((kc != null ||

                          (kc = comparableClassFor(k)) != null) &&

                         (dir = compareComparables(kc, k, pk)) != 0)

                    p = (dir < 0) ? pl : pr;

                else if ((q = pr.find(h, k, kc)) != null)

                    return q;

                else

                    p = pl;

            } while (p != null);

            return null;

        }

 

        /**

         * Calls find for root node.

         */

        final TreeNode<K,V> getTreeNode(int h, Object k) {

            return ((parent != null) ? root() : this).find(h, k, null);

        }

        static int tieBreakOrder(Object a, Object b) {

            int d;

            if (a == null || b == null ||

                (d = a.getClass().getName().

                 compareTo(b.getClass().getName())) == 0)

                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?

                     -1 : 1);

            return d;

        }

        final void treeify(Node<K,V>[] tab) {

            TreeNode<K,V> root = null;

            for (TreeNode<K,V> x = this, next; x != null; x = next) {

                next = (TreeNode<K,V>)x.next;

                x.left = x.right = null;

                if (root == null) {

                    x.parent = null;

                    x.red = false;

                    root = x;

                }

                else {

                    K k = x.key;

                    int h = x.hash;

                    Class<?> kc = null;

                    for (TreeNode<K,V> p = root;;) {

                        int dir, ph;

                        K pk = p.key;

                        if ((ph = p.hash) > h)

                            dir = -1;

                        else if (ph < h)

                            dir = 1;

                        else if ((kc == null &&

                                  (kc = comparableClassFor(k)) == null) ||

                                 (dir = compareComparables(kc, k, pk)) == 0)

                            dir = tieBreakOrder(k, pk);

 

                        TreeNode<K,V> xp = p;

                        if ((p = (dir <= 0) ? p.left : p.right) == null) {

                            x.parent = xp;

                            if (dir <= 0)

                                xp.left = x;

                            else

                                xp.right = x;

                            root = balanceInsertion(root, x);

                            break;

                        }

                    }

                }

            }

            moveRootToFront(tab, root);

        }

        final Node<K,V> untreeify(HashMap<K,V> map) {

            Node<K,V> hd = null, tl = null;

            for (Node<K,V> q = this; q != null; q = q.next) {

                Node<K,V> p = map.replacementNode(q, null);

                if (tl == null)

                    hd = p;

                else

                    tl.next = p;

                tl = p;

            }

            return hd;

        }

        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,

                                       int h, K k, V v) {

            Class<?> kc = null;

            boolean searched = false;

            TreeNode<K,V> root = (parent != null) ? root() : this;

            for (TreeNode<K,V> p = root;;) {

                int dir, ph; K pk;

                if ((ph = p.hash) > h)

                    dir = -1;

                else if (ph < h)

                    dir = 1;

                else if ((pk = p.key) == k || (k != null && k.equals(pk)))

                    return p;

                else if ((kc == null &&

                          (kc = comparableClassFor(k)) == null) ||

                         (dir = compareComparables(kc, k, pk)) == 0) {

                    if (!searched) {

                        TreeNode<K,V> q, ch;

                        searched = true;

                        if (((ch = p.left) != null &&

                             (q = ch.find(h, k, kc)) != null) ||

                            ((ch = p.right) != null &&

                             (q = ch.find(h, k, kc)) != null))

                            return q;

                    }

                    dir = tieBreakOrder(k, pk);

                }

 

                TreeNode<K,V> xp = p;

                if ((p = (dir <= 0) ? p.left : p.right) == null) {

                    Node<K,V> xpn = xp.next;

                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);

                    if (dir <= 0)

                        xp.left = x;

                    else

                        xp.right = x;

                    xp.next = x;

                    x.parent = x.prev = xp;

                    if (xpn != null)

                        ((TreeNode<K,V>)xpn).prev = x;

                    moveRootToFront(tab, balanceInsertion(root, x));

                    return null;

                }

            }

        }

        final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,

                                  boolean movable) {

            int n;

            if (tab == null || (n = tab.length) == 0)

                return;

            int index = (n - 1) & hash;

            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;

            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;

            if (pred == null)

                tab[index] = first = succ;

            else

                pred.next = succ;

            if (succ != null)

                succ.prev = pred;

            if (first == null)

                return;

            if (root.parent != null)

                root = root.root();

            if (root == null

                || (movable

                    && (root.right == null

                        || (rl = root.left) == null

                        || rl.left == null))) {

                tab[index] = first.untreeify(map);  // too small

                return;

            }

            TreeNode<K,V> p = this, pl = left, pr = right, replacement;

            if (pl != null && pr != null) {

                TreeNode<K,V> s = pr, sl;

                while ((sl = s.left) != null) // find successor

                    s = sl;

                boolean c = s.red; s.red = p.red; p.red = c; // swap colors

                TreeNode<K,V> sr = s.right;

                TreeNode<K,V> pp = p.parent;

                if (s == pr) { // p was s's direct parent

                    p.parent = s;

                    s.right = p;

                }

                else {

                    TreeNode<K,V> sp = s.parent;

                    if ((p.parent = sp) != null) {

                        if (s == sp.left)

                            sp.left = p;

                        else

                            sp.right = p;

                    }

                    if ((s.right = pr) != null)

                        pr.parent = s;

                }

                p.left = null;

                if ((p.right = sr) != null)

                    sr.parent = p;

                if ((s.left = pl) != null)

                    pl.parent = s;

                if ((s.parent = pp) == null)

                    root = s;

                else if (p == pp.left)

                    pp.left = s;

                else

                    pp.right = s;

                if (sr != null)

                    replacement = sr;

                else

                    replacement = p;

            }

            else if (pl != null)

                replacement = pl;

            else if (pr != null)

                replacement = pr;

            else

                replacement = p;

            if (replacement != p) {

                TreeNode<K,V> pp = replacement.parent = p.parent;

                if (pp == null)

                    root = replacement;

                else if (p == pp.left)

                    pp.left = replacement;

                else

                    pp.right = replacement;

                p.left = p.right = p.parent = null;

            }

 

            TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

 

            if (replacement == p) {  // detach

                TreeNode<K,V> pp = p.parent;

                p.parent = null;

                if (pp != null) {

                    if (p == pp.left)

                        pp.left = null;

                    else if (p == pp.right)

                        pp.right = null;

                }

            }

            if (movable)

                moveRootToFront(tab, r);

        }

        final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {

            TreeNode<K,V> b = this;

            // Relink into lo and hi lists, preserving order

            TreeNode<K,V> loHead = null, loTail = null;

            TreeNode<K,V> hiHead = null, hiTail = null;

            int lc = 0, hc = 0;

            for (TreeNode<K,V> e = b, next; e != null; e = next) {

                next = (TreeNode<K,V>)e.next;

                e.next = null;

                if ((e.hash & bit) == 0) {

                    if ((e.prev = loTail) == null)

                        loHead = e;

                    else

                        loTail.next = e;

                    loTail = e;

                    ++lc;

                }

                else {

                    if ((e.prev = hiTail) == null)

                        hiHead = e;

                    else

                        hiTail.next = e;

                    hiTail = e;

                    ++hc;

                }

            }

 

            if (loHead != null) {

                if (lc <= UNTREEIFY_THRESHOLD)

                    tab[index] = loHead.untreeify(map);

                else {

                    tab[index] = loHead;

                    if (hiHead != null) // (else is already treeified)

                        loHead.treeify(tab);

                }

            }

            if (hiHead != null) {

                if (hc <= UNTREEIFY_THRESHOLD)

                    tab[index + bit] = hiHead.untreeify(map);

                else {

                    tab[index + bit] = hiHead;

                    if (loHead != null)

                        hiHead.treeify(tab);

                }

            }

        }

 

        /* ------------------------------------------------------------ */

        // Red-black tree methods, all adapted from CLR

 

        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,

                                              TreeNode<K,V> p) {

            TreeNode<K,V> r, pp, rl;

            if (p != null && (r = p.right) != null) {

                if ((rl = p.right = r.left) != null)

                    rl.parent = p;

                if ((pp = r.parent = p.parent) == null)

                    (root = r).red = false;

                else if (pp.left == p)

                    pp.left = r;

                else

                    pp.right = r;

                r.left = p;

                p.parent = r;

            }

            return root;

        }

 

        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,

                                               TreeNode<K,V> p) {

            TreeNode<K,V> l, pp, lr;

            if (p != null && (l = p.left) != null) {

                if ((lr = p.left = l.right) != null)

                    lr.parent = p;

                if ((pp = l.parent = p.parent) == null)

                    (root = l).red = false;

                else if (pp.right == p)

                    pp.right = l;

                else

                    pp.left = l;

                l.right = p;

                p.parent = l;

            }

            return root;

        }

 

        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,

                                                    TreeNode<K,V> x) {

            x.red = true;

            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {

                if ((xp = x.parent) == null) {

                    x.red = false;

                    return x;

                }

                else if (!xp.red || (xpp = xp.parent) == null)

                    return root;

                if (xp == (xppl = xpp.left)) {

                    if ((xppr = xpp.right) != null && xppr.red) {

                        xppr.red = false;

                        xp.red = false;

                        xpp.red = true;

                        x = xpp;

                    }

                    else {

                        if (x == xp.right) {

                            root = rotateLeft(root, x = xp);

                            xpp = (xp = x.parent) == null ? null : xp.parent;

                        }

                        if (xp != null) {

                            xp.red = false;

                            if (xpp != null) {

                                xpp.red = true;

                                root = rotateRight(root, xpp);

                            }

                        }

                    }

                }

                else {

                    if (xppl != null && xppl.red) {

                        xppl.red = false;

                        xp.red = false;

                        xpp.red = true;

                        x = xpp;

                    }

                    else {

                        if (x == xp.left) {

                            root = rotateRight(root, x = xp);

                            xpp = (xp = x.parent) == null ? null : xp.parent;

                        }

                        if (xp != null) {

                            xp.red = false;

                            if (xpp != null) {

                                xpp.red = true;

                                root = rotateLeft(root, xpp);

                            }

                        }

                    }

                }

            }

        }

 

        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,

                                                   TreeNode<K,V> x) {

            for (TreeNode<K,V> xp, xpl, xpr;;) {

                if (x == null || x == root)

                    return root;

                else if ((xp = x.parent) == null) {

                    x.red = false;

                    return x;

                }

                else if (x.red) {

                    x.red = false;

                    return root;

                }

                else if ((xpl = xp.left) == x) {

                    if ((xpr = xp.right) != null && xpr.red) {

                        xpr.red = false;

                        xp.red = true;

                        root = rotateLeft(root, xp);

                        xpr = (xp = x.parent) == null ? null : xp.right;

                    }

                    if (xpr == null)

                        x = xp;

                    else {

                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;

                        if ((sr == null || !sr.red) &&

                            (sl == null || !sl.red)) {

                            xpr.red = true;

                            x = xp;

                        }

                        else {

                            if (sr == null || !sr.red) {

                                if (sl != null)

                                    sl.red = false;

                                xpr.red = true;

                                root = rotateRight(root, xpr);

                                xpr = (xp = x.parent) == null ?

                                    null : xp.right;

                            }

                            if (xpr != null) {

                                xpr.red = (xp == null) ? false : xp.red;

                                if ((sr = xpr.right) != null)

                                    sr.red = false;

                            }

                            if (xp != null) {

                                xp.red = false;

                                root = rotateLeft(root, xp);

                            }

                            x = root;

                        }

                    }

                }

                else { // symmetric

                    if (xpl != null && xpl.red) {

                        xpl.red = false;

                        xp.red = true;

                        root = rotateRight(root, xp);

                        xpl = (xp = x.parent) == null ? null : xp.left;

                    }

                    if (xpl == null)

                        x = xp;

                    else {

                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;

                        if ((sl == null || !sl.red) &&

                            (sr == null || !sr.red)) {

                            xpl.red = true;

                            x = xp;

                        }

                        else {

                            if (sl == null || !sl.red) {

                                if (sr != null)

                                    sr.red = false;

                                xpl.red = true;

                                root = rotateLeft(root, xpl);

                                xpl = (xp = x.parent) == null ?

                                    null : xp.left;

                            }

                            if (xpl != null) {

                                xpl.red = (xp == null) ? false : xp.red;

                                if ((sl = xpl.left) != null)

                                    sl.red = false;

                            }

                            if (xp != null) {

                                xp.red = false;

                                root = rotateRight(root, xp);

                            }

                            x = root;

                        }

                    }

                }

            }

        }

 

        /**

         * Recursive invariant check

         */

        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {

            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,

                tb = t.prev, tn = (TreeNode<K,V>)t.next;

            if (tb != null && tb.next != t)

                return false;

            if (tn != null && tn.prev != t)

                return false;

            if (tp != null && t != tp.left && t != tp.right)

                return false;

            if (tl != null && (tl.parent != t || tl.hash > t.hash))

                return false;

            if (tr != null && (tr.parent != t || tr.hash < t.hash))

                return false;

            if (t.red && tl != null && tl.red && tr != null && tr.red)

                return false;

            if (tl != null && !checkInvariants(tl))

                return false;

            if (tr != null && !checkInvariants(tr))

                return false;

            return true;

        }

   

6.16 java.util.TreeMap

java.util. TreeMap主要方法

 

public class TreeMap<K,V>

    extends AbstractMap<K,V>

    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

{

    private final Comparator<? super K> comparator;

 

    private transient Entry<K,V> root;

  public V get(Object key) {

        Entry<K,V> p = getEntry(key);

        return (p==null ? null : p.value);

}

    final Entry<K,V> getEntry(Object key) {

        // Offload comparator-based version for sake of performance

        if (comparator != null)

            return getEntryUsingComparator(key);

        if (key == null)

            throw new NullPointerException();

        @SuppressWarnings("unchecked")

            Comparable<? super K> k = (Comparable<? super K>) key;

        Entry<K,V> p = root;

        while (p != null) {

            int cmp = k.compareTo(p.key);

            if (cmp < 0)

                p = p.left;

            else if (cmp > 0)

                p = p.right;

            else

                return p;

        }

        return null;

    }

   final Entry<K,V> getEntryUsingComparator(Object key) {

        @SuppressWarnings("unchecked")

            K k = (K) key;

        Comparator<? super K> cpr = comparator;

        if (cpr != null) {

            Entry<K,V> p = root;

            while (p != null) {

                int cmp = cpr.compare(k, p.key);

                if (cmp < 0)

                    p = p.left;

                else if (cmp > 0)

                    p = p.right;

                else

                    return p;

            }

        }

        return null;

    }

public V put(K key, V value) {

        Entry<K,V> t = root;

        if (t == null) {

            compare(key, key); // type (and possibly null) check

 

            root = new Entry<>(key, value, null);

            size = 1;

            modCount++;

            return null;

        }

        int cmp;

        Entry<K,V> parent;

        // split comparator and comparable paths

        Comparator<? super K> cpr = comparator;

        if (cpr != null) {

            do {

                parent = t;

                cmp = cpr.compare(key, t.key);

                if (cmp < 0)

                    t = t.left;

                else if (cmp > 0)

                    t = t.right;

                else

                    return t.setValue(value);

            } while (t != null);

        }

        else {

            if (key == null)

                throw new NullPointerException();

            @SuppressWarnings("unchecked")

                Comparable<? super K> k = (Comparable<? super K>) key;

            do {

                parent = t;

                cmp = k.compareTo(t.key);

                if (cmp < 0)

                    t = t.left;

                else if (cmp > 0)

                    t = t.right;

                else

                    return t.setValue(value);

            } while (t != null);

        }

        Entry<K,V> e = new Entry<>(key, value, parent);

        if (cmp < 0)

            parent.left = e;

        else

            parent.right = e;

        fixAfterInsertion(e);

        size++;

        modCount++;

        return null;

    }

private void fixAfterInsertion(Entry<K,V> x) {

        x.color = RED;

 

        while (x != null && x != root && x.parent.color == RED) {

            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {

                Entry<K,V> y = rightOf(parentOf(parentOf(x)));

                if (colorOf(y) == RED) {

                    setColor(parentOf(x), BLACK);

                    setColor(y, BLACK);

                    setColor(parentOf(parentOf(x)), RED);

                    x = parentOf(parentOf(x));

                } else {

                    if (x == rightOf(parentOf(x))) {

                        x = parentOf(x);

                        rotateLeft(x);

                    }

                    setColor(parentOf(x), BLACK);

                    setColor(parentOf(parentOf(x)), RED);

                    rotateRight(parentOf(parentOf(x)));

                }

            } else {

                Entry<K,V> y = leftOf(parentOf(parentOf(x)));

                if (colorOf(y) == RED) {

                    setColor(parentOf(x), BLACK);

                    setColor(y, BLACK);

                    setColor(parentOf(parentOf(x)), RED);

                    x = parentOf(parentOf(x));

                } else {

                    if (x == leftOf(parentOf(x))) {

                        x = parentOf(x);

                        rotateRight(x);

                    }

                    setColor(parentOf(x), BLACK);

                    setColor(parentOf(parentOf(x)), RED);

                    rotateLeft(parentOf(parentOf(x)));

                }

            }

        }

        root.color = BLACK;

    }

}

 

6.17 Java.util.Set

Java.util.Set主要方法

 

public interface Set<E> extends Collection<E> {

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] a);

    boolean add(E e);

    boolean remove(Object o);

    boolean containsAll(Collection<?> c);

    boolean addAll(Collection<? extends E> c);

    boolean retainAll(Collection<?> c);

    boolean removeAll(Collection<?> c);

    void clear();

    boolean equals(Object o);

    int hashCode();

    @Override

    default Spliterator<E> spliterator() {

        return Spliterators.spliterator(this, Spliterator.DISTINCT);

    }

}

 

 

 

6.18 java.util. AbstractSet

java.util. AbstractSet主要方法

 

public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {

    public boolean equals(Object o) {

        if (o == this)

            return true;

 

        if (!(o instanceof Set))

            return false;

        Collection<?> c = (Collection<?>) o;

        if (c.size() != size())

            return false;

        try {

            return containsAll(c);

        } catch (ClassCastException unused)   {

            return false;

        } catch (NullPointerException unused) {

            return false;

        }

}

 

  public int hashCode() {

        int h = 0;

        Iterator<E> i = iterator();

        while (i.hasNext()) {

            E obj = i.next();

            if (obj != null)

                h += obj.hashCode();

        }

        return h;

    }

public boolean removeAll(Collection<?> c) {

        Objects.requireNonNull(c);

        boolean modified = false;

 

        if (size() > c.size()) {

            for (Iterator<?> i = c.iterator(); i.hasNext(); )

                modified |= remove(i.next());

        } else {

            for (Iterator<?> i = iterator(); i.hasNext(); ) {

                if (c.contains(i.next())) {

                    i.remove();

                    modified = true;

                }

            }

        }

        return modified;

    }

 

}

 

6.19 java.util. HashSet

java.util. HashSet主要方法

public class HashSet<E>

    extends AbstractSet<E>

    implements Set<E>, Cloneable, java.io.Serializable

{

    static final long serialVersionUID = -5024744406713321676L;

    private transient HashMap<E,Object> map;

    private static final Object PRESENT = new Object();

    public HashSet() {

        map = new HashMap<>();

}

public boolean add(E e) {

        return map.put(e, PRESENT)==null;

}

}

 

6.20 java.util. TreeSet

java.util. TreeSet主要方法

 

public class TreeSet<E> extends AbstractSet<E>

    implements NavigableSet<E>, Cloneable, java.io.Serializable

{

    private transient NavigableMap<E,Object> m;

 

    // Dummy value to associate with an Object in the backing Map

    private static final Object PRESENT = new Object();

    TreeSet(NavigableMap<E,Object> m) {

        this.m = m;

    }

    public TreeSet() {

        this(new TreeMap<E,Object>());

    }

public boolean add(E e) {

        return m.put(e, PRESENT)==null;

    }

}

 

6.21 Java.util. ServiceLoader

Java.util. ServiceLoader主要方法

 

6.22 java.util.concurrent

java.util.concurrent

 

6.22.1 java.util.concurrent. Semaphore

java.util.concurrent. Semaphore

 

public class Semaphore implements java.io.Serializable {

    private static final long serialVersionUID = -3222578661600680210L;

private final Sync sync;

   public void acquire() throws InterruptedException {

        sync.acquireSharedInterruptibly(1);

    }

public void release() {

        sync.releaseShared(1);

 }

}

 

 

6.22.1.1   java.util.concurrent. Semaphore. FairSync

  java.util.concurrent. Semaphore. FairSync

 

  protected int tryAcquireShared(int acquires) {

            for (;;) {

                if (hasQueuedPredecessors())

                    return -1;

                int available = getState();

                int remaining = available - acquires;

                if (remaining < 0 ||

                    compareAndSetState(available, remaining))

                    return remaining;

            }

     }

 

6.22.1.2   java.util.concurrent. Semaphore. NonfairSync

  java.util.concurrent. Semaphore.NonfairSync

 

   final int nonfairTryAcquireShared(int acquires) {

            for (;;) {

                int available = getState();

                int remaining = available - acquires;

                if (remaining < 0 ||

                    compareAndSetState(available, remaining))

                    return remaining;

            }

        }

 

 

6.22.2 java.util.concurrent. CyclicBarrier

java.util.concurrent. CyclicBarrier使用方法

package cn.java.threadmodel;

 

import java.util.concurrent.BrokenBarrierException;

import java.util.concurrent.CyclicBarrier;

 

public class MyCyclicBarrier {

    public static void main(String[] args) {

        final CyclicBarrier cyclicBarrier = new CyclicBarrier(10,()->{

            System.out.println("所有人都准备好了裁判开始了");

        });

        for (int i = 0; i < 10; i++) {

            //lambda中只能只用final的变量

            final int times = i;

            new Thread(() -> {

                try {

                    System.out.println("子线程" +

                            Thread.currentThread().getName() + "正在准备");

                    Thread.sleep(1000 * times);

                    System.out.println("子线程" +

                            Thread.currentThread().getName() + "准备好了");

                    cyclicBarrier.await();

                    System.out.println("子线程" +

                            Thread.currentThread().getName() + "开始跑了");

                } catch (InterruptedException e) {

                    e.printStackTrace();

                } catch (BrokenBarrierException e) {

                    e.printStackTrace();

                }

            }).start();

        }

    }

}

java.util.concurrent. CyclicBarrier使用主要属性

 

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition trip = lock.newCondition();

    /** The number of parties */

    private final int parties;

    private final Runnable barrierCommand;

    private Generation generation = new Generation();

    private int count;

 

public CyclicBarrier(int parties, Runnable barrierAction) {

        if (parties <= 0) throw new IllegalArgumentException();

        this.parties = parties;

        this.count = parties;

        this.barrierCommand = barrierAction;

    }

 

 

java.util.concurrent. CyclicBarrier dowait使用ReentrantLockCondition

 

   private int dowait(boolean timed, long nanos)

        throws InterruptedException, BrokenBarrierException,

               TimeoutException {

        final ReentrantLock lock = this.lock;

        lock.lock();

        try {

            final Generation g = generation;

 

            if (g.broken)

                throw new BrokenBarrierException();

 

            if (Thread.interrupted()) {

                breakBarrier();

                throw new InterruptedException();

            }

 

            int index = --count;

            if (index == 0) {  // tripped

                boolean ranAction = false;

                try {

                    final Runnable command = barrierCommand;

                    if (command != null)

                        command.run();

                    ranAction = true;

                    nextGeneration();

                    return 0;

                } finally {

                    if (!ranAction)

                        breakBarrier();

                }

            }

 

            // loop until tripped, broken, interrupted, or timed out

            for (;;) {

                try {

                    if (!timed)

                        trip.await();

                    else if (nanos > 0L)

                        nanos = trip.awaitNanos(nanos);

                } catch (InterruptedException ie) {

                    if (g == generation && ! g.broken) {

                        breakBarrier();

                        throw ie;

                    } else {

                        // We're about to finish waiting even if we had not

                        // been interrupted, so this interrupt is deemed to

                        // "belong" to subsequent execution.

                        Thread.currentThread().interrupt();

                    }

                }

 

                if (g.broken)

                    throw new BrokenBarrierException();

 

                if (g != generation)

                    return index;

 

                if (timed && nanos <= 0L) {

                    breakBarrier();

                    throw new TimeoutException();

                }

            }

        } finally {

            lock.unlock();

        }

    }

 

6.22.3 java.util.concurrent. CountDownLatch

 

java.util.concurrent. CountDownLatch使用demo

public static void main(String[] args) {

        final CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {

            //lambda中只能只用final的变量

            final int times = i;

            new Thread(() -> {

                try {

                    System.out.println("子线程" + Thread.currentThread().getName() + "正在赶路");

                    Thread.sleep(1000 * times);

                    System.out.println("子线程" + Thread.currentThread().getName() + "到公司了");

                    //调用latchcountDown方法使计数器-1

                    latch.countDown();

                    System.out.println("子线程" + Thread.currentThread().getName() + "开始工作");

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }).start();

        }

 

 

        try {

            System.out.println("门卫等待员工上班中...");

            //主线程阻塞等待计数器归零

            latch.await();

            System.out.println("员工都来了,门卫去休息了");

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

 

java.util.concurrent. CountDownLatch主要属性

 

    private final Sync sync;

    public CountDownLatch(int count) {

        if (count < 0) throw new IllegalArgumentException("count < 0");

        this.sync = new Sync(count);

    }

 

java.util.concurrent. CountDownLatch主要属性CountDownLatchawait方法

 

   public CountDownLatch(int count) {

           public void countDown() {

        sync.releaseShared(1);

}

 

   public void await() throws InterruptedException {

        sync.acquireSharedInterruptibly(1);

    }

 

6.22.4 java.util.concurrent. Executor

java.util.concurrent. Executor

 

6.22.5 java.util.concurrent. Executors

java.util.concurrent. Executors

 

6.22.6 java.util.concurrent. AbstractExecutorService

 

java.util.concurrent. AbstractExecutorService

 

6.22.7 java.util.concurrent. Future

java.util.concurrent. Future

 

6.22.8 java.util.concurrent. ForkJoinTask

java.util.concurrent. ForkJoinTask

 

 

6.22.9 java.util.concurrent. ForkJoinPool

 

java.util.concurrent. ForkJoinPool

 

 

 

6.22.10 java.util.concurrent.locks

java.util.concurrent.locks

 

6.22.10.1 java.util.concurrent.locks.lock

 

java.util.concurrent.locks.lock

 

public interface Lock {

    void lock();

    void lockInterruptibly() throws InterruptedException;

    boolean tryLock();

    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    void unlock();

    Condition newCondition();

}

 

 

6.22.10.2 java.util.concurrent.locks. LockSupport

 

java.util.concurrent.locks. LockSupport

 

public class LockSupport {

    private static final sun.misc.Unsafe UNSAFE;

private LockSupport() {} // Cannot be instantiated.

    public static void park(Object blocker) {

        Thread t = Thread.currentThread();

        setBlocker(t, blocker);

        UNSAFE.park(false, 0L);

        setBlocker(t, null);

    }

  public static void unpark(Thread thread) {

        if (thread != null)

            UNSAFE.unpark(thread);

}

}

 

6.22.10.3 java.util.concurrent.locks. AbstractOwnableSynchronizer

java.util.concurrent.locks. AbstractOwnableSynchronizer exclusiveOwnerThread重入线程

public abstract class AbstractOwnableSynchronizer

    implements java.io.Serializable {

    private static final long serialVersionUID = 3737899427754241961L;

    protected AbstractOwnableSynchronizer() { }

    private transient Thread exclusiveOwnerThread;

    protected final void setExclusiveOwnerThread(Thread thread) {

        exclusiveOwnerThread = thread;

    }

    protected final Thread getExclusiveOwnerThread() {

        return exclusiveOwnerThread;

    }

}

 

6.22.10.4 java.util.concurrent.locks. AbstractQueuedSynchronizer

 

java.util.concurrent.locks. AbstractQueuedSynchronizer

 

public abstract class AbstractQueuedSynchronizer

    extends AbstractOwnableSynchronizer

    implements java.io.Serializable {

    private static final long serialVersionUID = 7373984972572414691L;

protected AbstractQueuedSynchronizer() { }

    private transient volatile Node head;

    private transient volatile Node tail;

 private volatile int state;

   public final void acquire(int arg) {

        if (!tryAcquire(arg) &&

            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))

            selfInterrupt();

}

    final boolean acquireQueued(final Node node, int arg) {

        boolean failed = true;

        try {

            boolean interrupted = false;

            for (;;) {

                final Node p = node.predecessor();

                if (p == head && tryAcquire(arg)) {

                    setHead(node);

                    p.next = null; // help GC

                    failed = false;

                    return interrupted;

                }

                if (shouldParkAfterFailedAcquire(p, node) &&

                    parkAndCheckInterrupt())

                    interrupted = true;

            }

        } finally {

            if (failed)

                cancelAcquire(node);

        }

    }

private Node addWaiter(Node mode) {

        Node node = new Node(Thread.currentThread(), mode);

        // Try the fast path of enq; backup to full enq on failure

        Node pred = tail;

        if (pred != null) {

            node.prev = pred;

            if (compareAndSetTail(pred, node)) {

                pred.next = node;

                return node;

            }

        }

        enq(node);

        return node;

    }

   static void selfInterrupt() {

        Thread.currentThread().interrupt();

    }

 

    public final boolean release(int arg) {

        if (tryRelease(arg)) {

            Node h = head;

            if (h != null && h.waitStatus != 0)

                unparkSuccessor(h);

            return true;

        }

        return false;

    }

private void unparkSuccessor(Node node) {

        int ws = node.waitStatus;

        if (ws < 0)

            compareAndSetWaitStatus(node, ws, 0);

        Node s = node.next;

        if (s == null || s.waitStatus > 0) {

            s = null;

            for (Node t = tail; t != null && t != node; t = t.prev)

                if (t.waitStatus <= 0)

                    s = t;

        }

        if (s != null)

            LockSupport.unpark(s.thread);

 }

}

java.util.concurrent.locks. AbstractQueuedSynchronizer.Node

  static final class Node {

        static final Node SHARED = new Node();

        static final Node EXCLUSIVE = null;

        static final int CANCELLED =  1;

        static final int SIGNAL    = -1;

        static final int CONDITION = -2;

        static final int PROPAGATE = -3;

        volatile int waitStatus;

        volatile Node prev;

        volatile Node next;

        volatile Thread thread;

        Node nextWaiter;

        final boolean isShared() {

            return nextWaiter == SHARED;

        }

        final Node predecessor() throws NullPointerException {

            Node p = prev;

            if (p == null)

                throw new NullPointerException();

            else

                return p;

        }

        Node() {    // Used to establish initial head or SHARED marker

        }

        Node(Thread thread, Node mode) {     // Used by addWaiter

            this.nextWaiter = mode;

            this.thread = thread;

        }

        Node(Thread thread, int waitStatus) { // Used by Condition

            this.waitStatus = waitStatus;

            this.thread = thread;

        }

    }

 

6.22.10.5 java.util.concurrent.locks. ReentrantLock

java.util.concurrent.locks. ReentrantLock 重入锁

 

public class ReentrantLock implements Lock, java.io.Serializable {

    private static final long serialVersionUID = 7373984872572414699L;

    private final Sync sync;

    abstract static class Sync extends AbstractQueuedSynchronizer {

        private static final long serialVersionUID = -5179523762034025860L;

        abstract void lock();

        final boolean nonfairTryAcquire(int acquires) {

            final Thread current = Thread.currentThread();

            int c = getState();

            if (c == 0) {

                if (compareAndSetState(0, acquires)) {

                    setExclusiveOwnerThread(current);

                    return true;

                }

            }

            else if (current == getExclusiveOwnerThread()) {

                int nextc = c + acquires;

                if (nextc < 0) // overflow

                    throw new Error("Maximum lock count exceeded");

                setState(nextc);

                return true;

            }

            return false;

        }

 

        protected final boolean tryRelease(int releases) {

            int c = getState() - releases;

            if (Thread.currentThread() != getExclusiveOwnerThread())

                throw new IllegalMonitorStateException();

            boolean free = false;

            if (c == 0) {

                free = true;

                setExclusiveOwnerThread(null);

            }

            setState(c);

            return free;

        }

}

 

6.22.10.6 java.util.concurrent.locks. Condition

java.util.concurrent.locks. Condition信号监听方法

 

public interface Condition {

    void await() throws InterruptedException;

    void awaitUninterruptibly();

    long awaitNanos(long nanosTimeout) throws InterruptedException;

    boolean await(long time, TimeUnit unit) throws InterruptedException;

    boolean awaitUntil(Date deadline) throws InterruptedException;

    void signal();

    void signalAll();

}

 

6.22.10.7 java.util.concurrent.locks. ReentrantReadWriteLock

java.util.concurrent.locks. ReentrantReadWriteLock 读写锁对象

public class ReentrantReadWriteLock

        implements ReadWriteLock, java.io.Serializable {

    private static final long serialVersionUID = -6992448646407690164L;

    private final ReentrantReadWriteLock.ReadLock readerLock;

    private final ReentrantReadWriteLock.WriteLock writerLock;

    final Sync sync;

    public ReentrantReadWriteLock() {

        this(false);

    }

    public ReentrantReadWriteLock(boolean fair) {

        sync = fair ? new FairSync() : new NonfairSync();

        readerLock = new ReadLock(this);

        writerLock = new WriteLock(this);

 }

}

 

java.util.concurrent.locks. ReentrantReadWriteLock.Sync 读锁方法tryReadLock

final boolean tryReadLock() {

            Thread current = Thread.currentThread();

            for (;;) {

                int c = getState();

                if (exclusiveCount(c) != 0 &&

                    getExclusiveOwnerThread() != current)

                    return false;

                int r = sharedCount(c);

                if (r == MAX_COUNT)

                    throw new Error("Maximum lock count exceeded");

                if (compareAndSetState(c, c + SHARED_UNIT)) {

                    if (r == 0) {

                        firstReader = current;

                        firstReaderHoldCount = 1;

                    } else if (firstReader == current) {

                        firstReaderHoldCount++;

                    } else {

                        HoldCounter rh = cachedHoldCounter;

                        if (rh == null || rh.tid != getThreadId(current))

                            cachedHoldCounter = rh = readHolds.get();

                        else if (rh.count == 0)

                            readHolds.set(rh);

                        rh.count++;

                    }

                    return true;

                }

            }

        }

 

java.util.concurrent.locks. ReentrantReadWriteLock.Sync 写锁方法tryWriteLock

 

  final boolean tryWriteLock() {

            Thread current = Thread.currentThread();

            int c = getState();

            if (c != 0) {

                int w = exclusiveCount(c);

                if (w == 0 || current != getExclusiveOwnerThread())

                    return false;

                if (w == MAX_COUNT)

                    throw new Error("Maximum lock count exceeded");

            }

            if (!compareAndSetState(c, c + 1))

                return false;

            setExclusiveOwnerThread(current);

            return true;

        }

 

6.22.11 java.util.concurrent.atomic

java.util.concurrent.atomic. AtomicReference

 

6.22.11.1 java.util.concurrent.atomic. AtomicInteger

java.util.concurrent.atomic. AtomicInteger

 

public class AtomicInteger extends Number implements java.io.Serializable {

    private static final long serialVersionUID = 6214790243416807050L;

    private static final Unsafe unsafe = Unsafe.getUnsafe();

    private static final long valueOffset;

    static {

        try {

            valueOffset = unsafe.objectFieldOffset

                (AtomicInteger.class.getDeclaredField("value"));

        } catch (Exception ex) { throw new Error(ex); }

    }

 

    private volatile int value;

public final int getAndSet(int newValue) {

        return unsafe.getAndSetInt(this, valueOffset, newValue);

    }

    public final boolean compareAndSet(int expect, int update) {

        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);

    }

}

 

6.22.11.2 java.util.concurrent.atomic. AtomicReference

java.util.concurrent.atomic. AtomicReference

public class AtomicReference<V> implements java.io.Serializable {

    private static final long serialVersionUID = -1848883965231344442L;

 

    private static final Unsafe unsafe = Unsafe.getUnsafe();

    private static final long valueOffset;

    static {

        try {

            valueOffset = unsafe.objectFieldOffset

                (AtomicReference.class.getDeclaredField("value"));

        } catch (Exception ex) { throw new Error(ex); }

    }

    private volatile V value;

    public AtomicReference(V initialValue) {

        value = initialValue;

    }

    public AtomicReference() {

    }

   public final boolean compareAndSet(V expect, V update) {

        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);

    }

    public final boolean weakCompareAndSet(V expect, V update) {

        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);

    }

    @SuppressWarnings("unchecked")

    public final V getAndSet(V newValue) {

        return (V)unsafe.getAndSetObject(this, valueOffset, newValue);

    }

 

}

7.    References

 

Nio

https://blog.csdn.net/goligu/article/details/127008749