Synchronization

Synchronization


Threads aren't really syncronized... the code threads access are. Synchronization can come in many forms. Back to the Logger example... Most classes I write have at least one constructor that takes a Logger. Which gives the caller the ability to pass a Logger to the object being instantiated so that it can share it with other running objects. So all the classes running in a particular program can log to the same source.

This can present a small problem when dealing with threads. If four threads were all writing to the same logger at the same time, the output to the log would be hard to interpret at the least. One thread would interupt the next and what was streamed out to the console or file would be a garbled mess.

This is why there is synchronization. If the log method is synchronized the the first thread that gets it, locks it and no other thread can use it untill that first thread releases that lock.

There are two ways to implement synchronization...

CREATED 2013-01-08 12:47:08.0

00-19-4B

UPDATED 2013-01-08 13:00:31.0

Synchronizing Methods...


To synchronize a method put the synchronized keyword in front of the return type. In our example the log signature would look like this...

 public synchronized void log(LogLevel, String){  // logging stuff goes here } 

CREATED 2013-01-08 15:45:57.0

00-19-5A

UPDATED 2013-01-08 15:46:12.0

Synchronizing Blocks...


Synchronizing Blocks of code is a smaller scale of syncrhonizing methods, but the same general practive. Simply put a scynchonization block around the code suseptable to the race condition.

 public void log(LogLevel, String){  synchronized{  // code goes here  } } 

CREATED 2013-01-08 15:46:15.0

00-19-5B

UPDATED 2013-01-08 15:46:24.0

DeadLock...


Deadlock

CREATED 2013-01-08 15:54:43.0

00-19-5D

UPDATED 2013-01-16 14:01:30.0


CREATED 2013-01-08 15:00:07.0

00-19-57

UPDATED 2013-01-16 14:01:31.0

Knowledge

L
I
N
K
S

DBID: db.wam

Page Server: Ithica

©2012 Leistware Data Systems

      Hello anonymous