Concurrency

https://blog.krecan.net/2013/12/25/completablefutures-why-to-use-async-methods/

https://github.com/spotify/trickle/wiki

akka

jersey

maven

jvm internals

http://blog.jamesdbloom.com/JVMInternals.html

Unsafe

http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
http://howtodoinjava.com/2013/10/19/usage-of-class-sun-misc-unsafe/

Usafe for park thread
http://www.docjar.com/html/api/java/util/concurrent/locks/LockSupport.java.html
http://blog.csdn.net/iter_zc/article/details/40742399

packages

http://www.docjar.com/docs/api/java/util/concurrent/package-index.html
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/locks/ReentrantReadWriteLock.java#ReentrantReadWriteLock

ConcurrentLock

http://ifeve.com/reentrantlock-and-fairness/

spinlock

http://ifeve.com/java_lock_see1/
http://ifeve.com/java_lock_see4/
http://ifeve.com/java_lock_see2/

ReentrantReadWriteLock

it uses ThreadLocal
http://www.docjar.com/html/api/java/util/concurrent/locks/ReentrantReadWriteLock.java.html

source code analysis:
http://ifeve.com/juc-reentrantreadwritelock/

FutureTask implementation

implement a simple Future
https://gist.github.com/KlausBrunner/4110226
http://www.javacirecep.com/concurrency/java-implement-java-non-blocking-futures/

http://www.docjar.com/html/api/java/util/concurrent/FutureTask.java.html

FutureTask source analysis:
http://ifeve.com/futuretask-source/

ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<Boolean> future = new FutureTask<Boolean>(
  new Callable<Boolean>() {
     @Override
     public Boolean call() throws Exception {
          // length computing.
         return result;
     }   
  } 
)  

executor.execute(future);
try {
   boolean r = future.get();
}
F3.png
ListenableFuture, AbstractFuture and SettableFuture in Guava

http://stackoverflow.com/questions/14609778/actual-implementation-of-callable-and-future
http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html

AbstractQueuedSynchronizer

http://www.docjar.com/html/api/java/util/concurrent/locks/AbstractQueuedSynchronizer.java.html

http://gee.cs.oswego.edu/dl/papers/aqs.pdf
http://ifeve.com/introduce-abstractqueuedsynchronizer/

http://ifeve.com/jdk1-8-abstractqueuedsynchronizer/
http://ifeve.com/jdk1-8-abstractqueuedsynchronizer-part2/

http://ifeve.com/java-special-troops-aqs/

源码剖析AQS在几个同步工具类中的使用
http://ifeve.com/abstractqueuedsynchronizer-use/

The j.u.c Synchronizer Framework翻译(二)设计与实现
http://ifeve.com/aqs/
http://ifeve.com/aqs-1/
http://ifeve.com/aqs-2/
http://ifeve.com/aqs-3/

http://stackoverflow.com/questions/9644856/abstractqueuedsynchronizer-in-java-concurrent

how to implement

AbstractQueuedSynchronizer 比较精妙的地方, “尝试”动作都定义为抽象方法,交个各个子类去定义“尝试成功的含义” 而真正的释放则自己实现

1) in your overridden version of tryAcquire()/tryRelease() or tryAcquireShared()/tryReleaseShared(), just manipulate states. (don't call acquire/release….)
“资源是否可以被访问?”这个问题则交给AQS的子类去实现。

2) implement your business domain APIs via acquireShared()/releaseShared(),acquire()/release().
in the business domain APIs, you can based on getState() to call acquireShared()/releaseShared(),acquire()/release()

CyclicBarrier vs CountDownLatch in Java

http://java-latte.blogspot.com/2013/10/cyclicbarrier-vs-countdownlatch-in-java.html

condition vs Guava's monitor with Guard

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html
http://codingjunkie.net/google-guava-synchronization-with-monitor/

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/Monitor.html

BlockingQueue vs TransferQueue

when you use BlockingQueue, you can only put element into queue (and block if queue is full). With TransferQueue, you can also block until other thread receives your element (you must use new transfer method for that). TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll

http://www.concretepage.com/java/jdk7/transferqueue-java-example

all kinds of queues

http://ifeve.com/java-blocking-queue/

phaser

http://javaforu.blogspot.com/2011/08/java-7s-jucphaser-short-tutorial.html

1) When a thread wants to be known to the Phaser they invoke phaser.register() when the thread arrives at the barrier they invoke phaser.arrive()
http://stackoverflow.com/questions/1636194/flexible-countdownlatch/1637030#1637030

final Phaser phaser = new Phaser();

public Runnable getRunnable(){
    return new Runnable(){
        public void run(){
            ..do stuff...
            phaser.arrive();
        }
    };
}
public void doWork(){
    int phase = phaser.getPhase();

    phaser.register(); // register this task prior to execution 
    executor.submit( getRunnable());

    phaser.awaitAdvance(phase);
}

2) If the main thread wants to await for all registered tasks to complete phaser.arriveAndAwaitAdvance().
http://stackoverflow.com/questions/1636194/flexible-countdownlatch/1637030#1637030

final Phaser phaser = new Phaser();

public Runnable getRunnable(){
    return new Runnable(){
        public void run(){
            ..do stuff...
            phaser.arrive();
        }
    };
}
public void doWork(){
    phaser.register();//register self
    for(int i=0 ; i < N; i++){
        phaser.register(); // register this task prior to execution 
        executor.submit( getRunnable());
    }
    phaser.arriveAndAwaitAdvance();
}

3) if all task threads need to start execution at the same time:

http://java.dzone.com/articles/java-7-understanding-phaser

Note: if the task needs to run repeatedly.
http://stackoverflow.com/questions/6830904/java-tutorials-explanations-of-jsr166y-phaser

int getPhase()
getPhase() method can be used for monitoring purposes. Method returns the current phase number.
For first phase it returns 0, for second phase it returns 1 and so on.

int awaitAdvance(int phase). input phase is the expecting phase to be finished/advanced. output is the next phase #.

We can override the onAdvance(int phase, … ) method to control number of phases which we want to execute.
input phase is the current phase number when we enter onAdvance() method i.e. before advancing to next phase.
registeredParties is the current number of registered parties

Everytime before advancing to next phase overriden onAdvance() method is called and returns either true or false.
- If method returns true than phaser is terminated ,or
- If method returns false than phaser continues and can advance to next phase.
http://www.javamadesoeasy.com/2015/03/phaser-in-java_21.html

exchanger

http://www.javamadesoeasy.com/2015/03/exchanger-in-java.html

Guava

http://www.oschina.net/translate/tag/guava
https://publicobject.com/2007/09/series-recap-coding-in-small-with.html

https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained

MiltiSet is not a map<K, Integer> and MultiMap not map<K, Collections<V».

MultiMap<K, V>.asMap() will return a java map<K, Collections<V».

invert is on an existing MultiMap to built a MultiMap
 *  a => [1, 2, 4]
 *  b => [2, 4, 6]
 *  c => [2, 3, 5]

 * inverse maps:
 *  1 => ["a"]
 *  2 => ["a", "b", "c"]
 *  3 => ["c"]
 *  4 => ["a", "b"]
 *  5 => ["c"]
 *  6 => ["b"]
 */

ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create();
        multimap.putAll("b", Ints.asList(2, 4, 6));
        multimap.putAll("a", Ints.asList(4, 2, 1));
        multimap.putAll("c", Ints.asList(2, 5, 3));

        TreeMultimap<Integer, String> inverse = Multimaps.invertFrom(multimap, TreeMultimap.<Integer, String> create());

        System.out.println(inverse);

{1=[a], 2=[a, b, c], 3=[c], 4=[a, b], 5=[c], 6=[b]}
index is on each element of the input collections, such as List, Set. to built a MultiMap.

if you believe your result can be uniq indexed, you should use Maps.uniqueIndex in stead of MultiMaps.index.

ImmutableMap<Integer, String> stringsByIndex = Maps.uniqueIndex(strings, new Function<String, Integer> () {
    public Integer apply(String string) {
      return string.length();
    }
  });

example 1:

ImmutableSet<String> digits = ImmutableSet.of("zero", "one", "two", "three", "four",
  "five", "six", "seven", "eight", "nine");
Function<String, Integer> lengthFunction = new Function<String, Integer>() {
  public Integer apply(String string) {
    return string.length();
  }
};
ImmutableListMultimap<Integer, String> digitsByLength = Multimaps.index(digits, lengthFunction);
/*
 * digitsByLength maps:
 *  3 => {"one", "two", "six"}
 *  4 => {"zero", "four", "five", "nine"}
 *  5 => {"three", "seven", "eight"}
 */

example 2:

 * original list of maps:
 *  [
 *     {
 *          "type": "blog"
 *          "id": "292"
 *          "author": "john"
 *      }
 *     {
 *          "type": "blog"
 *          "id": "293"
 *          "author": "edv"
 *      }
 *     {
 *          "type": "photo"
 *          "id": "297"
 *          "author": "xxx"
 *      }
 *  ]
 * 
 * index:
 *  { "blog":  [
 *            {
 *               "type": "blog"
 *               "id": "292"
 *               "author": "john"
 *             }
 *            {
 *                "type": "blog"
 *                "id": "293"
 *                "author": "edv"
 *            }
 *      ]
 * 
 *    "photo":  [
 *            {
 *                 "type": "photo"
 *                 "id": "297"
 *                 "author": "xxx"
 *            }
 *     ]
 *  }
 */

 */
Map<String, String> map1 = ImmutableMap.of("type", "blog", "id", "292", "author", "john");
        Map<String, String> map2 = ImmutableMap.of("type", "blog", "id", "293", "author", "edv");
        Map<String, String> map3 = ImmutableMap.of("type", "photo", "id", "297", "author", "xxx");

        List<Map<String, String>> listOfMaps = Lists.newArrayList(map1, map2, map3);

        Multimap<String, Map<String, String>> partitionedMap = Multimaps.index(
                listOfMaps,
                new Function<Map<String, String>, String>() {
                    public String apply(final Map<String, String> from) {
                        return from.get("type");
                    }
                });

        System.out.println(partitionedMap.toString());

{blog=[{type=blog, id=292, author=john}, {type=blog, id=293, author=edv}], photo=[{type=photo, id=297, author=xxx}]}
How do I invert a regular java key value map?
Map<String, Integer> x = ...;
TreeMultimap<Integer, String> inverse2 = Multimaps.invertFrom(
                Multimaps.forMap(x),
                TreeMultimap.<Integer, String> create());

like:
TreeMultimap<Integer, String> inverse2 = Multimaps.invertFrom(
                Multimaps.forMap(ImmutableMap.<String, Integer>of("a", 1, "b", 2, "c", 3)),
                TreeMultimap.<Integer, String> create());
{1=[a], 2=[b], 3=[c]}

TreeMultimap<Integer, String> inverse2 = Multimaps.invertFrom(
                Multimaps.forMap(ImmutableMap.<String, Integer>of("a", 1, "b", 2, "c", 1)),
                TreeMultimap.<Integer, String> create());
{1=[a, c], 2=[b]}

Java 7 Concurrency Cookbook

http://ifeve.com/customizing-concurrency-classes-9/

定制并发类(十)实现一个基于优先级的传输队列
http://ifeve.com/customizing-concurrency-classes-11-2/


Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License