Created
July 24, 2016 04:42
-
-
Save killme2008/5db982ecf3153d74c6b114958eb4cd04 to your computer and use it in GitHub Desktop.
高速缓存对自旋锁的影响
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package net.fnil.java8_examples; | |
| import java.util.concurrent.CountDownLatch; | |
| import java.util.concurrent.CyclicBarrier; | |
| import java.util.concurrent.atomic.AtomicInteger; | |
| public class BusyLock { | |
| private int count; | |
| private AtomicInteger state; | |
| private BusyLock() { | |
| this.count = 0; | |
| this.state = new AtomicInteger(0); | |
| } | |
| private void lock() { | |
| while (!state.compareAndSet(0, 1)) | |
| //while (state.get() == 1) | |
| ; | |
| } | |
| private void unlock() { | |
| state.set(0); | |
| } | |
| public void incr() { | |
| lock(); | |
| count = count + 1; | |
| unlock(); | |
| } | |
| public static void runTests(boolean warnUp) throws Exception { | |
| int threads = 50; | |
| int n = 100000; | |
| BusyLock bl = new BusyLock(); | |
| Thread[] ts = new Thread[threads]; | |
| long start = System.nanoTime(); | |
| CyclicBarrier barrier = new CyclicBarrier(threads + 1); | |
| for (int i = 0; i < threads; i++) { | |
| ts[i] = new Thread(new Runnable() { | |
| @Override | |
| public void run() { | |
| try { | |
| barrier.await(); | |
| for (int j = 0; j < n; j++) | |
| bl.incr(); | |
| barrier.await(); | |
| } catch (Exception e) { | |
| } | |
| } | |
| }); | |
| ts[i].start(); | |
| } | |
| barrier.await(); | |
| barrier.await(); | |
| for (Thread t : ts) { | |
| t.join(); | |
| } | |
| long duration = (System.nanoTime() - start) / 1000000; | |
| if (!warnUp) | |
| System.out.println("count= " + bl.count + ",cost:" + duration | |
| + "ms"); | |
| } | |
| public static void main(String[] args) throws Exception { | |
| runTests(true); | |
| runTests(false); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment