Multithreaded and Synchronization Terminology This is not the

October 31, 2006 on 12:28 am | In Java |

Multithreaded and Synchronization Terminology This is not the first time that we have run into synchronization terminology. We have already used terms such as synchronization, critical sections, race condition, and locks. We never really explained them, and it is time to step back now and clarify the terminology. Take a simple code statement such as x = x + 1; If two threads execute this statement, we expect the resulting value stored in x to be x+2. Any other value would be incorrect. The problem with this code statement is that it is not executed atomically. After compiling it into the native machine assembler instructions, it is actually broken into a small number of instructions: load x, r5 // load the value of x into register r5add r5, 1 // add 1 to register r5store r5, x // store the value of register r5 into x If two threads execute the above code at roughly the same time, their instruction execution could interleave in a way that would result in x+1 stored as the new value of x instead of x+2. That unfortunate interleaving of thread exe-cution is called a race condition. The solution to this race condition is to guarantee that this block of assembler statements executes atomically. We call that block a critical section. Once a thread enters a critical section, no other thread can enter until the first one leaves. In that case, we say that the two threads are synchronized and that the critical section is mutually exclusive. Because the variable x is accessed by more than a single thread, it is considered shared data. Critical sections always revolve around access to shared data. To guarantee safe access to shared data (and correct execution), we use a synchronized block or a synchronized method. To protect the variable x in x = x+1; we could use one of three options. The first is a synchronized method: class C { private int x; … public synchronized void plusOne() { x = x+1; } } The second option is a synchronized block: class C { private int x; … public void someMethod() { … synchronized (this) { x = x+1; } … } } Page 152
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services

No Comments yet

TrackBack URI

Sorry, the comment form is closed at this time.