Home

markdown notes

Java

table of contents


Multicore Processors

Use Cases for multicore processors

Architecture of multicore processors

Examples of multicore processors

Multi-Threading

Challenges in Multi-threading

Atomic variable

Why to use atomic when we have synchronized and volatile?

Volatile variable

ThreadLocal variable

Considering ThreadLocal and ThreadPools

ThreadLocal and Memory Leak

Mutex

public class SequenceGenerator{
    private int count = 0;
    public int getSequence(){ return count++; }
}

How to implement Mutex?

  1. synchronized method
    public synchronized int getSequence(){ return count++; }
    
  2. synchronized block
    public Object mutex = new Object();
    public int getSequence(){ 
     synchronized(mutex){ return count++; }
    }
    
  3. ReentrantLock
    private ReentrantLock mutex = new ReentrantLock();
    public int getSequence(){
     try{
         mutex.lock();
         return count++;
     }
     finally{
         mutex.unlock();
     }
    }
    
  4. Semaphore with setting limit to 1

Semaphore

used to limit number of concurrent connections to a resource

class SemaphoreTest{
  private Semaphore semaphore;
  public SemaphoreTest(int limit){
      semaphore = new Semaphore(limit);
  }
  // acquire permits or blocks until available
  public boolean getResourceBlocking(){
      return semaphore.acquire();
  }
  // try to acquire permit, returns false if not available instead of blocking
  public boolean getResourceNonBlocking(){
      return semaphore.tryAcquire();
  }
  // releases the lock/permit
  public void releaseResource(){
      semaphore.release();
  }
  // returns available slots
  public int availablePermits(){
      return semaphore.availablePermits();
  }
}

Apache commons has TimedSemaphore which releases all locks after specified timeout.
initialized as new TimedSemaphore(long period, TimeUnit.SECONDS, limit);