Razvan said:
Somebody asked me today what is a monitor. I said that it is some
piece of code that manages the locking mechanism and that it should
not be concerned about it because the monitor mechanism is implemented
in Java by default.
Can somebody give a more academic/corect definition ?
According to a book I happened to have handy, the name "monitor" was invented
by Tony Hoare, and was popularised in his paper "Monitors: an operating system
structuring concept" which was published in the CACM in 1974 (it's in the ACM's
online library, but you need a subscription to read it).
Apparently the concept was then used in the Pascal family of languages.
Having wondered what "monitor" really meant myself (not being a Pascal
programmer), I went off and read the paper. Here's a summary.
A "monitor" is a programming language element used for expressing the control
of concurrency. In modern terms it is best viewed as a flavour of class with
some added elements and properties that make it well-adapted to expressing
concurrency.
A monitor is a collection of:
some data items (variables)
some procedures (methods)
some "conditions", which can be true or false.
The procedures have exclusive access to the variables and conditions (which
makes a monitor very like a modern OO object). Additionally, the
compiler/system ensures that no two procedures can be active at once (very much
like "synchronized" methods in Java). Lastly any procedure can "wait" for a
condition to become true, or it can "notify" any other processes that the state
of a condition had changed.
As you'll see, it's all very familiar. It's interesting to compare it to the
state of the art at that time. I don't think anyone (except Alan Kay, and his
associates, of course) really knew what OO was then (I don't think the term was
in anything like general use, if it had even been invented). And although
Simula had already introduced the "class" concept (Hoare mentions it in the
paper) I don't think an understanding of /objects/ (as distinct from ADTs, say)
had yet emerged. One concurrency concept that it was intended to subsume was
the "critical section", where passages of code scattered around the program
would be marked such that none of them were allowed to execute concurrently.
Compared with that (and with semaphores, etc) monitors have a much more
structured (and modern!) feel to them. BTW, Hoare ascribes the invention to
Per Hinch-Bransen.
The paper then goes on to illustrate (and prove) how monitors can be used to
solve various concurrency problems (like bounded queues, emulating semaphores,
etc), and to discuss issues like which of the waiting processes should be
scheduled next when a condition was notified. Something of a classic, that
paper...
HTH
-- chris