Skip to content

[docs]:ThreadLocal添加注释 单行if/while语句添加花括号 增加可读性 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
  •  
  •  
  •  
12 changes: 4 additions & 8 deletions src/java/lang/Integer.java
Original file line number Diff line number Diff line change
Expand Up @@ -1292,8 +1292,7 @@ public static int remainderUnsigned(int dividend, int divisor) {
// Bit twiddling

/**
* The number of bits used to represent an {@code int} value in two's
* complement binary form.
* The number of bits used to represent an {@code int} value in 二进制补码.
*
* @since 1.5
*/
Expand Down Expand Up @@ -1349,11 +1348,7 @@ public static int lowestOneBit(int i) {
}

/**
* Returns the number of zero bits preceding the highest-order
* ("leftmost") one-bit in the two's complement binary representation
* of the specified {@code int} value. Returns 32 if the
* specified value has no one-bits in its two's complement representation,
* in other words if it is equal to zero.
* 入参的二进制补码左边0的数量 如果入参是0那么结果就是32.
*
* <p>Note that this method is closely related to the logarithm base 2.
* For all positive {@code int} values x:
Expand All @@ -1371,8 +1366,9 @@ public static int lowestOneBit(int i) {
*/
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
if (i == 0) {
return 32;
}
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
Expand Down
26 changes: 18 additions & 8 deletions src/java/lang/Thread.java
Original file line number Diff line number Diff line change
Expand Up @@ -383,19 +383,21 @@ private void init(ThreadGroup g, Runnable target, String name,
this.daemon = parent.isDaemon();
// 子线程继承父线程的优先级属性
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
if (security == null || isCCLOverridden(parent.getClass())) {
this.contextClassLoader = parent.getContextClassLoader();
else
} else {
this.contextClassLoader = parent.contextClassLoader;
}
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
// 当父线程的 inheritableThreadLocals 的值不为空时
// 会把 inheritableThreadLocals 里面的值全部传递给子线程
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
if (inheritThreadLocals && parent.inheritableThreadLocals != null) {
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
}
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;

Expand Down Expand Up @@ -667,8 +669,9 @@ public Thread(ThreadGroup group, Runnable target, String name,
*/
public synchronized void start() {
// 如果没有初始化,抛异常
if (threadStatus != 0)
if (threadStatus != 0) {
throw new IllegalThreadStateException();
}

// 将当前线程加入到所在的线程组,记录为活跃线程
group.add(this);
Expand Down Expand Up @@ -844,8 +847,9 @@ public final synchronized void stop(Throwable obj) {
*/
public void interrupt() {
// 如果由别的线程对当前线程发起中断
if (this != Thread.currentThread())
if (this != Thread.currentThread()) {
checkAccess();
}

synchronized (blockerLock) {
Interruptible b = blocker;
Expand Down Expand Up @@ -1243,6 +1247,7 @@ public final void checkAccess() {
*
* @return 该线程的字符串表示
*/
@Override
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
Expand All @@ -1264,8 +1269,9 @@ public String toString() {
*/
@CallerSensitive
public ClassLoader getContextClassLoader() {
if (contextClassLoader == null)
if (contextClassLoader == null) {
return null;
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader.checkClassLoaderPermission(contextClassLoader,
Expand Down Expand Up @@ -1401,8 +1407,9 @@ private static class Caches {
* "enableContextClassLoaderOverride" RuntimePermission is checked.
*/
private static boolean isCCLOverridden(Class<?> cl) {
if (cl == Thread.class)
if (cl == Thread.class) {
return false;
}

processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
Expand All @@ -1423,6 +1430,7 @@ private static boolean isCCLOverridden(Class<?> cl) {
private static boolean auditSubclass(final Class<?> subcl) {
Boolean result = AccessController.doPrivileged(
new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
for (Class<?> cl = subcl;
cl != Thread.class;
Expand Down Expand Up @@ -1486,6 +1494,7 @@ public enum State {

/**
* 运行中的线程
* RUNNABLE_READY调用start方法 RUNNABLE_RUNNING调用run方法
*/
RUNNABLE,

Expand Down Expand Up @@ -1698,8 +1707,9 @@ public int hashCode() {
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
if (obj == this) {
return true;
}

if (obj instanceof WeakClassKey) {
Object referent = get();
Expand Down
1 change: 1 addition & 0 deletions src/java/lang/ThreadGroup.java
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,7 @@ void list(PrintStream out, int indent) {
* @param e the uncaught exception.
* @since JDK1.0
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
Expand Down
30 changes: 21 additions & 9 deletions src/java/lang/ThreadLocal.java
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,9 @@ private ThreadLocalMap(ThreadLocalMap parentMap) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
while (table[h] != null) {
h = nextIndex(h, len);
}
table[h] = c;
size++;
}
Expand Down Expand Up @@ -466,11 +467,16 @@ private void replaceStaleEntry(ThreadLocal<?> key, Object value,
// incremental rehashing due to garbage collector freeing
// up refs in bunches (i.e., whenever the collector runs).
int slotToExpunge = staleSlot;
// 往左找直到遇到空插孔
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
i = prevIndex(i, len)) {
// 如果遇到垃圾值
if (e.get() == null) {
// 垃圾值所在插孔下标记作slotToExpunge
slotToExpunge = i;
}
}

// Find either the key or trailing null slot of run, whichever
// occurs first
Expand All @@ -491,26 +497,29 @@ private void replaceStaleEntry(ThreadLocal<?> key, Object value,
tab[staleSlot] = e;

// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
if (slotToExpunge == staleSlot) {
slotToExpunge = i;
}
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}

// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
if (k == null && slotToExpunge == staleSlot)
if (k == null && slotToExpunge == staleSlot) {
slotToExpunge = i;
}
}

// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);

// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
if (slotToExpunge != staleSlot) {
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
}

/**
Expand Down Expand Up @@ -547,8 +556,9 @@ private int expungeStaleEntry(int staleSlot) {

// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
while (tab[h] != null) {
h = nextIndex(h, len);
}
tab[h] = e;
}
}
Expand Down Expand Up @@ -605,8 +615,9 @@ private void rehash() {
expungeStaleEntries();

// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
if (size >= threshold - threshold / 4) {
resize();
}
}

/**
Expand Down Expand Up @@ -654,8 +665,9 @@ private void expungeStaleEntries() {
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
if (e != null && e.get() == null) {
expungeStaleEntry(j);
}
}
}
}
Expand Down
35 changes: 26 additions & 9 deletions src/java/util/ArrayList.java
Original file line number Diff line number Diff line change
Expand Up @@ -435,8 +435,10 @@ public E remove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0)
// 将elementData数组index+1位置开始拷贝到elementData从index开始的空间
{
System.arraycopy(elementData, index + 1, elementData, index,
numMoved);
}
// 使size-1 ,设置elementData的size位置为空,让GC来清理内存空间
elementData[--size] = null; //便于垃圾回收器回收

Expand Down Expand Up @@ -769,28 +771,33 @@ private class Itr implements Iterator<E> {
int expectedModCount = modCount;//迭代过程不运行修改数组,否则就抛出异常

//是否还有下一个
@Override
public boolean hasNext() {
return cursor != size;
}

//下一个元素
@Override
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//检查数组是否被修改
checkForComodification();// 检查数组是否被修改
int i = cursor;
if (i >= size)
if (i >= size) {
throw new NoSuchElementException();
}
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;//向后移动游标
return (E) elementData[lastRet = i];//设置访问的位置并返回这个值
cursor = i + 1;// 向后移动游标
return (E) elementData[lastRet = i];// 设置访问的位置并返回这个值
}

//删除元素
@Override
public void remove() {
if (lastRet < 0)
if (lastRet < 0) {
throw new IllegalStateException();
}
checkForComodification();//检查数组是否被修改

try {
Expand Down Expand Up @@ -827,8 +834,9 @@ public void forEachRemaining(Consumer<? super E> consumer) {

//检查数组是否被修改
final void checkForComodification() {
if (modCount != expectedModCount)
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}

Expand All @@ -841,34 +849,42 @@ private class ListItr extends Itr implements ListIterator<E> {
cursor = index;
}

@Override
public boolean hasPrevious() {
return cursor != 0;
}

@Override
public int nextIndex() {
return cursor;
}

@Override
public int previousIndex() {
return cursor - 1;
}

@Override
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
if (i < 0) {
throw new NoSuchElementException();
}
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
cursor = i;
return (E) elementData[lastRet = i];
}

@Override
public void set(E e) {
if (lastRet < 0)
if (lastRet < 0) {
throw new IllegalStateException();
}
checkForComodification();

try {
Expand All @@ -878,6 +894,7 @@ public void set(E e) {
}
}

@Override
public void add(E e) {
checkForComodification();

Expand Down
3 changes: 2 additions & 1 deletion src/java/util/HashMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -660,9 +660,10 @@ public void putAll(Map<? extends K, ? extends V> m) {
* @param key 参数key
* @return 如果没有映射到node,返回null,否则返回对应的value
*/
@Override
public V remove(Object key) {
Node<K, V> e;
//根据key来删除node。removeNode方法的具体实现在下面
// 根据key来删除node。removeNode方法的具体实现在下面
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
Expand Down
1 change: 1 addition & 0 deletions src/java/util/HashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ public boolean add(E e) {
* @param o object to be removed from this set, if present
* @return <tt>true</tt> if the set contained the specified element
*/
@Override
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
Expand Down
Loading