IBM tutorials - illyfrancis/scribble GitHub Wiki

Tech library

Multicore and threads

http://www.ibm.com/developerworks/library/j-nothreads/

Tutorials

Java concurrency

http://www.ibm.com/developerworks/training/kp/j-kp-concurrency/

  • 5 things didn't know about j.u.c part 1
    • TimeUnit
    • CopyOnWriteArrayList
    • BlockingQueue
    • ConcurrentMap
    • SynchronousQueues
  • 5 things... part 2
    • Semaphore for throttling
    • CountDownLatch
    • Executor instead of creating Threads directly
      • Executor exec = getAnExecutorFromSomeplace(); exec.execute(new Runnable() { ... });
      • ExecutorService
        • ExecutorService executor = Executors.newFixedThreadPool(..)
      • Callable and Future
    • ScheduledExecutorService
    • Timeout methods
    • also look at .locks and .atomic package, CyclicBarrier
  • Java concurrency bug patterns for multicore systems
    1. volatile keyword only guarantees that a variable is visible; it does not guarantee atomicity.
    2. simultaneous locking on updated fields (to fix, use private final to ensure the lock object remains unchanged and mutex is guaranteed)
    • read through the example but the gist is the synchronized field is updated with a 'different' instance
    1. java.util.concurrent lock leak
    • i.e. Lock.lock() invocation without unlock() on the same instance causes a lock leak (see below).
    1. performance tuning synchronized blocks (instead, reduce the scope of synch block to be more effective
    2. multi-stage access (where it needs access to multiple resources of which are individually thread safe but in combination or when you use them together they are not. hence need synchronized them)
    3. symmetric lock deadlock (read it again and look for Concurrency in Practice for workaround)
Example - lock leak
private final Lock lock = new ReentrantLock();

public void lockLeak() {
  lock.lock();
  try {
    accessSharedResource(...);
    lock.unlock();
  } catch (Exception e) {}
}

public void accessSharedResource() throws InterruptedException {...}

Instead put the unlock invocation in the finally block.

public void lockLeak() {
  lock.lock();
  try {
    accessSharedResource(...);
  } catch (Exception e) {}
  finally {
    lock.unlock();
  }
}

Actor concurrency

http://www.ibm.com/developerworks/training/kp/j-kp-actorconcurrency/