Saturday, January 7, 2012

Thread Synchronizing in Java Threading

Thread Synchronization

Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

The Producer/Consumer example

To introduce systematically the Java threads synchronization techniques consider the Producer/Consumer example, proposed in http://www.cs.technion.ac.il/~assaf/publications/parjava.doc.gz. We modified this example to facilitate the practical experimentation of the analyzed synchronization ideas.

The example consists of a class MyData0 that stores an integer value and of two threads of the classes Producer and Consumer. The Producer writes in an infinite loop consecutive integer values into the MyData0 object and the Consumer reads in an infinite loop these values. The Producer and Consumer threads are created and initialized in the ProducerConsumerDriver class.

The task is to synchronize the Producer and the Consumer so that the values will not be lost when the Producer performs two consecutive writings, and the values will not be duplicated when the Consumer will performs to consecutive readings.

Consider first the first Version of this example without any synchronization:

public class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;

public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}

public void run() {
for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } } public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } }


Main Program

public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);

p1.start();
c1.start();
}
}

0 comments:

Post a Comment

Tu comentario será moderado la primera vez que lo hagas al igual que si incluyes enlaces. A partir de ahi no ser necesario si usas los mismos datos y mantienes la cordura. No se publicarán insultos, difamaciones o faltas de respeto hacia los lectores y comentaristas de este blog.