21

Java synchronizers

Embed Size (px)

DESCRIPTION

An elimentary thought on java synchronizer primitives.

Citation preview

Page 2: Java synchronizers

Available synchronizers

What is synchronizing

Basic nuts and bolts(in java)

Various synchronizers

Examples

Page 3: Java synchronizers

ReentrantLock (lock, unlock)

Condition (await and signal)

Semaphore (acquire permits and release)

Future (get -<will block initially and auto release once

isDone>)

CyclicBarrier (await – block until a number later

auto release)

CountDownLatch (await and countDown)

What is the similarity in all of these ???

Page 4: Java synchronizers

Similarity

For eg: lock, acquire, get, await almost mean

threads are about to block on a condition

Auto release, release, unlock almost mean a

thread is about to be un-blocked.

Difference

Some synchronizers work with a shared mode

(semaphore) and others work on per thread basis

(lock)

Each synchronizer has a separate state/trigger on

which block and unblock occurs!

Page 5: Java synchronizers

Acquire and release shared resource on

condition

Acquire while (synchronization state does not allow acquire) {

enqueue current thread if not already queued;

possibly block current thread;

}

dequeue current thread if it was queued;

Release update synchronization state;

if (state may permit a blocked thread to acquire)

unblock one or more queued threads;

Atomically

Managing state

Means to block and

un block threads

Means to queue

and de-queue

threads

Page 6: Java synchronizers

Features

Blocking and non-blocking wait

Interruptible wait.

Timed wait

Shared acquires and releases

Exclusive acquire and release

Fair and unfair notification

Means (Basic components needed)

Atomically manage state

Enqueue and de-queue threads

Means to block and un-block

Page 7: Java synchronizers

Atomically managed : Use a hardware

primitive called

compareAndSetState(expected, new)

If the actual value==expected, then assign new

value; else spin.

Means to block and unblock:

LockSupport.park() and LockSupport.unpark()

Enque and de-queue

Non blocked data structures to efficiently

manage threads into and out-of the queue.

Page 8: Java synchronizers

So we need some sort of skeletal framework

which can take care some basic features

using the components

Here comes AbstractQueuedSynchronizer

[AQS] class which encapsulates the gory

details and provides some common functions

related to acquire and release

However it also allows to override some

methods to acquire/release on special

conditions.. (advanced features)

Page 9: Java synchronizers

Yes, All the synchronizers actually adapt a

specialized version of AQS as an inner class

called as Sync. (A beautiful example for Inner

classes)

Synchronizer’s various methods will

ultimately map/call to one Sync class calls.

AQS methods are overriden for different

purposes

Different state to atomically managed

Fair, unfair policies etc.

Page 10: Java synchronizers

tryAcquire

tryRelease

trySharedAcquire

tryReleaseShared

Page 11: Java synchronizers

class Mutex {

class Sync extends

AbstractQueuedSynchronizer {

private static final long serialVersionUID =

1L;

public boolean tryAcquire(int permits) {

return compareAndSetState(0, 1);

}

public boolean tryRelease(int permits) {

setState(0);

return true;

}

}

private final Sync sync = new Sync();

public void lock() {

sync.acquire(0);

}

public void unlock() {

public static void main(String[] args) {

final Mutex mutex = new Mutex();

Runnable r1 = new Runnable() {

public void run() {

mutex.lock();

try {System.out.println("r1");

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

} finally { mutex.unlock();; }

}

};

Runnable r2 = new Runnable() {

public void run() {

mutex.lock();

try { System.out.println("r2");

Thread.sleep(100);

} catch (InterruptedException e)

{e.printStackTrace();

} finally { mutex.unlock(); }

}

};

new Thread(r1).start();

new Thread(r2).start();

First extend

template

Next,

Adapter

Page 12: Java synchronizers

A classic primitive that constitutes the

method for restricting access to shared

resources

Imagine waiting on the yellow line at

Immigration check counters (how haplessly u crib

as u are eager to be called by some one)

Imagine bank tellers

Some may be fair (throughput is less) and

others may be unfair!! But throughput is

more

Page 13: Java synchronizers

Semaphores can be seen as permit holders . Create with initial number of permits

. acquire takes a permit, waiting if necessary

. release adds a permit

. But no actual permits change hands.

. Semaphore just maintains the current count.

Can use for both “locking” and “synchronizing” . With initial permits=1, can serve as a lock

. Useful in buffers, resource controllers

. Use in designs prone to missed signals

. Semaphores “remember” past signals

Page 14: Java synchronizers

class ResourcePool {

FairSemaphore available =new FairSemaphore(N);

Object[] items = ... ;

public Object getItem() throws IE {

available.acquire();

return nextAvailable();

}

public void returnItem(Object x) {

If (unmark(x))

available.release();

}

synchronized Object nextAvailable();

synchronized boolean unmark(Object x);

}

Page 15: Java synchronizers

A latch specifies conditions that once set

never change.

This provides a way to start several threads

and have them wait until a signal is received

from a coordinating thread.

Think of examination hall; while u await for

the START signal!.

Or multi-player game before the whistle

Page 16: Java synchronizers

Execute CountDownLatchDemo.java

Execute SemaphoreTunnel.java

Page 17: Java synchronizers

A barrier offers a common point (called a

barrier point) for a set of threads to wait

for each other before continuing their

execution.

An advantage over countdownlatch

Can be reset and rerun repeatedly

Once the barrier is met we could break the

barrier

Optionally provides Post barrier routine

Kind of split-merge (however merge will need to

wait till all splitters are done!)

Page 18: Java synchronizers

Execute CyclicBarrierDemo.java

Page 19: Java synchronizers

Exchanger simplifies the way of communicating

between threads, that is, by passing a specific

object between two threads. That's why there's

the <V> after the class name.

Instead of using Piped streams for stream-based,

inter-thread communication (where one side

writes and the other reads),

Exchanger relies on a single exchange method

for the transfer of one-off data between

threads.

The Exchanger is not a general replacement for

the piped model, but their usages are similar

Page 20: Java synchronizers

Execute ExchangerDemo.java

Page 21: Java synchronizers