jugLviv

Meta


Share on:


Five advanced Java Synchronizers you probably don’t know

juglvivjuglviv
Besides the common synchronize which is based in the lock bit that every Java object has, you have more sophisticated synchronizers in java, such as:
// Define the semaphore to control 3 permits. 
// 3 Threads can acquire the mySemaphore
Semaphore mySemaphore = new Semaphore(3, true);

// 3 threads can execute this line of code. The 4 thread must wait for a release
mySemaphore.acquire();

// .. somewhere in the code a thread releases the mySemaphore,
// and now the next waiting thread can acquire
mySemaphore.release();
// Initializes a countdown starting from 3
CountDownLatch latch = new CountDownLatch(3);

// ... other threads are running...

// Some thread blocks and waits for the latch countdown
// to reach "0"
latch.await();

// ... code, methods, other objects... etc...

// ... at some place the OTHER threads do the countdown,
// decrementing the latch.. when it reachs 0
// the blocked thread with the "await()" follows its way
latch.countDown();
// 3 threads must await before can unblock
CyclicBarrier barrier = new CyclicBarrier(3);

// threads they block here until the 3 is reached
barrier.await();

// after 3 threads in await this code will run!
System.out.println("Thank you to the 3 friends who awaited for me!”);
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html
void runTasks(List<Runnable> tasks) {
// Initialize the phaser, "1" to register self
final Phaser phaser = new Phaser(1);
// create and start threads
for (final Runnable task : tasks) {

// register here
phaser.register();
new Thread() {
public void run() {

// await all creation
phaser.arriveAndAwaitAdvance();
task.run();
}
}.start();
}

// allow threads to start and deregister self
phaser.arriveAndDeregister();
}
// Create the exchanger. 
// We choose String as the data datatype
Exchanger<String> ex = new Exchanger<String>();

//
// .... Somewhere at Thread 1,
//

// I will block until I can send str1 to Thread 2, and receive a value too!
String str1 = "value to send from Thread 1 to Thread 2";
String valueReturnedFromThread2 = ex.exchange(str1);

//
// ... Somewhere at Thread 2,
//

// I will block until I can send str2 to Thread 1
// I will receive a value from Thread 1 too!
String str2 = "value to send to Thread 1 from Thread 2";
String valueReturnedFromThread1 = ex.exchange(str2);

Оригінал тут

juglviv
Author