This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

A preface

In the world of code, strangeness should always be the most familiar word on the road, because only strangeness can broaden, only strangeness can be more challenging. All right, let’s talk about the good stuff in ThreadLocal: the ++ I thing. I’ve written about I ++ and ++ I through bytecode before, but I didn’t see the ++ I usage scenario in the program, so I encountered it today.

The second code

private void set(ThreadLocal key, Object value) { // We don't use a fast path as with get() because it is at // least as common to use set() to create new  entries as // it is to replace existing ones, in which case, a fast // path would fail more often than not. Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1); for (Entry e = tab[i]; e ! = null; e = tab[i = nextIndex(i, len)]) { ThreadLocal k = e.get(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (! cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }Copy the code

Int sz = ++size; I was surprised, because I’ve been working for years and I haven’t seen ++ I used, and then I ++ and ++ I

I++ is a local variable table to add data to the stack, and then the local variable table +1, and then read the stack data, the stack data is unchanged, if so, the following code is not the final output of 0;

int i = 0; for(int j =0; j<10; j++){ System.out.println(i++); }Copy the code

Then the output is 0, 1, 2… not what I thought, and finally I realized why, because although I read the stack value, the +1 of the local variable table is not useless. The local variable up here is still incremented by 1.

Then we’ll talk about why we use ++size, but there’s actually another benefit to using ++ I in terms of performance, and if you look at the bytecode it’s that ++ I is doing the stack +1 instead of locally changing the table +1 so it’s faster.