LJRTbook_ch1-3

Embed Size (px)

Citation preview

  • 8/9/2019 LJRTbook_ch1-3

    1/91

  • 8/9/2019 LJRTbook_ch1-3

    2/91

  • 8/9/2019 LJRTbook_ch1-3

    3/91

  • 8/9/2019 LJRTbook_ch1-3

    4/91

  • 8/9/2019 LJRTbook_ch1-3

    5/91

  • 8/9/2019 LJRTbook_ch1-3

    6/91

  • 8/9/2019 LJRTbook_ch1-3

    7/91

  • 8/9/2019 LJRTbook_ch1-3

    8/91

  • 8/9/2019 LJRTbook_ch1-3

    9/91

  • 8/9/2019 LJRTbook_ch1-3

    10/91

  • 8/9/2019 LJRTbook_ch1-3

    11/91

  • 8/9/2019 LJRTbook_ch1-3

    12/91

  • 8/9/2019 LJRTbook_ch1-3

    13/91

  • 8/9/2019 LJRTbook_ch1-3

    14/91

  • 8/9/2019 LJRTbook_ch1-3

    15/91

  • 8/9/2019 LJRTbook_ch1-3

    16/91

  • 8/9/2019 LJRTbook_ch1-3

    17/91

  • 8/9/2019 LJRTbook_ch1-3

    18/91

  • 8/9/2019 LJRTbook_ch1-3

    19/91

  • 8/9/2019 LJRTbook_ch1-3

    20/91

  • 8/9/2019 LJRTbook_ch1-3

    21/91

  • 8/9/2019 LJRTbook_ch1-3

    22/91

  • 8/9/2019 LJRTbook_ch1-3

    23/91

  • 8/9/2019 LJRTbook_ch1-3

    24/91

  • 8/9/2019 LJRTbook_ch1-3

    25/91

  • 8/9/2019 LJRTbook_ch1-3

    26/91

  • 8/9/2019 LJRTbook_ch1-3

    27/91

  • 8/9/2019 LJRTbook_ch1-3

    28/91

  • 8/9/2019 LJRTbook_ch1-3

    29/91

  • 8/9/2019 LJRTbook_ch1-3

    30/91

  • 8/9/2019 LJRTbook_ch1-3

    31/91

  • 8/9/2019 LJRTbook_ch1-3

    32/91

  • 8/9/2019 LJRTbook_ch1-3

    33/91

  • 8/9/2019 LJRTbook_ch1-3

    34/91

  • 8/9/2019 LJRTbook_ch1-3

    35/91

  • 8/9/2019 LJRTbook_ch1-3

    36/91

  • 8/9/2019 LJRTbook_ch1-3

    37/91

  • 8/9/2019 LJRTbook_ch1-3

    38/91

  • 8/9/2019 LJRTbook_ch1-3

    39/91

  • 8/9/2019 LJRTbook_ch1-3

    40/91

  • 8/9/2019 LJRTbook_ch1-3

    41/91

  • 8/9/2019 LJRTbook_ch1-3

    42/91

  • 8/9/2019 LJRTbook_ch1-3

    43/91

  • 8/9/2019 LJRTbook_ch1-3

    44/91

  • 8/9/2019 LJRTbook_ch1-3

    45/91

  • 8/9/2019 LJRTbook_ch1-3

    46/91

    Chapter 3 Multi-Threaded Programming

    f the operation of an ind!strial ro)ot is interr!pted )eca!se i t detects a h! an'orker 'ithin its 'orkin ran e, on oin otions ha%e to stop )!t the 'ork-piecesho!ld not )e dropped, 'hich re !ires en ineered e*ception handlin and not

    si pl& ter ination of the thread."till, it is )etter to thro' an Error 'hich is !ch ore likel& to reach the o!ter le%-el of error handlin despite =la &= /or =too )!s&= pro ra ers. Do like in the code e*-a ple a)o%e.

    Aliveness"ince interr!pt is ore of an order to co it s!icide than act!all& interr!ptin , theinterr!pted thread a& contin!e for !i te a 'hile )efore i t is ter inated dead. t isso eti es !sef!l to kno' 'hen the thread reall& has stopped its e*ec!tion. (hat isdone )& callin the isAlive ethod of the thread o)6ect. A li%e thre ad o)6ect is 'hat'e call an active ob9ect .

    Notice th at e%en if a th re ad has te r i nated, the o)6ect as s!ch re a ins /as the re -a ins - ) !t aft er t er inat ion, e%en 'hen isAlive ret ! rns false , i t cannot )e

    )ro! h t )ack to life )& cal lin st art a ai n. (h!s , a thread ob5ect can only be s tar $ted once .

  • 8/9/2019 LJRTbook_ch1-3

    47/91

    Threads

    n practice, in &o!r o'n code if &o! are a'are of the li itations, thread ter inationis not a pro)le . (o specif& a ti e-o!t for 6oinin a thread, there are %ersions of 6oin'ith ti e-o!t ar ! ents.

    Inappropriate thread methodsA on the !sef!l and 'ell desi ned ethods of class Thread , there are also so e=feat!res= that rese )les =)! s= and sho!ld )e a%oided.

    irst there is a ethod destroy 'hich is s!pposed to act!all& interr!pt and kill thethread.

  • 8/9/2019 LJRTbook_ch1-3

    48/91

    Chapter 3 Multi-Threaded Programming

    public class Thread implements Runnable {

    static int MAX_PRIORITY; // Highest possible priority. static int MIN_PRIORITY; // Lowest possible priority. static int NORM_PRIORITY; // Default priority.

    Thread(); // Use run in subclass. Thread(Runnable target); // Use the run of 'target'.

    void start (); // Create thread which calls run. void run () {}; // Work to be defined by subclass. static Thread currentThread ();// Get currently executing thread.

    void setPriority (int pri); // Change the priority to 'pri'. int getPriority(); // Returns this threads priority.

    static void sleep (long t); // Suspend execution at least 't' ms static void yield(); // Reschedule to let others run.

    void interrupt (); // Set interrupt request flag. boolean isInterrupted (); // Check interrupt flag of thread obj. static boolean interrupted (); // Check and clear for current thread.

    boolean isAlive (); // True if started but not dead. void join (); // Waits for this thread to die. void join (long t); // Try to join, but only for 't' ms.}

    Note th at the (hre ad class does not rela te to real ti e. nst ead, the real- ti e clock is, as entioned, o)tained )& callin System.currentTimeMillis();

    'hich ret!rns the %al!e of the real-ti e clock as a long e*pressed in illiseconds.

    (he reader a& cons!lt the DK class doc! enta tion for f!rther infor ation.

    3.2 Resources and mutual exclusion Semaphores"e aphores are of interest as a )asic echanis that is a%aila)le in one for or an-other in all /M operatin s&ste s and real-ti e kernels. n so e ind!strial s&ste s,the onl& a%aila)le echanis is se aphore s, on 'hich other concepts co!ld )e )!ilt.Also historicall&, the se aphore 'as the first /introd!ced )& Di6kstra in 1I G prin-ciple for efficientl& handlin !t!al e*cl!sion and s&nchroni ation , sol%in pro)le ss!ch as the )ank acco!nt transactions descri)ed earlier.

    A Semaphore is a echanis that can )e !sed for i ple entat ion of the f!nda -ental a)stractions sho'n in the pre%io!s chapter. "!ch a echanis re !ires cer-

    tain feat!res fro the operatin or r!n- ti e s&ste , and cannot )e p!rel& i ple-

    &' >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    49/91

    Resources and mutual exclusion Semaphores

    ented in, for instance, a%a 'itho!t help fro nati%e s&ste s calls. (herefore, these aphore methods 'e are a)o!t to introd!ce should be considered as system calls/part of the operatin or r!nti e s&ste 'ith certain properties, not to )e conf!sed

    'ith ordinar& ethods that can )e i ple ented on the a%a le%el.9e a&, on the other hand, )e a)le to i ple ent se aphores in a%a if 'e can !seso e )!ilt- in or nati%e a%a feat!re /s&nchroni ed ethods in this case to acco -

    plish s!spens ion of e*ec! tion !n ti l cer tai n condit ions are f!lfil led. Alter nati%e l&,so e 'a& of i ple entin ato ic ethods co!ld )e a%aila)le /s!ch as nati%e eth -ods for disa)lin and ena)lin interr!pts . An ato ic ethod is a ethod that can-not )e interr!pted )& e*ec!tion of other parts of the soft'are. An&ho', no atter ho' 'e i ple ent se aphore echanis , nati%el& or )!i l t on so e a%a feat!re,'e think of the ethods as ato ic and 'ith properties accordin to the se !el.

    Semaphore methods>ecall that se aphores are the pri ar& echanis in an& s all e )edded s&s-te s, so 'e need se aphore classes that odel the se aphore concept and s!pportscross co pi la tion to nat i%e code. #ink in 'i th nat i%e i p le en tat ions of se aphores as pro%ided in ost real-ti e kernels then per its f!ll efficienc& also'hen special hard'are is !sed. (o this end, let !s first st!d& the concept and thenlook into the i ple entation.

    Core operationsA se aphore is )asicall& a non-ne ati%e inte er-%al!ed co!nter 'i th t 'o ato ic

    ethods and a !e!e for )locked 'ait in threads. (he ethods /'i th ret!rn t&pevoid are

    take ();decre ents the co!nter if it is positi%e, )!t if the co!nter is ero, e*ec!tion of the caller is s!spended and that thread is p!t in so e kind of !e!e 'ait infor the co!nter to )eco e positi%e.

  • 8/9/2019 LJRTbook_ch1-3

    50/91

    Chapter 3 Multi-Threaded Programming

    Supporting timeoutn addition to the core ethods, for con%enience, the follo'in ethod /ret!rn t&pe

    boolean is also defined

    tryTake (long timeout)(he sa e as take , )!t the caller i%es !p takin the se aphore after timeout

    i ll iseconds. f the se aphore 'as taken, true is ret!rned. : ther 'ise falseis ret!rned.

    $sin this ethod re !ires so e care. irst , there is no !arantee that the caller is!n)locked e*actl& after the timeout t i e, i t can )e later /)!t not earlier . (he re-lease t i e a& depend on 'hat other threads that ha%e iss!ed )lockin calls 'i thti eo!ts, the CP$ load, etc. (h!s, the sa e t&pe of pro)le s as 'i th the Thread-.sleep ethod.

    "econdl&, the ret!rned )oolean %al!e !st )e taken care of /'hich is not checked )&

    the co piler in a%a, 6!st like in C CJJ C . f false is ret!rned, perhaps after a lonti e of operation, and not considered d!e to a pro ra in error, shared reso!rcescan )& accident )e accessed 'itho!t !t!al e*cl!sion. (he na e tryTake , instead of o%erloadin on take for instance, is selected to e phasis the characteristics of theoperation.

    inall&, consider if &o!r desi n is ri ht if &o! !se the tryTake operation. t sho!ld )e!sed instead of i ple entin additional ti er threads, )!t not for c&clic pollin of the se aphore %al!e. "o e s&ste s pro%ide a 'a& of pollin the %al!e 'itho!t act! -all& tr&in to take the se aphore. "ince s!ch a ethod easil& co!ld )e is!sed )&!nskilled pro ra ers, s!ch a ethod is not pro%ided here.

    Semaphores in other systems9hen proposed )& Di6kstra, the ori inal na e of the take operation 'as P, fro theD!tch 'ord Passeren, referrin to the sit!ation that the thread 'ants to Pass. (heori inal na e of the i%e operation 'as U, fro Uri6 e%en, referrin to the release/=free- i%in = of the reso!rce. (he na es P and U are still !sed in an& s&ste s to-da&.

    (he ost co on na es for take and i%e are 'ait and si nal, respecti%el&. (hesena es are ore e*pressi%e and relates 'ell to the En lish ter s !sed for railroadse aphores. (he se aphore concept act!all& ori inates fro railroad traffic, 'herethe tracks are the reso!rces. As 'e ' il l see later, 'ai t is not a !sef!l na e for a

    se aphore ethod in a%a since it alread& is a final ethod / 'ith another eaninin class :)6ect.

    #ookin for appropriate na es for the se aphore operations, the )est choice /ac-cordin to the a!thor 'as fo!nd in U*9orks, a a6or >(:" fro 9ind>i%er "&s-te s nc. (hat C-)ased AP contained the f!nctions sem_take an d sem_give , )othtakin a pointer to the se aphore data str!ct!re as an ar ! ent. n o)6ect orientedter s, the ar ! ent is the o)6ect / the so called this pointer na ed as the o)6ect ,sem i s the na e of the class, and the _ )& con%ention corresponds to ethod selec-

    && >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    51/91

    Resources and mutual exclusion Semaphores

    tion in the lo)al na espace in C.

    Correspondin l&, the tryTake ethod is a%aila)le in so e s&ste s, and if not, it canal'a&s )e i ple ented !sin an e*tra /ti er thread. (&picall&, there is one ti er thread ser%in all ti eo!t re !ests.

    Using semaphores(he /ato ic se aphore ethods can )e !sed in different 'a&s to sol%e conc!rrenc&

    pro)le s , or se apho re s can )e !sed to cre ate othe r a)strac tio ns . #et !s th er efor ere%ie' so e eneric sit!ations 'hen se aphores can )e !sed. (o i ll!strate the se-

    !encin and )lockin that takes place 'hen threads call the se aphore ethods,'e !se an $7# /or :7( )ased notation, 'ith so e e*tra s& )ols to e phasi e theconc!rrenc& and )lockin iss!es. i !re +-1 e*plains the notation !sed.

    Signaling(he co!nter contained in the standard t&pe of se aphore, accordin to the descrip-tion a)o%e, is ainl& !sef!l for si nalin . (hat is, 'hen one acti%it& has so e res!ltor reso!rce read& for !se )& so e other acti%it&, the prod!cin thread si nals to thecons! in thread. f the prod!cer si nals /callin give se%eral t i es )efore thecons! er 'aits /callin take , the 3non-ne ati%e inte er-%al!ed co!nter containedin the ordinar& t&pe of co!ntin se aphore res!lts in that take needs to )e called as

    an& t i es as give has )een called. n other 'ords, the co!nter co prises a e o-r& 'hich i plies that si nalin in ad%ance is not for otten. i !re +-F sho's ho' athread (1 si nals to a thread (2; (1 can r!n in ad%ance 'hereas (2 can catch !p'i th ear li er call s of give )! t (2 ne%er r !ns in ad%ance of (1. (hi s t&pe of se aphore is referred to as a counting semaphore .

    "o eti es 'e do not 'ant the si naled thread, (2 in this case, to catch !p 'hengive

    has )een called !l t iple t i es. (hat can )e acco plished )& !sin aboolean

    instead of a co!nter as the state %aria)le of the se aphore. (hat corresponds to theco!nter )ein one )inar& di it , and s!ch a se aphore is therefore !s!all& called abinary semaphore .

    A less !s!al t&pe of se aphore is the multistep semaphore , 'hich is !sef!l 'hen 'e'ant s!ccessi%e calls of take to )e ato ic. or instance, a prod!cin thread si nals'hene%er a )&te of data is p! t in a ) !ffer, ) !t the cons! in thread is readin a!nicode /t 'o )&tes per character strin . 9e then 'ant to call take(2) to onl& et

    200 -01-11 15 05 [email protected] &)

    Figure 3-1 Symbols used for the 1:L- O:T + based but enhanced/ se3uence dia+ gra ms .

    : Executing

    : Potential blocking

    : Blocked Thread

    (active obj.)Semaphore(passive obj.)

  • 8/9/2019 LJRTbook_ch1-3

    52/91

    Chapter 3 Multi-Threaded Programming

    !n)locked 'hen there are t 'o )&tes a%aila)le. :ne can al'a&s sol%e the pro)le'itho!t s!ch a !ltistep feat!re, )!t !sin a !ltistep se aphore can )e ore con-%enient and efficient.

    Mutual exclusion

    Perhaps the ost 'ell-kno'n !sa e of se aphores is for !t!al e*cl!sion. An& of the se aphore t&pes !sed for si nalin can )e !sed for !t!al e*cl!sion, )!t thereare reasons for pro%idin a special mut ual ex clusion semaphore . "!ch a se aphoreis so eti es referred to as a = !te*=. 9e 'ill call it a mute* semaphore . As depictedin i !re +-+, the %er& sa e thread that has called mutex.take() , thereafter ha%ine*cl!si%e access to the shared data , sho!ld call mutex.give() 'hen the critical sec-tion is left. An& one acti%it& not follo'in this protocol, for instanc e )& callin give

    &* >eal-(i e Pro ra in H a a%a- )ased approach

    Figure 3-3 Se3uence diagram showing two threads T! and T'/ using a semaphoremute*/ for mut ually e*clusive access to some shared resource. )n this case

    T! happens to be the first to take the semaphore" resulting in T' being

    blocked while T! is in the critical section.

    take take

    give

    give

    mutexT1 T2

    Figure 3-2 4 threa d T! signa li ng to threa d T' via a coun ting sem ap hore. Th e coun ter

    is assumed to be initiali6ed to 6ero" resulting in the first call of takeblocking its caller. 2or each give " one take can be called without blocking.

    takegive

    take

    signalT1 T2

    give

    give

    take

    take

  • 8/9/2019 LJRTbook_ch1-3

    53/91

    Resources and mutual exclusion Semaphores

    one e*tra ti e )efore take, 'o!ld da a e the 'hole application. (herefore, it is aood idea to ha%e a dedicated !te* se aphore class, in 'hich the take sa%es a ref-

    erence to the c!rrent l& e*ec! tin thread /enterin the cr it ical section and give

    checks that the caller is the sa e thread /lea%in the critical section . :f co!rse, oneco!ld i a ine sit!ations 'hen the !nlockin sho!ld )e taken care of )& another thread, 6!st like a person lockin a roo co!ld hand o%er the ke& o so eone elsethat takes care of !nlockin , )!t that is si pl& not per itted.

    Another )enefit 'ith distin !ishin !te* se aphores fro si nalin ones is to in-for the r!n-ti e s&ste /incl!din the sched!ler of thread e*ec!tion that a call of take eans lockin a reso!rce. (hat infor ation can then )e !sed /as 'e 'ill see inChapter 4 to i pro%e response ti es.

    RendezvousD!rin the 1IG0 s there 'as a de%elop ent to'ards a !nifor s&nchroni at ion

    pri i ti%e cal led rend e %o!s , 'hich is rench an d eans so ethin like = ett in to -ether a t a eetin point=. t ' as in the Ada lan !a e s tandard in 1IG+ that ren -

    de %o!s 'as defined as the eneral s&nchroni ation echanis . 9ith lan !a e s!p- por t for (ask s /acti%e o)6ec ts 'it h )!il t- in ! t!al e*cl !sion th at co !nic ate s&n -chrono!sl& /i.e., !sin rende %o!s , the intention 'as to force conc!rrent real-ti esoft'are to )e 'ritten in s!ch a 'a& that is 'as read& for distri)!tion o%er se%eral

    processors.

  • 8/9/2019 LJRTbook_ch1-3

    54/91

    Chapter 3 Multi-Threaded Programming

    i !re +-4 ill !s t ra tes the rende %o!s concept and ho' to i ple ent i t !sinse aphores. Note that (1 is )locked d!rin s&nchroni ation 'hen onl& (2 accessesthe shared data. (he =s&nc.= inter%al for (2 therefore corresponds to a crit ical sec-

    t ion, and (2 a& not !se the shared data )efore entry.take and a fter exit.give .o r (1 on the other hand, shared da ta a& )e anip! la ted !nt il entry.give is

    called /'hich is to )e directl& follo'ed )& exit.take and after /)lockin ends afterexit.take . (h!s, (1 is so to sa& in the critical section all the ti e, )!t )locked 'henco !nication takes place. "ince interaction 'ith (2 is re !ired )efore (1 can pro-ceed, it is eas& to i a ine sit!ations 'hen the !se of rende %o!s as the onl& eanfor s&nchroni ation ets cl! s&.

    Metaphors for semaphores9ith the se aphore classes a%aila)le, one has to keep in ind 'hen to !se 'hatclass /se aphore !se cases . t is then !sef!l to ha%e so e ental pict!re of ho' the

    different se aphore classes are to )e !sed. "ince se aphores /in real life historical -l& co e fro railroad traffic, a train control e*a ple 'ill )e !sed. Note, ho'e%er,that this has %er& li tt le to do 'i th rai lroad se aphores as s!ch; i t is onl& o!r se aphore classes !sed in a railroad conte*t.

    n i !re +-5 there is a se aphore mutex !sed to ha%in onl& one train at a t i e onthe track for !nloadin /shared reso!rce , and there is a se aphore signal !sed for si nalin the a%aila)ilit& of ite s in the )!ffer )et'een the track for !nloadin andloadin . (he /passi%e )!ffer per it the /acti%e trains to access the ite s indepen -dentl& /as&nchrono!sl& of each other, as lon as the )!ffer is not e pt&. (he one tothe lo'er r i ht , on the other hand, pro%ides no s!ch inter ediate s tora e; )othtrains ha%e to )e there to per it i te s to )e transferred fro one train to another,

    &0 >eal-(i e Pro ra in H a a%a- )ased approach

    Figure 3-5 ,ailroad tracks seen from above" illustratin g semaphore usage. The nameof the semaphores refer to the semaphore figures earlier in this section. TheBuffer is a place for storage" permitting one train to unload and contin +ue before the ne*t train arrives for loading. )n the lower right 6one there isno such buffer or intermediate passive ob9ect/ so loading has to be donedirectly from one train to another" w hich corresponds to the synchronousmechanism of rende6vous.

    Industrial track (resources handled along the line)

    Track for loading

    Track for unloading (incoming trains mutual exclusive)

    Buffer signal

    mutex

    entry exit

    Wagon to wagon zone

  • 8/9/2019 LJRTbook_ch1-3

    55/91

    Resources and mutual exclusion Semaphores

    'hich corresponds to rende %o!s i ple ented )& the se aphores entry and exit .n ore detai l, t rains on the ind!st r ia l t rack ha%e access to reso!rces a lon the

    track )!t 'hen reachin the transfer one it ets )locked !ntil the other train is on

    the ad6acent track. (he train enterin the one for !nloadin /co in fro the track for loadin also has to 'ait !ntil the other train is there.

  • 8/9/2019 LJRTbook_ch1-3

    56/91

    Chapter 3 Multi-Threaded Programming

    (herefore, the defa!lt i ple entation is for the r!n-an&'here /that is, p!re a%a case.(he idea is then to s!pport platfor s pro%idin nati%e se aphores )& proper cross-co pi-lation tools /o!tside the scope of this chapter .

    he Semaphore interfaceAll se aphores pro%ide the ethods i%e, take, and tr&(ake. (hat is e*pressed )& the in-terface "e aphore, 'hich is !sef!l 'hen a se aphore o)6ect is to )e !sed 'itho!t theneed to kno' 'hat t&pe of se aphore it is. (hese ethods are doc! ented as

    public void give ()ncre ents )& 1 the co!nter represented )& this se aphore, and notif& at least

    one, if an&, of the 'aitin threads. 8asicall& this eans e*ec!tin thefollo'in t'o lines,++count; // Or set to true (or 1) in case of a binary semaphore.notify(); // If any threads blocked, release the first in queue.

    atomically /s&nchroni ed, 'ith interr!pts disa)led, or in hard'are, asacco plished in a partic!la r t&pe of s&ste .

    public void take ()Ca!ses the callin thread to )lock !ntil the co!nter that represents thisse aphore o)tains a positi%e %al!e. :n ret!rn the co!nter, na ed co!nt

    )elo', is decre e nted )& 1. 8asica ll& th is eans e*ec! ti nwhile (count

  • 8/9/2019 LJRTbook_ch1-3

    57/91

    Resources and mutual exclusion Semaphores

    BinarySemA "e aphore containin a )oolean fla instead of a co!nter, to s!pportsi nalin in cases 'hen 'aitin threads sho!ld not catch !p 'ith s!ccessi%e

    issed calls of i%e. n the defa!lt a%a i ple entat ion a )oolean is !sed tokeep the state of the se aphore. Nati%e appin s can !se that, or a )it, or aco!nter 'ith a a*i ! %al!e of one as in 'in+2.

    CountingSem8asic t&pe of se aphore containin a co!nter 'hich is incre ented )& one for each call to i%e, and decre ented )& one for each ret!r nin call of take. At&pical si nalin e*a ple !sin this t&pe of se aphore 'as sho'n in i !re +-F.

    MultistepSemCo!ntin se aphore per it t in incre ents and decre ents that are reater than one. $sef!l 'hen t'o /or ore s!ccessi%e calls of take needs to )e done

    'itho!t risk for pree ption in )et'een.MutexSemA "e aphore 'ith special s!pport for mut !al ex cl!sion. irst, thei ple enta tion a& check that the thread callin i%e o'ns the lock /that is,has taken the 7!te*"e . "econdl&, this t&pe of se aphore is re !ired to

    pro%ide so cal led priori t& inhe ri tanc e /see Chapt er 4 as a ean to o)tai n )o!nd ed respon se ti es for hi h pr iori t& th re ads 'hen a lo'-priori t& th read is pree p ted and then star% ed 'hen in a cri tica l sec tion .

    n principle, not considerin real-ti e re !ire ents and ass! in correct pro ra -in , the MultistepSem co!ld )e !sed in all cases /or the CountingSem in al ost all

    cases , )!t pro%idin and !sin s!ita)le a)stractions is %al!a)le in soft'are de%elop-ent. Proposed !sa e

    Declare se aphore a t tr i) ! tes and ar ! ents to )e of t&pe Semaphore , e*cept'hen the code is tailored to a specific t&pe of se aphore.

    n nor al cases, instantiate a MutexSem for !t!al e*cl!sion and a CountingSemfor si nalin .

    n special cases, !se the BinarySem for si nalin 'hen =catchin !p= is not desiredor for si plified reso!rce reser%ation, and !se the MultistepSem for si nalin

    !l t ip le s teps in an a to ic anner or for a to ic reser%ation of ! lt ip le re-so!rces.

    All "e aphore classes are declared final to per it opti al code and appin to na -ti%e se aphores 'hen cross-co pilin to s all e )edded s&ste s.

    Errors and exceptions9hen a )lockin se aphore operation is interr!pted, i t res!lts in SemInterrupted

    )ein th ro'n. 9he n a th re ad calls mutex.give / 'here mutex is an instance of Mu-texSem 'itho!t first ha%in ac !ired it )& callin take , a SemViolation is thro'n.(he caller is not e*pected to catch these, e*cept for properl& sh!t-do'n of the appli-cation, since contin!ed e*ec!tion ost likel& 'ill %iolate reso!rce allocation r!les

    200 -01-11 15 05 [email protected] )1

  • 8/9/2019 LJRTbook_ch1-3

    58/91

    Chapter 3 Multi-Threaded Programming

    and res!lt in conc!rrenc& fa!lts. (herefore, SemInterrupted a nd SemViolation ares!)classes of java.lang.Error . (hat also i%es the )enefit that calls do not ha%e to

    )e s!rro !nde d )& tr&- catch. 9he n there ar e reasons to catch th e , for inst ance ri h t

    )efore th re ad te r i natio n, th at is of co!rse possi)le.

    )' >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    59/91

    Objects providing mutual exclusion Monitors

    3.3 Objects providing mutual exclusion Monitors(he ke& idea 'ith the concept of onitors is to co )ine o)6ect oriented pro ra -

    in 'ith !t!al e*cl!sion. As descri)ed in Chapter 2, an o)6ect 'ith ethods thatare !t!all& e*cl!si%e is called a onitor. Act!all&, the onitor concept as initiall&defined )&

  • 8/9/2019 LJRTbook_ch1-3

    60/91

    Chapter 3 Multi-Threaded Programming

    s!ch a lock a%aila)le in each o)6ect, e%en for the ordinar& onesX (he s&nchroni edke&'ord tells the co piler to enerate code that !ses the lock. (here)&, the pro ra

    ets ore eas& to read and 'rite. or instance, consider the )ank acco!nt in i !re+- .

    Synchronized blocks

    9hile the !se of s&nchroni ed ethods i pro%es reada)ilit& /co pared to the !se of se aphores , a%a also pro%ides a less /co pared to proper !se of onitors str!c-t!red alternati%e for lockin an o)6ect; the synchroni6ed block . 9ithin the )races theo)6ect obj is locked for e*cl!si%e !se

    synchronized(obj) { /* Exclusive access to obj here.. */ }

    :f co!rse, a s&nchroni ed )lock !ses the sa e o)6ect lock as the s&nchroni ed eth -ods of that o)6ect, there)& akin the )lock and the ethods !t!all& e*cl!si%e. As&nchroni ed ethod is e !i%alent to a ethod 'ith the o!ter ost )lock

    { synchronized(this) { /* Method body here. */ } }

    The benefit of language support8oth s&nchroni ed ethods and )locks are %er& con%enient 'hen ret!rnin fro a

    ethod. Co pare this 'i th the !se of se aphores 'hich rese )les the sit!ation'hen the lan !a e co piler does not s!pport s&nchroni ation or conc!rrenc&, like inC CJJ. >et!rnin a %al!e fro a onitor ethod often re !ires the ret!rn %al!e to

    )e decla re d as an addi tional local %aria)le, calle d ans in the follo'in i ple enta -tion of the class Account , not per ittin the acco!nt to )e o%erdra'n

    )& >eal-(i e Pro ra in H a a%a- )ased approach

    Figure 3-6 The bank account class to the left uses a semaphore for locking the ob9ect toaccomplish mutual e*clusion. ;y declaring the methods synchroni6ed" as tothe right" the same thing is achieved but in a simpler and more readablemanner. )n Java" there is an invisible lock in every ob9ect.

    class Account { int balance; Semaphore mutex = new MutexSem();

    void deposit(int amount) { mutex.take();

    balance += amount; mutex.give(); }

    void withdraw(int amount){

    mutex.take();balance -= amount;

    mutex.give(); }

    }

    class Account { int balance;

    synchronized void deposit(int amount) { balance += amount; }

    synchronized void withdraw(int amount) { balance -= amount; }}

  • 8/9/2019 LJRTbook_ch1-3

    61/91

    Objects providing mutual exclusion Monitors

    1: class Account {2: int balance;3: Semaphore mutex = new MutexSem();

    4:5: void deposit(int amount) { // As in implemented above.... }6:7: int withdraw(int amount) {8: int ans = 0;9: mutex.take();10: if (amount > balance) {11: ans = amount - balance;12: balance = 0;13: } else {14: balance -= amount;15: }16: mutex.give();17: return ans;18: }19: }

    8ased on this code, consider the follo'in

  • 8/9/2019 LJRTbook_ch1-3

    62/91

    Chapter 3 Multi-Threaded Programming

    withdraw still 'orks /since ans is !sed onl& )& the 'ithdra' ethod )!t conc!r -rent calls of 'i thdra' can i%e the 'ron res!lt. (his is )eca!se the ' ithdra'

    ethod no lon er is reentrant. or instance, one caller /'ith lo' priorit& locks

    the reso!rce and carries o!t the transaction, 'hile a second thread / 'ith hi h pri -orit& pree pts the first thread )et 'een lines 1 and 1F. 9hen res! in , thefi rs t thread 'i ll ret ! rn the res!l t of the second call and the res!l t of the fi rs ttransaction is lost, that is, if amount>balance .

    7akin a ethod or f!nction reentrant )& onl& !sin local %aria)les /allocated onthe s tack of each thread is s tandard; 'e need to !nders tand that no a t ter if ' e!se a lan !a e s!pportin s&nchroni ed or not. eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    63/91

    Objects providing mutual exclusion Monitors

    onitors 'e et no help fro the co piler as 'hen 'e !se s&nchroni ed ethods toaccess protected attri)!tes. (he lack of s!pport for the (ask a)straction co!ld )econsidered as a deficienc& of a%a, )!t as 'ill )e ar !ed later, the task is not a s!it -

    a)le a)straction for the desi n of o)6ect oriented conc!rrent /or real-ti e s&ste san&'a&.

    Use and misuse of keyword volatile(o f!rther descrie)e the special need for conc!rrent soft'are to )e 'ell-str!ct!redthe follo' in code snippet contains a s&nchroni ed ethod in a thread o)6ect. 8&

    )rea ki n r! le A a)o%e 'e a& sa& th at 'e ha%e one erro r, and there is a risk th at!t!al e*cl!sion 'ill not 'ork, )!t 'hat other pro)le s can res!ltM

    /* * Find five faults , concerning concurrency, in this class. */import I.robot.dest; // Import static robot dest ination class Dest .

    public class PathCoord extends Thread {

    private double x,y ;

    public synchronized int dist () {return Math.sqrt( x*x+y*y );}

    public void int run() { double path = 0.0; // Path coordinate, locally on thread stack. while(!isInterrupted()) { path = Dest.step(path); // Local data and reentrant method.

    x = Dest.fx(path); // Calling one thread-safe method, y = Dest.fy(path); // and calling another one. Dest.nextStep(x,y); // Use x,y and wait for next sample. } }}

  • 8/9/2019 LJRTbook_ch1-3

    64/91

    Chapter 3 Multi-Threaded Programming

    as 'ill )e f!rther entioned 'ithin the s&nchroni ation details )elo'.

    2. E%en if 'e 'o!ld !se sin le precision / float for x and y , there)& a%oidin the pro)le of i te 1 'it ho!t !sin volatile /that decreases perfor ance , and e%enif 'e ne%er et a conte*t s'itch at the critical point /e. ., d!e to the priorities andsched!ler :" !sed )et'een the calls of fx and fy , the res!lt of another threadcallin dist co!ld sti ll )e ' ron or o!tdatedX (he reason is that CP$s toda&

    ake e*tensi%e !se of so called data cashes co prised )& on-chip e or& that is!ch faster to !se than the nor al e*ternal /pri ar& e or&.

  • 8/9/2019 LJRTbook_ch1-3

    65/91

    Objects providing mutual exclusion Monitors

    Synchronization detailsAs 'ith an& set of )asic r!les, there are so e cases 'hen the e*perienced pro ra -

    er for ood reasons, or the )e inner for )ad reasons, a& 'ant to )reak the r!les.8efore doin that , )e a'are of the pre%ios section and the follo'in

    1. As a 'a& of doin an!al perfor ance opti i ation, s all et and set ethods/)elon in to a onitor 'ith other ethods s&nchroni ed are often not declareds&nchroni ed.

  • 8/9/2019 LJRTbook_ch1-3

    66/91

    Chapter 3 Multi-Threaded Programming

    private Object lock = new Object(); // More attributes are declared here ....

    public void methodOne(int x) { synchronized( lock ) { // Attributes are accessed here.... } }}

    (his 'a&, other o)6ects cannot interfere 'ith the s&nchroni ation. A ain, the !n -fort!nate a%a desi n decision to s!pport s&nchroni ed )locks )!t not s&nchro -ni ed classes 'i th appropriate se antics ca!ses e*tra tro!)le 'hen de%elopinrelia)le soft'are. "till, the sit!ation is )etter than in other a6or lan !a es. >e-call this i te 'hen readin a)o!t wait a nd notify )elo'. Another e*a p le 'ill

    )e the non- na ti %e a %a i ple entat io n of se a pho res.+. Do not s&nchroni e on p!) lic a t tr i )! tes. (hat is, if &o! /a ainst the eneral

    !ideline s&nchroni e on an attri)!te like the lock in the pre%io!s i te , that at -tri)!te sho!ld )e pri%ate or final. : ther 'ise, that o)6ect reference a& chan efro one s&nchroni ation point to another, there)& re o%in the s&nchroni ation.#ockin cannot )e ens!red if the look can replaced )& an&one.

    4. Do not re o%e s&nchroni ation )& s!)classin /!nless i t is a final class and &o!reall& kno' 'hat &o! are doin . f a )ase class declares a ethod as s&nchro -ni ed, the s!)class sho!ld do so too. (here is nothin in a%a enforcin s!ch a

    prac ti ce , and &o! i ht 'ant to opt i i e etho ds in a s!)cla ss )& o i tt in s&n -

    chroni ed, )!t the risk for hard- to-find conc!rrenc& errors nor all& is too hi hconsiderin the interpla& )et'een onitor ethods.

    5. f s&nchroni ation is needed )et'een !ltiple onitors, s!ch as interconnected )!ffers , the& of co!rse need an o)6ect in co on to s&nchroni e on. An al te rna -ti%e 'o!ld )e to er e the different onitors to for one onitor ' ith all thef!nctionalit& incl!ded, )!t s!ita)le onitor classes a& )e a%aila)le alread&; 6!stthe si nalin and !t!al e*cl!sion )et 'een the need to )e added. $sin s&n-chroni ed )locks to s&nchroni e on so e shared lock o)6ect /s!ch as one of the

    onitors if that code has )een prepared for it is clearl& prefera)le co pared tore'ritin the application.

    As entioned in the last ite , the need for s&nchroni ation )et'een o)6ects can )ed!e to the need for si nalin /'hich 'e earlier acco plished )& se aphores . 9henan o)6ect has )een locked )& synchronized /for a ethod or a )locks , there can )econditions that need to )e f!lfil led )efore the operations on the shared data can )ef!lfilled. a %a pro%ides the follo'in s!pport for that sit!ation.

    *6 >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    67/91

    Objects providing mutual exclusion Monitors

    Conditions wait and notifyConsider a )!ffer 'ith operations put and get . (o acco plish !t!al e*cl!sion d!r -

    in anip!lation of the )!ffer, those ethods are t&picall& declared s&nchroni ed.

  • 8/9/2019 LJRTbook_ch1-3

    68/91

    Chapter 3 Multi-Threaded Programming

    condition 3ueue , 'here it t&picall& is inserted in priorit& order 'ith the thread'ith the hi hest priorit& first. (he sa%ed conte*t of the )locked threa d,referrin to the stack of the thread and there)& to the state of e*ec!tion, of

    co!rse contains the state of the half ade onitor operation.notify()

    (hreads 'aitin in the condition !e!e 'ill re ain there !ntil notified )&so e other thread, or !ntil a ti eo!t occ!rs as e*plained later. (hreads thatinside the onitor chan e an& data that affects conditions that the threads inthe condition !e!e i ht 'aitin for, sho!ld call notify to wake up one of theblocked threads . f the condition !e!e is e pt&, notif& does nothin . tdepends on the r!nti e s&ste 'hich of the )locked threads that are selectedfor notification, )!t here 'e ass! e the nor al case that it is the first in

    !e!e thread, 'hich in t!rn is the one 'ith the hi hest priorit&.After the thread is notified and read& for e*ec!tion, it has to co pete for CP$

    ti e 'ith all other threads to ad%ance its e*ec!tion point at all. 9hene*ec!tion ad%ances, the thread also has to co pete /a ainX 'ith other threadsfor e*cl!si%e access to the onitor, and if not s!ccessf!l it is )locked and

    placed in the onit or !e! e /in priori t& order 'e ass! e , e%en if not specified )& a% a .

    notifyAll() 4ll the threads in the condition 3ueue are noti fied , and there)& ade read& for e*ec!tion. (he& are then all s!)6ect to sched!lin as e*plained for notify ."ince sched!lin is not part of the a%a specification, and since kno'in 'hatthreads that i ht )e !sin the onitor re !ires lo)al infor ation, therelia)le and porta)le 'a& of notification is to al'a&s call notifyAll instead of notify

    ; the !se ofnotify

    is p!rel& for opti i ation and perfor ance t!nin/to pre%ent e*cessi%e conte*t s'itches that can )e the case 'hen an& threadsfirst are !n)locked and then all )!t one calls wait a ain 'hen the conditiona ain is not f!lfilled .

    Note th at e%en if the co piler lets &o! cal l thes e ethods an&' he re in the pro ra/since the& are p!)lic ethods of class Object , the& onl& 'ork if the callin thr eadfirs t h as locke d th e o)6ect %ia synchronized . :the r'is e, an IllegalMonitor-StateException is thro'n.

    8e a'are of the )i difference )et'een callin wait /i.e., Object.wait and callinsleep /i.e., Thread.sleep fro inside a onitor, that is, fro inside a s&nchroni ed

    ethod or )lock. Callin wait res!lts in other threads )ein per it ted to enter the

    onitor, like te porar& !nlockin to let so e other thread chan e the state of theonitor as desired. Callin sleep eans that the onitor is locked d!rin the sleep

    ti e, and no other threads are allo 'ed to enter d!rin that t i e.

    Basic use of wait and notifyA notified thread is o%ed fro the condition !e!e to the onitor !e!e 'here ithas to co pete 'i th other threads, as decided )& the !nderla&in r!nti e s&ste/here 'e ass! e priorit& ordered !e!es . 9hen the thread holdin the lock onitor

    *' >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    69/91

    Objects providing mutual exclusion Monitors

    lea%es, the first thread in the onitor !e!e is !n)locked /p!t in the read& !e!eand is s!)6ect to CP$ ti e sched!lin . plications No a tter ho' lo' pr iori t& or 'hat :", a th read tha t ot into the on ito r 'ill

    co plete its onitor operation /critical section if i%en CP$ ti e and if not call-in 'ait. 9e sa& there is no resource preemption .5

    D!e to pree ption /that is, e*ec!tion pree ption, not to )e conf!sed 'ith the re-so!rce pree ption , the thread holdin the onitor 'i ll re ain there if hi her

    priori t& th reads are sched!l ed for e*ec !t ion inst ead. (here is nothin sa&in that a thread that has )een notified, 'hich eans i t has

    )ee n in the e*cl !s i%e are al re ad& , is i%en access a ain )efore an& of the ne'l& ar -ri%ed threads in the onitor !e!e. (his depends on the sched!ler, ho'e%er, andis not specified )& a%a.

    (he a6or point no' i s that when a thread is continuing after wait" the conditionthat was waited for still cannot be assumed to actually be fulfilled . As an e*a ple,ass ! e one thread ca llin obj = buffer.fetch() to e t the ne*t o)6ect fro a

    )!ffer, and th at th e )!ffe r t! rned o!t to )e e pt&. A cons! e r th re ad calli n fetchsho!ld of co!rse )e )locked !ntil so e other /prod!cer thread p!ts another o)6ectin the )!ffer )& callin buffer.post(obj) . Correspondin l&, a prod!cer thread call-in post is to )e )locked !ntil the )!ffer is not f!ll. Ass! in the si plest case 'ithonl& one prod!cer and one cons! er, an strai htfor'ard )!t fra ile i ple entation

    5 n the ori inal %ersion of the onitor concept, proposed )& +? 0lasses" with attr ib utes and init ia li 6a tion left out for brevity" im plem enti ng producer+consumer communication via a bound ed buffer based on ja-va.util.ArrayList . The if (...) wait (); makes the buffer fragile@ ad +ditional calls of notify e.g." in other methods/ or additiona l threadscould course the buffering to fail.

    class Producer extends Thread{ public void run()

    {

    prod = source.get(); buffer.post (prod); }}

    class Consumer extends Thread{ public void run()

    { cons = buffer.fetch (); sink.put(cons); }}

    class Buffer{ synchronized void post (Object obj) {

    if (buff.size()==maxSize) wait (); if (buff.isEmpty()) notify (); buff.add(obj); }

    synchronized Object fetch () { if (buff.isEmpty()) wait (); if (buff.size()==maxSize) notify (); buff.remove(buff.size()); }}// This Buffer is badly implemented!

  • 8/9/2019 LJRTbook_ch1-3

    70/91

    Chapter 3 Multi-Threaded Programming

    co!ld )e accordin to i !re +-G. n a ore eneral sett in , ' ith ore threads in-%ol%ed or the )!ffer f!nctionalit& )ein e*tended, the follo'in pro)le s arise /see

    i !re +-F

    1. E%en if the notif&in thread calls notif& onl& 'hen the condition to proceed is :K for the 'ai t in thread, the condition may again not be true when the waiting thread is continuing X Ass! e 'e ha%e one prod!cer P and t 'o cons! ers C1 andC2, !sin the Buffer like C1 tries to fetch an o)6ect, )!t ets )locked on since the )!ffer is e pt&. P posts an o)6ect to the )!ffer, and since the )!ffer 'as e pt& that res!lts in a

    notification of C1 that is o%ed fro the condition !e!e to the onitor !e!e. 8efore C1 is sched!led for e*ec!tion, that is, )efore C1 act!all& enters the e*-

    cl!si%e area, C2 /ha%in a hi her priorit& contin!es /for e*a ple after a sleep

    that 'as co pleted after a clock interr!pt and tries to enter the onitor. f this happens )efore P has left the e*cl!si%e area, )oth C1 and C2 are )lockedin the oni tor !e!e . /C1 a)o!t to contin!e af ter wait , ) !t C2 fi rs t in the

    !e!e d!e to hi her priorit&. 9hen P lea%es the onitor, there are one o)6ect in the )!ffer. C2 enters the e*-

    cl!si%e area, ets the o)6ect, and 'hen lea%in C1 is o%ed to the read& !e!eof the sched!ler and is allo'ed to enter the onitor /o'nin the lock .

    "ince C1 is contin!in after 'ait, accordin to the sho'n i ple enta tion as-s! in that the )!ffer is not e pt&, C1 tries to et the ne*t o)6ect. (here areno s!ch o)6ect, and the )!ffer /and the application fails .

    2. t c an ) e difficult to keep track of what condition other threads are blocked on , or it can )e hard to %erif& correctness or re%ise the code. n the referred )!ffer e*a -

    ple it a& appe ar to )e si ple , )! t does th e )!ffer 'ork correct l& e%en for max-Size e !al to oneM

    f 'e 'o!ld add another ethod awaitEmpty that sho!ld )lock !ntil the )!ffer ise pt& /!sef!l d!rin application sh!tdo'n , or an additional ethod awaitFullthat sho!ld )lock !ntil the )!ffer is f!ll /!sef!l for special handlin of o%erflo's ,'hen and ho' an& ti es sho!ld notify then )e calledM

    t is so eas& to o%erlook so e cases, and act!all& takin care of all cases )& theappropriate lo ic /s!ch as co!nters for threads )locked on this or that conditionleads to !nnecessar& co ple* code that is hard to !nderstand and aintain.

    7emedy 1se notify All instead of notify , and le t o ther threads ree%al!atetheir conditions /ass! in the re ed& for ite 1 is !sed . (he e*ception fro thisr!le is 'hen opti i in for 'ell kno'n and perfor ance critical parts of the ap-

    plica tion.

    Pro ra in in a%a, app lica tion failure t&picall& eans an ArrayOutOfBoundExceptionor a NullPointerException that can )e ca! ht and handled, or at least 'e kno' 'hat and'here it 'ent 'ron . $sin an !nsafe lan !a e s!ch as CJJ, the s&ste can crash /at alater sta e 'itho!t essa es.

    *& >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    71/91

    Objects providing mutual exclusion Monitors

    +.

  • 8/9/2019 LJRTbook_ch1-3

    72/91

    Chapter 3 Multi-Threaded Programming

    n short, as r!les of th! ) for pro ra in

    A Al'a&s !se 'hile in front of 'ait while (!okToProceed) wait ();

    8 nstead of notify() !se notify All();

    C (!ne perfor ance 'hen needed, !sin notify() or condition o)6ects e*plained )elo'.

    Keep i !re +-F in ind 'hen &o! de%elop &o!r onitor ethods.

    Timeout on waiting(here are sit!ations 'hen 'aitin for a condition to )e f!lfilled a& not take orethan a certa in a o!nt of ti e . After that t i e 'e 'ant to e t a t i eo! t. or this

    p! rpose, th ere are t'o %ersions of 'a it accep ti n ti eo! t ar ! e nts

    wait(long timeout)

    (he thread e*ec!tin 'ithin the onitor te poraril& lea%es the onitor,'aitin for a notification as nor al. f notif& is not called 'ithin timeoutilliseconds, 'e i%e !p 'aitin and ret!rn to the caller an&'a&. (he timeout

    is ini ! %al!e; it can )e lon er as an i plication of the act!al sched!linof in%ol%ed threads and the internal ti er. A timeout e !al to ero ise !i%alent to callin 'ait ' itho!t an& timeout ar ! ent. A ne ati%e timeoutres!lts in an IllegalArgumentException .

    wait(long timeout, int nanos)(he sa e as pre%io!s 'ait )!t ' ith the ti eo!t ti e set to

    ** >eal-(i e Pro ra in H a a%a- )ased approach

    2igure >+A Two alterna ti ve implem ent ations of the ;uffer class. +'.)n the left version"all methods always call notifyAll does not need to be last/" possibly result+ing in performance problems. )n the version to the right" robustness and per+

    forma nce sho uld be acceptable.

    class Buffer // Inefficient!!{ synchronized void post (Object obj) { while (buff.size()>=maxSize) { wait (); } buff.add(obj); notifyAll (); }

    synchronized Object fetch () { while (buff.isEmpty()) { wait (); } buff.remove(buff.size()); notifyAll (); }}

    class Buffer // Well done.{ synchronized void post (Object obj) { while (buff.size()>=maxSize) { wait (); } if (buff.isEmpty()) notifyAll (); buff.add(obj); }

    synchronized Object fetch () { while (buff.isEmpty()) { wait (); } if (buff.size()>=maxSize) notifyAll (); buff.remove(buff.size()); }}

  • 8/9/2019 LJRTbook_ch1-3

    73/91

    Objects providing mutual exclusion Monitors

    1000000*timeout+nanos nanoseconds. A ain, this is a ini ! ti e thatdepends on the act!al sched!lin , if the resol!tion of ti e in o!r r!nti es&ste is hi h eno! h.

  • 8/9/2019 LJRTbook_ch1-3

    74/91

    Chapter 3 Multi-Threaded Programming

    dt>timeout after the pre%io!s code fra ent is not s!fficient; conc!rrenc& correct -ness a& re !ire so e ore onitor lo ic to cope 'ith all possi)le interlea%in s, asal'a&s.

    Interrupted waiting9hen a thread that is )locked on wait / 'ith or 'itho!t ti eo!t , or on sleep as de-scri )ed on pa e +G, the )lockin is interr!pted and an InterruptedException isthro'n to the callin thread. (he appropriate handlin of s!ch an interr!pted 'aitis t&picall& kno'n defined in the callin thread o!tside the onitor ethods. eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    75/91

    Objects providing mutual exclusion Monitors

    "o eti es interr!ptin a thread is !sed to act!all& interr!pt a co and or actionin an al ost e*pected 'a&. (hat is, instead of cl!tterin the code 'ith a lot of testsif the operation is to )e a)orted, 'e can let e*ec!tion contin!e !nti l i t reaches a

    )lockin cal l and then !t il i e the th ro 'n RTInterrupted . or instance, a ro)ot per-for in its task accordin to a se !ence of instr!ctions can )e interr!pted )& the op-erator 'ho iss!es another task or si pl& s tops the ro)ot d!e to so e fa!l t. (hethread that handles operator inp!t can then interr!pt the on oin ro)ot 'ork, andsince co p!ters are faster than echanics the 'ork thread 'i ll )e )locked on et-tin a ne' order or on the co pletion of last order. 8& catchin InterruptedExcep-tion and con%ertin i t to an RTInterrupted in 'hate%er onitor it occ!rs, 'e canthen catch the RTInterrupted and ter inate the thread like

    class RobotDuty extends Thread{ public void run()

    { try { while (doWork(Master.nextInstruction())) {}; } catch (RTInterrupted) { Master.workAborted();} // Acknowledge. } // No more work; end of duty!}(er inatin the thread /and creatin a ne' one for the ne*t 'ork l ike in this e*-a ple is con%enient for handlin sessions that ha%e a finite life t i e, s!ch as pro-cessin a )atch recipe in a che ical ind!str&, or carr&in o!t an e-)!siness transac -t ion; the s ta te of the sess ion is kept )& the thread, and )oth the act i%it& and thestate ets ar)a e- collected 'hen the session is finished. n feed)ack control, on theother hand, 'e !s!all& create the threads that e*ec!te d!rin the entire l ifeti e !p -ti e of the s&ste ; the state of the controlled s&ste needs to )e aintained alsoo%er ode chan es and the like, and the control can )e sensiti%e to dela&s d!rincreation of ne' threads.

    More on monitor programming(he follo'in applies to the !se of standard a%a packa es, 'hereas enhanced s!p-

    por t for oni to rs 'il l )e introd!ce d in Chap ter 4.

    Static monitors locking class variables

    E*ec!tin s&nchroni ed code res!lts in the s&nchroni ed ob5ect )ein locked. (hatis, !t!al e*cl!sion is pro%ided for the o)6ect /not the class and conc!rrent accessto different o)6ects of the sa e class is, of co!rse, still per itted.

  • 8/9/2019 LJRTbook_ch1-3

    76/91

    Chapter 3 Multi-Threaded Programming

    synchronized(static_attribute){} )lock. n the sa e 'a&, since a static ethodhas no reference to = this' o)6ect, a static ethod does not pro%ide !t!a l e*cl!sionfor an& non-static ethods.

  • 8/9/2019 LJRTbook_ch1-3

    77/91

    Objects providing mutual exclusion Monitors

    application s!ch that holdsLock is needed.

    Multiple conditions

    (o separate )et'een different conditions, it 'o!ld )e desira)le to ha%e !ltiple con-ditions attached to a onitor o)6ect, instead of the sin le i plicit condition that isassociated 'ith each a%a o)6ect. (he reason is perfor ance; instead of notif&in allthreads 'hen an&thin has chan ed, res!l t in in an& conte*t s'i tches e%en if there is onl& one or a fe' threads that 'ait for that partic!lar chan e. "ince DK1.5there are the packa e java.util.concurrent.locks incl!din interfaces Lock andCondition , and classes i ple entin these interfaces.

  • 8/9/2019 LJRTbook_ch1-3

    78/91

    Chapter 3 Multi-Threaded Programming

    3.4 Message-based communication Mailboxesnstead of the lo'-le%el characteristics of se aphores, the desire to s!pport conc!r -

    renc& in an o)6ect oriented 'a& led to onitors; passi%e o)6ects !sed to i ple entcolla)oration )et'een acti%e o)6ects. n an& cases, ho'e%er, 'e can )enefit froha%in s!ch passi%e o)6ects 'ith additional f!nctionalit& for

    8!fferin:ften threads 'ork in prod!cer- cons! er like sit!ations 'hen trans ittedo)6ects need to )e )!ffered in so e t&pe of !e!e. (hat lets the threads 'ork

    ore as&nchrono!sl& 'ith respect to each other. (hat is, e%en if there areso e te porar& )lockin 'hen postin fetchin o)6ects into fro the !e!e /toacco plish !t!al e*cl!sion d!rin the ass! a)l& short !e!in operations ,a )!ffer o%erall lets the threads operate ore independentl& of each other.

    Acti%it& interaction

    (raditionall&, )efore the e ail era, essa es 'ere sent %ia ail)o*es /passi%eo)6ects pro%idin )!fferin and distri)!ted to the ail)o* of the addressee. f the sender and recei%er are close to each other /like threads in the sa e U7 ,and the sender kno's /has a reference to 'here the recei%er is, the o%erheadof distri)!t ion /cost of the sta p and ail dela& can )e a%oided )& p!ttin the

    essa e directl& in the recei%ers ail)o*. An&ho', e%en if the essa es/trans it ted o)6ects are )!ffered in a passi%e o)6ect /the ail)o* , the ai isto send it to so e other acti%e o)6ect /person , 'hich deser%es special s!pport.

    Distri)!tionf the sender and the recei%er of a essa e are not close to or not a'are of each

    others location, it is desira)le to ha%e so e ail distri)!tion s&ste . E%en if

    the topic of distri)!ted s&ste s is o!tside the scope of this chapter,co !nicatin %ia essa es akes !s prepared for the sit!ation 'hen each

    essa e has to )e sent %ia ordinar& ail; the essa e can look the sa e, onl&the ailin differs. f 'e 'o!ld call t he recei%in acti%e o)6ect directl&, theaddressee 'o!ld need to )e a%aila)le at that partic!lar ti e. (herefore,co !nicatin %ia essa es can )e a ood eneric sol!tion.

    Encaps!lationData protection /!sin private or protected in a%a ens!res encaps!lation of se !ential pro ra s, 'hich eans that o)6ects 'ill )e ens!red to f!nctionindependentl& of each other. or real-ti e pro ra s that is not eno! h; 'hen

    ethods of another o)6ect is called fro a ti e- a'are thread /lookin at the

    clock fre !entl& , the caller 3 i%es !p it=s o'n 'ill and co its itself to perfor i n the inst r!c tion s i%en in the /hidden i ple e nta tion of the cal led

    ethod, 'hich can res!lt in )lockin for a lon ti e.

  • 8/9/2019 LJRTbook_ch1-3

    79/91

    Message-based communication Mailboxes

    ro one point of %ie', a so called ail)o* is nothin )!t a special t&pe of onitor,so 'e do not need an& additional s!pport fro the lan !a e /no ne' ke&'ords likesynchronized 'hich s!pports oni tors . ro another point of %ie' , 'hen the

    a)o%e aspects are i portant, essa e )ased o)6ect interaction can )e considered to )e f!n da e ntal, so let !s st art 'it h so e consideratio ns a)o! t the a)st rac tio n 'edeal 'ith.

    More on object interaction7ethod calls in a lan !a e s&ste pro%idin onl& passi%e o)6ects are )& definition as&nchrono!s t&pe of co !nication. (hat is, passi%e o)6ects 'ork s&nchrono!sl&since the& share the sa e thread of e*ec!tion. n other 'ords, this t&pe of co !ni -cation )et'een o)6ects is s&nchrono!s since the called o)6ect re ains in its 'ell de-fined state d!rin the data transfer.

    D!rin a ethod call, the caller enters the scope of the ethod 'ithin the scope of the called o)6ect, perfor in e*actl& 'hat the ethod states. n a sin le-threadeds&ste this is fine; data access %ia ethods pro%ide encaps!lation and data a)strac -tion. 9hen all o)6ects are e*ec!ted )& the sa e thread, 'e act!all& do not think of an& thread at a ll . Data is t ransferred %ia ar ! ents and ret ! rn %al!es, in )oth di-rections )et'een the o)6ects, 'hich is strai htfor'ard and efficient in sin le-thread -ed applications.

    (o s!pport !l t i- threaded applications, the pro ra in lan !a e co!ld pro%ideacti%e /conc!rrentl& e*ec!tin o)6ects, and odels other than ethod calls for datatransfer )et 'een o)6ects. n fact, 'i thin o)6ect-oriented pro ra in in eneral,

    co !nication )et'een o)6ects are /as in the lan !a e " alltalk often referred toas essa e passin . n a%a, o)6ect interaction ste s fro the traditional /co p!ta -tionall& efficient C CJJ approach 'ith ethod calls 'hich are )asicall& the sa e asf!nction calls in C.

  • 8/9/2019 LJRTbook_ch1-3

    80/91

    Chapter 3 Multi-Threaded Programming

    (h!s, the )!ffer 'e need can )e a onitor. 9e a& co pare 'ith essa es 'ithin!ser interaction packa es s!ch as the A9(. "!ch essa es are called e%ents sincethe& represent an application e%ent, )!t the& are not )!ffered e*cept )efore )ein

    fed into the application. Additionall&, the A9( InputEvent s are t i e-s ta ped sothe raphics classes and the application can react accordin l& to 'hen the e%ent/s!ch as a o!se click occ!rred ph&sicall&, 'hich can )e !ite different fro 'henthe e%ent is processed /in partic!lar on a hea%il& loaded s&ste .

    or instance, ass! e t'o o!se clicks sho!ld )e considered a a do!)le-click if thereis less than 1 s )et'een the , and that the !ser clicks t ' ice ' i th the second click 0.I s after the first. (hen if there is a 0.2 s dela& ri ht after processin re isterinthe first click, the second click 'ill )e processed 1.1 s after the first one. $sin theti e-sta ps it can still )e ded!ced that the !ser act!all& do!)le-clicked.

    "i ilar sit!ations appear in feed)ack control 'here the dela& /difference )et'een

    c!rrent t i e and e%ent t i e res!lts is so called phase la , 'hich in t!rn res!lts in )ad da p in or e%en inst a)i li t&. "ince o!r ai is )oth conc!r re nt and real+time pro-ra in , t i e-sta pin o!r essa es /at the t i e of creation ' il l al 'a&s )e

    done.

    Events as messages(he e ission of an e%ent o)6ect denotes so e e*plicit chan e in state or e*ec!tion of an application. "ince the DK1.0 there is the class java.awt.Event 'hich 'as !sedas the )ase class for all the e%ents in the old A9(1.0 contain ent- )ased e%ent od-el. (hat odel 'as to a lar e e*tent i ple ented )& inheritance. t 'as con%enient'hen pro ra in s all applets, )!t did not scale !p at all to lar er application

    'hich i plied e*tensi%e tra%ersals of the contain ent hierarch& for each e%ent/s!ch as a o!se click . (he java.awt.Event is kept onl& for )ack'ard co pati)ilit&and sho!ld not )e !sed.

    "ince DK1.1, the so called dele ation-)ased e%ent odel is !sed, )oth in the A9(/ java.awt as 'ell as in " 'in / C; javax.swing and a%a 8eans /java.beans .(he )ase class for e%ents in all these packa es is the /packa e and application areane! t ra l java.util.EventObject . (he dele ation odel eans that e%ent handlersre ister the sel%es as listeners /s&nchrono!s s!)scri)ers to certain e%ents, and thee itter of the e%ents calls so e e%ent-processin ethod accordin to the interfacefor that partic!lar t&pe of e%ent. or instance, clickin 'ith the o!se on a )!ttonin the B$ /Braphical $ser nterface res!lts in an InputEvent in to the a%a B$

    pack a e /e. . A9( 'her e the associa te d java.awt.Button o)6ect calls the ethodactionPerformed(event) of the e%ent listeners that i ple ent the ActionListenerinterface and ha%e )een re is tered %ia the Button.addActionListener(listener)

    ethod.

    or pro ra in of e )edded s&ste s in eneral 'e sho!ld of co!rse not dependon an& raphics-related packa es or classes /since e )edded processors !s!all& donot pro%ide a B$ , and the& are s!)6ect to restrictions on a%aila)le e or& for thecore operation of the s&ste . /Co pare 'ith #in!* 'hich is %er& s all 'itho!t the

    ,& >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    81/91

    Message-based communication Mailboxes

    raphics, co pared to a f!l l installation ' ith ' indo' ana ers and the l ike. 9e'ill, ho'e%er, ake !se of the dele ation-)ased e%ent odel; &o! s!)scri)e on thee%ents &o! 'ant to recei%e so the sender does not ha%e to perfor an& ass distri-

    )! tion 'hich 'o!ld )e a 'aste of reso! rces .n the packa es entioned a)o%e, e ittin an e%ent is !s!all& referred to as firin

    it. (o fire an e%ent 'i ll )e referred to as synchronously calling the event lis teners ,'hereas to post an e%ent ' il l )e referred to as a synchronously buf fer the event for later processing )& the recei%in thread. (his a rees, altho! h not stated e*plicitl&,'ith con%entions !sed in %ario!s raphics packa es, e%en if postin is nor all& han -dled internall& and the !ser code is ass! ed to process each fired e%ent in a sin le-threaded anner /to i pro%e perfor ance and to red!ce co ple*it& conc!rrenc& .(hat re !ires that all l isteners can process their e%ents instantl&, other' ise the en-tire B$ 'o!ld =free e= d!rin that period of processin or 'aitin . or the sit!ation'hen 'aitin act!all& ha%e to )e done, for instance 'aitin for a do'nload of a fileto )e co pleted after a do'nload )!t ton has )een p!shed, conc!rrent B$ -)ased

    processin can )e re ! es ted and ana e d %ia the javax.swing.SwingUtilitiesand javax.swing.Timer classes. n SwingUtilities , &o! ha%e to !se the ethodsinvokeLater a nd invokeAndWait , 'hich take a Runnable ar ! ent . (hat Runnableis r!n conc!rrentl& ' ith the )!i lt- in B$ e%ent- dispatchin thread, )!t in s!ch a'a& that i t does not interfere 'i th the s 'in A9( and the !ser=s e%ent processincode, 'hich concernin the B$ ainl& sta&s sin le-threa ded.

    n !l t i- threaded pro ra in threads need to operate as&nchrono!sl& /altho! hs&nchroni in 'hen accessin shared data , so the e ittin thread needs to po st thee%ents essa es to so e )!fferin o)6ect 'here the recei%in thread can fetc h the

    e%ents essa es.or threads r!nnin in different %irt!al /or ph&sical achines, sendin a essa e

    fro one thread to another cannot )e acco plished )& si pl& passin a reference toan e%ent o)6ect )et'een the threads. >ecall that o)6ect references / 'hich are point -ers 'ithin the address space of the :"-process ha%e a eanin onl& 'ithin the pro-

    ra . or !lti-threaded pro ra s / 'ithin one U7 :"-process on the other hand,'e can )!i ld !pon the EventObject class entioned a)o%e. (o prepare for real-ti e

    pro ra in , ho'e%er , 'e need a ne' )ase class 'ith so e addi tion s for real+timee%ent o)6ects.

    Real-Time Events RTEvent(he class se.lth.cs.realtime.event. RTEvent i s the EventObject )ase class for real- t i e e%ents. >eal- ti e here )asical l& eans that e%ents are time+stamped ,'hereas tr!e real-t i e properties ha%e to do ' ith the properties of the e*ec!tinthreads and their sched!lin .

  • 8/9/2019 LJRTbook_ch1-3

    82/91

    Chapter 3 Multi-Threaded Programming

    E%er&RTEvent co es fro a so!rce o)6ect referred to in the EventObject )ase class.Additional Ds, s!ch as se !ential n! )ers or the kind of e%ent 'i thin a certaint&pe, are e*pected to )e defined in s!)classes to ether ' ith other !ser attri)!tes.

    (he ti e sta p is, ho'e%er, f!nda ental to real-ti e s&ste s as a ean to denotethe freshness of the data . t is therefore an a t tr i )! te here and the oti%at ion for this class.

    (he source at tri)!te, t&picall& )ein a thread o)6ect, is not s!pposed to keep an&reference to the e%ent after postin it. (herefore, ethods of this class sho!ld notneed to )e s&nchroni ed. (o s!pport detection of kept references, for instance 'henthe e%ent is sent a ain , there is a fie ld owner 'hich is set to the sa e as source'hen the e%ent is created. 9hen an e%ent is transferred, for instance %ia a )!ffer,the o'nership chan es to the )!ffer and then to the recei%in thread. $sin a%ail -a)le classes, the !ser sho!ld not need to care a)o!t the o'nership, i t is checked todetect certain pro ra in errors. "o eti es, ho'e%er, it is desira)le to keep a setof e%ent o)6ects that are sent se%eral t i es, for instance e%er& ti e a certain statetransition occ!rs. n s!ch cases the specific e%ent s!)classes are s!pposed to set the/protected o'ner field to null , 'hich disa)les the checkin of o'nership.

    >efer to the online class doc! entation for f!rther details. n short, ne lectin a fe'feat!res for later chapters, the se.lth.cs.realtime.RTEvent class looks as

    public abstractclass RTEvent extends EventObject {

    protected long timestamp; // Creation time in ms. protected volatile transient Object owner; // Responsible thread.

    public RTEvent (); // Use current Thread & TimeMillis. public RTEvent(Object source); // Set source, default timestamp. public RTEvent(long ts); // Set timestamp, default source public RTEvent(Object source, long ts); // Override both defaults.

    public final Object getOwner() public double getSeconds() public long getMillis ()

    public long getNanos()}(here is also a setOwner ethod, )!t that ethod is declared final and has pack-

    a e %isi)ilit& so it is of no interest for !ser code. "till, the !ser can in RTEvent s!)-classes freel& odif& )oth the timestamp and owner at tri)!tes. or instance, ownercan )e set to n!ll, and the timestamp can )e odified accordin to an i pro%ed esti-

    ation of a sa pled inp!t data %al!e. (he o'ner does not need to )e a thread o)- 6ect, 'hich is !sef!l 'hen , e. ., re ! la tor o)6ects in a control s&s te are dr i%en )&so e e*ternal thread; the e%ent- e it t in /)!t passi%e fro a a%a point of %ie'control )lock can still )e the re istered o'ner F of the o)6ect.

    F (he concept of o'nership is taken fro the :"E operatin s&ste fro ENEA.se

    ,* >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    83/91

    Message-based communication Mailboxes

    (he owner a t t r i) ! te is declared volatile to per it thread- safe access e%ent froethods not )ein synchronized . 8oth source /fro java.util.EventObject and

    owner are declared transient since those attri)!tes ha%e no eanin o!tside the

    pro ra / U7 'her e th e& 'ere create d. nst ead, for instanc e 'hen seriali ed to astrea of )&tes and sent o%er a net'ork, the& )oth et the %al!e null .

    Real-Time Event Buffers RTEventBuffer(he class RTEventBuffer 8 is desi ned to acco plish essa e-)ased co !nication'ith )!fferin and !sin RTEvent o)6ects as essa es. (o a%oid conf!sion 'ith other t&pes of )!ffers in other a%a packa es or in operatin s&ste s, the follo'in sho!ld

    )e clear

    1. (raditionall&, de ands on fle*i)ilit& ha%e )een odest for real-ti e and e )ed-ded s&ste s, and pro ra in /in C 'itho!t s!pport for o)6ect orientation has

    )ee n stand ard. 7essa es for co !nic ati on are th en in os t cases st ati ca ll& de -fined )& so e struct t&pe. (he si e of the essa e can then )e o)tained )& call-in sizeof , no additional s!)classes are a%aila)le /or ' i ll )e a%aila)le d!rinr!nti e , the data is not s!)6ect to relocation )& so e e or& ana er /BC ,and therefore the essa e can )e handled and copied as a se !ence of )&tes.9ith so e restrictions, the sa e holds for pro ra in in CJJ. A essa e canthen )e referred to )& a pointer to the e or& location, )!t to i pro%e ro)!st -ness for lar e co ple* s&ste s the essa e data is nor all& copied for transfer to so e other part of the soft'are. (he reason is that an!al e or& ana e -

    ent in ter s of pro ra in r!les and so called reference co!ntin does notscale !p %er& 'ell.

    or !l t i- threaded pro ra in in a%a, 'e do not kno ' the o)6ect si e or 'here the o)6ect is stored in e or&, and 'e do not ha%e to cop& essa es for reasons of e or& ana e ent /since a%a pro%ides BC . Postin an e%ent o)-

    6ect therefore eans pass in the /one 'ord refere nc e to th at o)6ect, 'hich al sosa%es the ti e for the cop&in .

    2. (he RTEventBuffer is not !sef!l for co !nication )et'een :" processes the&nor all& 'ork in different address spaces and o)6ect references cannot )e shared,and hence o)6ects are to )e represented )& data that is copied to the )!ffer. (heactions to con%ert a a%a o)6ect to a se !ence of )&tes are referred to as seriali a -tion. (hat is s!pported in a%a, partl& in ter s of the interface java.io.Serial-izable , )!t that is o!tside the scope of this chapter.

    G (his ) !ffer and the e%ent class RTEvent are part of the se.lth.cs.realtime.event packa e. #ike for th e se.lth.cs.realtime.semaphore packa e, the classes as presen te d in th is chap te r are part of the #!nd a%a- )ased >ea l- (i e /# >( li) ra r& th atin ore detail 'ill )e the topic of the ne*t chapter. (he classes introd!ced in this chapter add )asic !tilities for conc!rrent pro ra in , 'itho!t chan in the odel of a%athreads and 'itho!t addin real-ti e s!pport. (hese classes are strai htfor'ard to !se onan& a%a platfor , 'hereas the co plete # >( li)rar& adds ore f!nda ental feat!res.

    200 -01-11 15 05 [email protected] ,,

  • 8/9/2019 LJRTbook_ch1-3

    84/91

    Chapter 3 Multi-Threaded Programming

    +. 8!ffers !sed for conc!rrent pro ra in , s !ch as the java.util.Vector , are!s!all& !n)o!nded. (hat is, the& e*pand in si e 'hen f!ll , or a java.lang.Out-OfMemoryError is thro'n. :!r ai at real-ti e a'are conc!rrenc&, to prepare for

    e%en hard real t i e later, oti%ates so e care concernin reso!rces, s!ch ase or&. E%en if 'e for fle*i)le real- ti e s&ste s do not kno' e*actl& ho' an&

    )&tes o!r appl ication needs, 'e need so e )o!nd s on the !sed reso!rces. or )!fferi n , th is eans th at 'e 'ork 'ith bounded buffers as the defa!lt . f , inso e cases, there sho!ld )e a need for !n)o!nded )!ffers, it is si ple to o%erridepost or fetch ethods to e*pand the )!ffer si e on de and.

    :ther reasons for o!r o'n )!ffer i ple entation incl!de /co pare ' ith java.u-til.Vector shrinka e 'itho!t losin )!ffer content, s!pport for RTEvent and o)-

    6ect o'ners hi p, desi n s!ita) le for e )edd ed na ti% e i p le e ntation on s all - e -or& s&ste s, and licensin iss!es for s!ch s&ste s. or the p!rpose of s!)classin ,t he in te rn al s of t he )!ffe r is !sef!l to kno'; t he se.lth.cs.realtime.even-t. RTEventBuffer is i ple ented as follo's.

    "tora e and s&nchroni ation"ince the )!ffer is to )e !sed

    ainl& as a : !e!e, 'i th a )o!nd ed si e th at is nor a ll& keptconstant, it is )est represented )&an arra&. (hat is of co!rse not%isi)le fro the o!tside, )!t tos!)classes it is. 9hen the inde*needs to ad%ance )e&ond the

    a*i ! inde* of the arra& it flipso%er and contin!es at inde* ero.(herefore this t&pe of )!ffer is alsocalled rin )!ffer, as depicted in

    i !re +-10.(he ethods of the )!ffer co!ld )econsidered )ein synchronized ,that is, the )!ffer is thread safe . (o

    pre%ent inte rference 'it hwait notify internall& froe*ternal code s&nchroni in on the

    )!ffer o)6ect, the s&nchroni a tion of the )!ffer ethods are acco plished )&synchronized(lock){...}

    'here the lock is declared asprotected Object lock = new Object();

    (hat onitor lock can then )e replaced in s!)classes or in the constr!ctor, if the operation of the )!ffer needs to )e s&nchroni ed 'ith so e other o)6ects/s!ch as an other )!ffer .(he act!al )!ffer arra& is, as sho'n in i !re +-10, declared as

    ,0 >eal-(i e Pro ra in H a a%a- )ased approach

    i !re +-10 >in )!ffer as an arra& 'ithsi e 12, c!rrentl& filled 'ith F o)-

    6ects /refere nced fro the ra& ele -ents .

    Y0Z

    Y1Z

    Y5Z

    Y11Z

    Y10Z

    Y2ZY+Z

    Y4Z

    YIZYGZ

    YFZ

    YEZ

    RTEvent[] buffer currSize==7

    fetchAt

    postAt

    growth

  • 8/9/2019 LJRTbook_ch1-3

    85/91

    Message-based communication Mailboxes

    protected RTEvent[] buffer;

    Constr!ction

    A ne' )!ffer is created )& the follo'in constr!ctors, 'here the defa!ltmaxSize is so e s&ste dependent DEFAULT_SIZE /c!rrentl& 4 in o!r s&ste , and the defa!lt lock o)6ect is allocated and internall&. (he

    para eters maxSize and lock o%errides the defa!lts public RTEventBuffer() public RTEventBuffer(int maxSize) public RTEventBuffer(int maxSize, Object lock)

    Postin(he ethods for postin e%ents to the )!ffer are na ed doPost , tryPost , or si pl& post . (he doPost ethod si pl& )locks the caller !ntil the postin isco pleted. (he tryPost i%es !p if the )!ffer is f!ll, either i ediate l& if noti eo!t is i%en or after the specified timeout /in s . (he ethod post is the

    eneric one that is s!)6ect to replace ent in s!)classes, 'hereas the other ethods are declared final for reasons of efficienc&.

    (he post ethod )& defa!lt si pl& calls doPost and ret ! rns null . (he ret!rn/of t&pe RTEvent %al!e is !sef!l 'hen s!)classin and chan in post to callone of the tryPost ethods, 'hich ret!rn null 'hen the e%ent 'ass!ccessf!ll& posted. (he e%ent s!pplied as an ar ! ent to tryPost is ret!rnedif not posted /d!e to the )!ffer )ein f!ll . >et!rnin the !nposted e%entsi plifies the callin code. (he p!)lic postin ethods are

    RTEvent post(RTEvent e)final void doPost(RTEvent e)final RTEvent tryPost(RTEvent e)

    final RTEvent tryPost(RTEvent e, long timeout)

    etchin(he correspondin ethods for fetchin essa es look as follo's, 'here thetryFetch ethods ret!rn null if no e%ent o)6ect 'as o)tained.

    RTEvent fetch()final RTEvent doFetch()final RTEvent tryFetch()final RTEvent tryFetch(long timeout)

    Control and stat!s(he follo'in non-)lockin ethods can )e !sed to check if the )!ffer is e pt&or f!ll.

    boolean isEmpty()boolean isFull()or a sin le prod!cin or cons! in thread these ethods can )e !sef!l, )!t

    in the eneral case 'ith o!ter threads in%ol%ed the ret!rned state a& of co!rse )e in%alid alread& 'hen e*ec!tion contin!es on the ne*t line /d!e to

    pree p tio n, etc. , so !sin the try- ethods are !s!all& preferred."o eti es state or ode chan es are to take place )ased on the state of the

    200 -01-11 15 05 [email protected] ,2

  • 8/9/2019 LJRTbook_ch1-3

    86/91

    Chapter 3 Multi-Threaded Programming

    )!ffer, an d th e respon si )le th read is to )e )locked !n ti l the )!ffer condi tion isf!lfilled. (he follo'in a'ait- ethods are )lockin . E*a ples of !se incl!dea'ait all e%ent cons! ed )efore ter inatin the application, a'ait prod!cer

    started )efore startin operator or net'orkin interface, a'ait )!ffer filled'ith e%ent trace, and a'ait cons! er started, respecti%el&

    void awaitEmpty()void awaitNotEmpty()void awaitFull()void awaitNotFull()

    (he fetchAll is to et all )!ffered e%ents lea%in the )!ffer e pt&. (he e%entthat 'as the ne*t to )e fetched is ret!rned as the first ele ent /inde* 0 ,follo'ed )& the other e%ents in : order 'ith the ost recentl& posted e%entas the last ele ent. An e pt& arra& /not n!ll is ret!rned if the )!ffer 'ase pt&. Callin flush also res!lts in an e pt& )!ffer.

    RTEvent[] fetchAll()void flush()

    (here are set and get ethods for the a*i ! si e of the )!ffer. Note thatif the a*i ! si e of the )!ffer is decreased to less than the c!rrent si e/o)tained %ia currentSize , the caller of setMaxSize is )locked !ntil the si eact!all& has decreased to the ne' a*i ! si e /d!e to other threads fetchin

    essa es .int currentSize()public int getMaxSize()void setMaxSize(int newSize)

    :ther protected fieldsApart fro the protected )!ffer arra & and o)6ect lock descri)ed a)o%e, thefollo'in are the other fields for s!)class !sa e. irst there are the inde*es for readin respecti%el& 'ritin as sho'n in i !re +-10, as 'ell as the c!rrentsi e

    int currSize;int postAt;int fetchAt;

    (here are t 'o fields for keepin the a*i ! si e. t is the maxSizeW that isthe re !ested a*i ! si e. (he maxSizeR can te poraril& d!rin shrinka e/resizing e !al to true of a too lar e )!ffer )e reater than maxSizeW , )!tthe& 'ill ha%e the sa e %al!e d!rin nor al operation /'hen resizing e !alsfalse .

    int maxSizeR;int maxSizeW;boolean resizing;

    (hreads that are interr!pted d!rin /or prior to )lockin are thro'n an RTInter-rupted error.

    06 >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    87/91

    Message-based communication Mailboxes

    Referring to buffer input or output"o eti es it is desira)le to ha%e an o)6ect that represents onl& one end of a )!ffer.

    or the RTEventBuffer , !tili in a%a interfaces, this is acco plished )& one inter -face for inp!t containin the post ethods, and one interface for o!tp!t containinthe ethods for fetchin e%ents. (h!s,

    class RTEventBuffer implements RTEventBufferInput, RTEventBufferOutput

    'here these interfaces are defined as

    interface RTEventBufferInput { RTEvent post(RTEvent e); void doPost(RTEvent e); RTEvent tryPost(RTEvent e); RTEvent tryPost(RTEvent e, long timeout); RTEvent tryPost(RTEvent e, long timeout, int nanos);

    }

    interface RTEventBufferOutput {RTEvent fetch();

    RTEvent doFetch(); RTEvent tryFetch(); RTEvent tryFetch(long timeout); RTEvent tryFetch(long timeout, int nanos);}

    >efer to the RTEventBuffer a)o%e for a description of the ethods. $sin these in-terfaces &o! can for instance ha%e the o!tp!t of a )!ffer ana ed as a shared re-so!rce in a onitor, 'hile the inp!t can )e directl& a%aila)le for postin e%ents/fro se%eral threads since the RTEventBuffer )& itself is a onitor . 9ithin s!ch a

    onitor holdin an RTEventBufferInput , a potentiall& )lockin call s!ch as doFetchsho!ld onl& )e !sed 'ith reat care since the )locked thread 'ill lock also the o!ter

    onitor.

    n eneral for prod!cer-cons! er sit!ations, the inp!t and o!tp!t interfaces to the )!ffer si pl& pro%ide a con%enie nt 'a& of passin one end of the )!ffer to th e pro-d!cer or the cons! er. :f co!rse an o)6ect /a onitor or an ordinar& o)6ect i%en anRTEventBufferInput can check if it is an instance of RTEventBuffer /'hich it doesnot need to )e since an& o)6ect can i ple ent the sa e interface , and if so, cast toRTEventBuffer and !se also the post ethods. e-call, ho'e%er, that !lti-thre adin ainl& is a)o!t cooperatin conc!rrenc&.

    200 -01-11 15 05 [email protected] 01

  • 8/9/2019 LJRTbook_ch1-3

    88/91

    Chapter 3 Multi-Threaded Programming

    Threads and event-based communicationA ail)o*, here acco plished )& an instance of RTEventBuffer 9 , can )e declared andreferred to in different 'a&s (he ail)o*/es can )e ade lo)all& a%aila)le, for e*a ple created in the ain

    pro ra and passed as ar ! e nt to the cons tr!c to rs of the different send in r e -cei%in o)6ects/ t&picall& threads , or staticall& defined attri)!tes of so e classkno'n to other classes at co pile ti e. 9ith s!ch lo)all& defined ail)o*es,the& are %isi)le in the soft'are desi n, as entities of their o'n.

    9e can also %ie' the pro%ided )!fferin as a propert& of so e o)6ect, and ha%ethe ail)o* as an attri)!te internal to the class that pro%ides the ethods that

    ake !se of the )!fferin . (&picall& the enclosin class 'ill )e of t&pe Thread andact as the recei%er of the e%ents /altho! h the sender can )e !na'are of that if sendin is acco plished )& so e other ethod of the recei%in thread. 9ith s!cho)6ect-internal ail)o*es, the )!fferin is part of the internal desi n of that class.

    (h!s, the the ain difference here is a desi n choice sho!ld ail)o*es )e e*posed-to or part-of the o)6ects that ake !se of the M ollo'in co on o)6ect-orienteddesi n r !les, this depends on 'hat 'e see as ent i ties 'i th in o!r desi n . f the

    )!ffers for the core of the appl ication it a& )e prefer a)l e to ha%e the e*posed.( classes ' il l incl!de )oth the RTEventBuffer an dother )!ffer classes 'ith different properties and different i ple entations. (he a%a- doc

    pa es pro%ide the %al id descr ip tion for pro ra i n !sin the a%aila )le )!ffers , 'h ile the/not co plete description here co%ers the eneral ideas of e%ents and )!ffers.

    0' >eal-(i e Pro ra in H a a%a- )ased approach

  • 8/9/2019 LJRTbook_ch1-3

    89/91

    Message-based communication Mailboxes

    public RTEvent putEvent (RTEvent ev) { mailbox.doPost (ev); // Subclasses may use tryPost. return null; // Subclasses may return resulting event.

    } // etc. etc.}(he J in J Thread is to stress the fact that this t&pe of thread sti ll is a /conc!rrent

    a%a thread /that is, not specified to )e real t i e as 'i ll )e the case in follo' inchapters .

    (o si plif& pro ra in in the case that the sa e thin sho!ld )e repeated o%er and o%er a ain, there is a defa!lt r!n ethod that calls perfor accordin to the fol-lo'in

    public void run () { while (!isInterrupted()) {

    perform (); } }

    9hen i ple entin the thread )eha%ior, in run or perform , the the doFetch andtryFetch ethods are !sef!l, like is this e*e plif&in perform ethod class MyEventProcessor extends JThread { public void perform() { serverObject.process(mailbox.doFetch()); } }

    n addition to the ethods of the )ase class Thread as sho'n on Pa e 41, this eanstha t the class JThread pro%ides the follo'in si ple to i ple ent )!t con%enient

    ethods

    public RTEvent putEvent (RTEvent ev) // Generic event inputpublic void terminate () // Interrupt and joinpublic static void sleepUntil (long wakeUpTime) // Sleep until that absolute time

    protected void perform () // Override to define cyclic work

    200 -01-11 15 05 [email protected] 03

  • 8/9/2019 LJRTbook_ch1-3

    90/91

    Bibliography

    (o )e acco plished.....

  • 8/9/2019 LJRTbook_ch1-3

    91/91

    Index