Wednesday, December 16, 2009

SCJP

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier. Table 1-1 lists all of the Java keywords including one new one for 5.0, enum.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.Examples of legal and illegal identifiers follow, first some legal identifiers:
int _a;
int $c;
int ______2_w;
int _$;
int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal (it's your job to recognize why):

int :b;
int -d;
int e#;
int .f;
int 7g;

Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:

Dog
Account
PrintWriter

For interfaces, the names should typically be
adjectives like

Runnable
Serializable



Variables Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:

buttonWidth
accountBalance
myString


Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:

MIN_HEIGHT


JavaBean Property Naming Rules

  • If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter name for a property named "size." Keep in mind that you do not need to have a variable named size (although some IDEs expect it). The name of the property is inferred from the getters and setters, not through any variables in your class. What you return from getSize() is up to you.
  • If the property is a boolean, the getter method's prefix is either get or is. Forexample, getStopped() or isStopped() are both valid JavaBeans names fora boolean property.
  • The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size.
  • To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (get, is, or set).
  • Setter method signatures must be marked public, with a void return type and an argument that represents the property type.
  • Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property.

JavaBean Listener Naming Rules

  • Listener method names used to "register" a listener with an event source must use the prefix add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source will have to allow others to register for Action events.
  • Listener method names used to remove ("unregister") a listener must use the prefix remove, followed by the listener type (using the same rules as the registration add method).
  • The type of listener to be added or removed must be passed as the argument to the method.
  • Listener method names must end with the word "listener".

Examples of valid JavaBean method signatures are

public void setMyValue(int v)
public int getMyValue()
public boolean isMyStatus()
public void addMyListener(MyListener m)
public void removeMyListener(MyListener m)

Examples of invalid JavaBean method signatures are

void setCustomerName(String s) // must be public
public void modifyMyValue(int v) // can't use 'modify'
public void addXListener(MyListener m) // listener type mismatch .


Source File Declaration Rules

  • There can be only one public class per source code file.
  • Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
  • If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java.
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  • import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • A file can have more than one nonpublic class.
  • Files with no public classes can have a name that does not match any of the classes in the file.
Class Declarations and Modifiers

The following code is a bare-bones class declaration:

class MyClass { }

This code compiles just fine, but you can also add modifiers before the class declaration. Modifiers fall into two categories:

  • Access modifiers: public, protected, private.
  • Non-access modifiers (including strictfp, final, and abstract).
package name convention

Sun recommends that developers use reverse domain names, appended with division and/or project names. For example, if your domain name is geeksanonymous.com, and you're working on the client code for the TwelvePointOSteps program, you would name your package something like com.geeksanonymous.steps.client.That would essentially change the name of your class to com.geeksanonymous.steps.client.Utilities. You might still have name collisions within your company, if you don't come up with your own naming schemes, but you're guaranteed not to collide with classes developed outside your company (assuming they follow Sun's naming convention, and if they don't, well, Really Bad Things could happen).


Class Access
What does it mean to access a class? When we say code from one class (class A) has access to another class (class B), it means class A can do one of three things:

  • Create an instance of class B.
  • Extend class B (in other words, become a subclass of class B).
  • Access certain methods and variables within class B, depending on the access
control of those methods and variables. In effect, access means visibility. If class A can't see class B, the access level of the methods and variables within class B won't matter; class A won't have any way to access those methods and variables.








Thursday, November 26, 2009

os-java:Processes

Early computer systems allowed only one program to be executed at a time. This program had complete control of the system and had access to all the system's resources. In contrast, current-day computer systems allow multiple programs to be loaded into memory and executed concurrently. This evolution required firmer control and more compartmentalization of the various programs; and these needs resulted in the notion of a process, which is a program in execution. A process is the unit of work in a modern time-sharing system.

Operating-system processes executing system code and user processes executing user code.

Even if the user can execute only one program at a time, the operating system may need to support its own internal programmed activities, such as memory management. In many respects, all these activities are similar, so we call all of them processes.

Text section, Program counter, Stack, Data section, Heap

Informally, as mentioned earlier, a process is a program in execution. A process is more than the program code, which is sometimes known as the text section. It also includes the current activity, as represented by the value of the program counter and the contents of the processor's registers. A process generally also includes the process stack, which contains temporary data (such as method parameters, return addresses, and local variables), and a data section, which contains global variables. A process may also include a heap, which is memory that is dynamically allocated during process run time.

Prgram and Process

We emphasize that a program by itself is not a process; a program is a passive entity, such as a file containing a list of instructions stored on disk, whereas a process is an active entity, with a program counter specifying the next instruction to execute and a set of associated resources.

One program separate processes

Although two processes may be associated with the same program, they are nevertheless considered two separate execution sequences. For instance, several users may be running different copies of the mail program, or the same user may invoke many copies of the editor program. Each of these is a separate process

Process State

As a process executes, it changes state. The state of a process is defined in part by the current activity of that process. Each process may be in one of the following states.

(Figure 4.1 Diagram of process state.)


  • New: The process is being created.
  • Running: Instructions are being executed.
  • Waiting: The process is waiting for some event to occur (such as an I/O completion or reception of a signal)
  • Ready: The process is waiting to be assigned to a processor.
  • Terminated: The process has finished execution.

It is important to realize that only one process can be running on any processor at any instant. Many processes may be ready and waiting, however.


Process Control Block


Each process is represented in the operating system by a process control block (PCB)—also called a task control block.

It contains many pieces of information associated with a specific process, including these.

(Figure 4.2 Process control block ((PCB).)
  • Process state: The state may be new, ready, running, waiting, halted, and so on.
  • Program counter: The counter indicates the address of the next instruction to be executed for this process.
  • CPU registers: The registers vary in number and type, depending on the computer architecture. They include accumulators, index registers, stack pointers, and general-purpose registers, plus any condition-code information. Along with the program counter, this state information must be saved when an interrupt occurs, to allow the process to be continued correctly afterwards.
  • CPU-scheduling information: This information includes a process priority, pointers to scheduling queues, and any other scheduling parameters.
  • Memory-management information: This information may include such information as the value of the base and limit registers, the page tables, or the segment tables, depending on the memory system used by the operating system.
  • Accounting information: This information includes the amount of CPU and real time used, time limits, account numbers, job or process numbers, and so on.
  • I/O status information: This information includes the list of I/O devices allocated to the process, a list of open files, and so on.
In brief, the PCB simply serves as the repository for any information that may vary from process to process.

(Figure 4.3)Diagram showing CPU switch from process to process.

Threads

Many modern operating systems have extended the process concept to allow a process to have multiple threads of execution and thus to perform more than one task at a time.

Process Scheduling

Process scheduler selects an available process (possibly from a set of several available processes) for program execution on the CPU. For a uniprocessor system, there will never be more than one running process. If there are more processes, the rest will have to wait until the CPU is free and can be rescheduled.

Scheduling Queues


As processes enter the system, they are put into a job queue, which consists of all processes in the system. The processes that are residing in main memory and are ready and waiting to execute are kept on a list called the ready queue. This queue is generally stored as a linked list. A ready-queue header contains pointers to the first and final PCBs in the list. Each PCB includes a pointer field that points to the next PCB in the ready queue.


The system also includes other queues. When a process is allocated the CPU, it executes for a while and eventually quits, is interrupted, or waits for the occurrence of a particular event, such as the completion of an I/O request. Suppose the process makes an I/O request to a shared device, such as a disk. Since there are many processes in the system, the disk may be busy with the I/O request of some other process. The process therefore may have to wait for the disk. The list of processes waiting for a particular I/O device is called a device queue. Each device has its own.

device queue (Figure 4.4).







Disabla Enable SeLinux

To confirm this, you can temporarily disable SELinux by running this command as root:

/usr/sbin/setenforce 0

Once that command has been run, try the installer again. You should be albe to proceed through the installation at this point. Once installed, you can run the command:

/usr/sbin/setenforce 1









Wednesday, November 18, 2009

os-java:operating system structure

System Components



Process Management



Main-Memory Management



File Management



I/O-System Management



Secondary-Storage Management




Networking




Protection System




Command-Interpreter System




Operating-System Services




System Calls




Process Control




File Management




Device Management




Information Maintenance




Communication

There are two common models of communication:
  • the message-passing model.
  • the shared-memory model.

In the message-passing model, information is exchanged through an interprocess-communication facility provided by the operating system.

In the shared-memory model, processes use map memory system calls to gain access to regions of memory owned by other processes.

Both of the models just discussed are common in operating systems, and some systems even implement both.

( Figure 3.5 ) Communications models. (a) Msg passing.
(b) Shared memory.


System Programs

System programs provide a convenient environment for program development and execution. Some of them are simply user interfaces to system calls; others are considerably more complex. They can be divided into these categories:


  • File management: These programs create, delete, copy, rename, print, dump, list,and generally manipulate files and directories.
  • Status information: Some programs simply ask the system for the date, time,amount of available memory or disk space, number of users, or similar statusinformation. That information is then formatted and printed to the terminal or otheroutput device or file.
  • File modification: Several text editors may be available to create and modify thecontent of files stored on disk or tape.
  • Programming-language support: Compilers, assemblers, and interpreters forcommon programming languages (such as C, C++, Java, Visual Basic, and PERL)are often provided to the user with the operating system, although some of theseprograms are now priced and provided separately.
  • Program loading and execution: Once a program is assembled or compiled, itmust be loaded into memory to be executed. The system may provide absoluteloaders, relocatable loaders, linkage editors, and overlay loaders. Debuggingsystems for either higher-level languages or machine language are needed also.
  • Communications: These programs provide the mechanism for creating virtualconnections among processes, users, and computer systems. They allow users tosend messages to one another's screens, to browse web pages, to send electronic-mail messages, to log in remotely, or to transfer files from one machine to another.

system utilities or application programs


In addition to systems programs, most operating systems are supplied with programs that are useful in solving common problems or performing common operations. Such programs include web browsers, word processors and text formatters, spreadsheets, database systems, compilers, plotting and statistical-analysis packages, and games. These programs are known as system utilities or application programs.


Command interpreter

Perhaps the most important system program for an operating system is the command interpreter. The main function of this program is to get and execute the next user-specified command. Many of the commands given at this level manipulate files:


In one approach, the command interpreter itself contains the code to execute the command. For example, a command to delete a file may cause the command interpreter to jump to a section of its code that sets up the parameters and makes the appropriate system call. In this case, the number of commands that can be given determines the size of the command interpreter, since each command requires its own implementing code.


An alternative approach—used by UNIX, among other operating systems implements most commands through system programs. In this case, the command interpreter does not understand the command in any way; it merely uses the command to identify a file to be loaded into memory and executed. Thus, the UNIX command to delete a file.

rm G

would search for a file called rm, load the file into memory, and execute it with the parameter G.

Wednesday, November 4, 2009

os-java:computer system structure

A modern, general-purpose computer system consists of a CPU and a number of device controllers and adapters that are connected through a common bus that provides access to shared memory.

(Figure 2.1).

For a computer to start running it needs to have an initial program to run. This initial program,or
bootstrap program, tends to be simple.

bootstrap program
  • Stored in read-only memory (ROM) such as firmware or EEPROM within the computer hardware.
  • It initializes all aspects of the system, from CPU registers to device controllers to memory contents.
  • The bootstrap program must know how to load the operating system and how to start executing that system.
  • To accomplish this goal, the bootstrap program must locate and load into memory the operating-system kernel.
  • The operating system then starts executing the first process, such as "init," and waits for some event to occur.
event
  • Event is usually signalled by an interrupt from either the hardware or the software.
  • Hardware may trigger an interrupt at any time by sending a signal to the CPU, usually by way of the system bus.
  • Software may trigger an interrupt by executing a special operation called a system call (also called a monitor call).
Events are almost always signalled by the occurrence of an interrupt or a trap. A trap (or an exception) is a software-generated interrupt caused either by an error (for example, division by zero or invalid memory access) or by a specific request from a user program that an operating-system service be performed.

interrupt


For each type of interrupt, separate segments of code in the operating system determine what action should be taken, and an interrupt service routine is provided to deal with the interrupt.
  • When the CPU is interrupted, it stops what it is doing and immediately transfers execution to a fixed location.
  • The fixed location usually contains the starting address where the service routine for the interrupt is located.
  • The interrupt service routine executes; on completion, the CPU resumes the interrupted computation.

    (Figure 2.2.)
interrupt handling

The straightforward method for handling this transfer would be to invoke a generic routine to examine the interrupt information and then call the interrupt-specific handler.

However, because only a predefined number of interrupts is possible, a table of pointers to interrupt routines can be used instead.


A system call is invoked in a variety of ways, depending on the functionalityprovided by the underlying processor. In all forms, it is the method used by a process to request action by the operating system. A system call usually takes the form of a trap to a specific location in the interrupt vector.

I/O Structure

General-purpose computer system consists of a CPU and multiple device controllers that are connected through a common bus.

Depending on the controller, there may be more than one attached device. For instance, seven or more devices can be attached to the small computer-systems interface (SCSI) controller.

A device controller maintains some local buffer storage and a set of special-purpose registers.

The device controller is responsible for moving the data between the peripheral devices that it controls and its local buffer storage.

The size of the local buffer within a device controller varies from one controller to another, depending on the particular device being controlled. For example, the size of the buffer of a disk controller is the same as or a multiple of the size of the smallest addressable portion of a disk, called a sector, which is usually 512 bytes. Currently, 2MB to 8MB disk controller buffers are common.

I/O Interrupts

  • To start an I/O operation, the CPU loads the appropriate registers within the device controller.
  • The device controller, in turn, examines the contents of these registers to determine what action to take.
  • For example, if it finds a read request, the controller will start the transfer of data from the device to its local buffer.
  • Once the transfer of data is complete,the device controller informs the CPU that it has finished its operation. It accomplishes this communication by triggering an interrupt.

synchronous I/O

I/O is started; then, at I/O completion, control is returned to the user process.

asynchronous I/O

Returns control to the user program without waiting for the I/O to complete. The I/O then can continue while other system operations are occurring.

Two I/O methods: (a) synchronous, and (b) asynchronous.

( Figure 2.3 )


Whichever approach is used, waiting for I/O completion is accomplished in one of two ways. Some computers have a special wait instruction that idles the CPU until the next interrupt. Machines that do not have such an instruction may have a wait loop:

Loop: jmp Loop

This tight loop simply continues until an interrupt occurs, transferring control to another part of the operating system. Such a loop might also need to poll any I/O devices that do not support the interrupt structure but that instead simply set a flag in one of their registers and expect the operating system to notice that flag.


If the CPU always waits for I/O completion, as it does when the synchronous approach is used, only one I/O request can be outstanding at a time.

A better alternative is to start the I/O and then continue processing other operating- system or user program code—the asynchronous approach.

A system call is then needed to allow the user program to wait for I/O completion, if desired. If no user programs are ready to run, and the operating system has no other work to do, we still require the instruction or waitidle loop, as before.

We also need to be able to keep track of many I/O requests at the same time. For this purpose, the operating system uses a table containing an entry for each I/O device: the device-status table.

(Figure 2.4).

Each table entry indicates the device's type, address, and state (not functioning, idle, or busy).

If the device is busy with a request, the type of request and other parameters will be stored in the table entry for that device.

Since it is possible for other processes to issue requests to the same device, the operating system will also maintain a wait queue—a list of waiting requests—for each I/O device.

An I/O device interrupts when it needs service.(completion of an I/O request) When an interrupt occurs, the operating system first determines which I/O device caused the interrupt. It then indexes into the I/O device table to determine the status of that device and modifies the table entry to reflect the occurrence of the interrupt.

If there are additional requests waiting in the queue for this device, the operating system starts processing the next request.

Example - keyboard input

  • In a simple terminal-input driver, when a line is to be read from the terminal the first character typed is sent to the computer.
  • When that character is received, the asynchronous-communication (or serial-port) device to which the terminal line is connected interrupts the CPU.
  • When the interrupt request from the terminal arrives, the CPU is about to execute some instruction. The address of this interrupted instruction is saved, and control is transferred to the interrupt service routine for the appropriate device.
  • The interrupt service routine saves the contents of any CPU registers that it will need to use.
  • It checks for any error conditions that might have resulted from the most recent input operation.
  • It then takes the character from the device and stores that character in a buffer.
  • The interrupt routine must also adjust pointer and counter variables, to be sure that the next input character will be stored at the next location in the buffer.
  • The interrupt routine next sets a flag in memory indicating to the other parts of the operating system that new input has been received.
  • The other parts are responsible for processing the data in the buffer and for transferring the characters to the program that is requesting input.
  • Then, the interrupt service routine restores the contents of any saved registers and transfers control back to the in interrupted instruction.

It should be clear that the main advantage of asynchronous I/O is increased system efficiency. While I/O is taking place, the system CPU can be used for processing or starting I/Os to other devices. Because I/O can be slow compared to processor speed, the system makes efficient use of its facilities.

Direct memory access (DMA)

Direct memory access (DMA) is used for high-speed I/O devices. After setting up buffers, pointers, and counters for the I/O device, the device controller transfers an entire block of data directly to or from its own buffer storage to memory, with no intervention by the CPU. Only one interrupt is generated per block, rather than the one interrupt per byte generated for low-speed devices.

Main Memory

Main memory and the registers built into the processor itself are the only storage that the CPU can access directly.There are machine instructions that take memory addresses as arguments, but none that take disk addresses. Therefore, any instructions in execution, and any data being used by the instructions, must be in one of these direct-access storage devices. If the data are not in memory, they must be moved there before the CPU can operate on them.


Memory-mapped I/O.

Ranges of memory addresses are set aside and mapped to the device registers. Reads and writes to these memory addresses cause the data to be transferred to and from the device registers. This method is appropriate for devices that have fast response times, such as video controllers. In the IBM PC, each location on the screen is mapped to a memory location. Displaying text on the screen is almost as easy as writing the text into the appropriate memory-mapped locations.

I/O ports

Memory-mapped I/O is also convenient for other devices.The CPU transfers data through these kinds of devices by reading and writing a few device registers, called I/O ports.

rogrammed I/O (PIO)

To send out a long string of bytes through a memory-mapped serial port, the CPU writes one data byte to the data register, then sets a bit in the control register to signal that the byte is available. The device takes the data byte and then clears the bit in the control register to signal that it is ready for the next byte. Then the CPU can transfer the next byte. The CPU may use polling to watch the control bit, constantly looping to see whether the device is ready; this method of operation is called programmed I/O (PIO).

Interrupt driven

If the CPU does not poll the control bit, but instead receives an interrupt when the device is ready for the next byte, the data transfer is
interrupt driven.


Cache

Registers that are built into the CPU are generally accessible within one cycle of the CPU clock. Most CPUs can decode instructions and perform simple operations on register contents at the rate of one or more operations per clock tick. The same cannot be said of main memory, which is accessed via a transaction on the memory bus. Accessing memory may take many cycles of the CPU clock, in which case the processor normally needs to stall, since it does not have the data required to complete the instruction that it is executing. Because memory is accessed so frequently, this situation is intolerable. The remedy is to add fast memory between the CPU and main memory. A memory buffer used to accommodate a speed differential, called a cache.

cache coherency

In a hierarchical storage structure, the same data may appear in different levels. For example, suppose that integer A is located in file B, which resides on magnetic disk. Integer A is to be incremented by 1. The increment operation proceeds by first issuing an I/O operation to copy the disk block on which A resides to main memory. Next, A is copied to the cache and to an internal register. Thus, the copy of A appears in several places: on the magnetic disk, in main memory, in the cache, and in an internal register (see Figure 2.7). Once the increment takes place in the internal register, the values of A in the various storage systems differ. The values become the same only after the new value of A is written from the internal register back to the magnetic disk.

In such an environment, a copy of A may exist simultaneously in several caches.We must make sure that an update to the value of A in one cache is immediately reflected in all other caches where A resides. This situation is called cache coherency, and it is usually a hardware problem (handled below the operating-system level).


Dual-Mode Operation


At system boot time, the hardware starts in monitor mode. The operating system is then loaded and starts user processes in user mode. Whenever a trap or interrupt occurs, the hardware switches from user mode to monitor mode (that is, changes the state of the mode bit to 0). Thus, whenever the operating system gains control of the computer, it is in monitor mode. The system always switches to user mode (by setting the mode bit to 1) before passing control to a user program.


The dual mode of operation provides us with the means for protecting the operating system from errant users—and errant users from one another. We accomplish this protection by designating some of the machine instructions that may cause harm as privileged instructions. The hardware allows privileged instructions to be executed.only in monitor mode. If an attempt is made to execute a privileged instruction in user mode, the hardware does not execute the instruction but rather treats it as illegal and traps it to the operating system.

system call

The concept of privileged instructions also provides the means for a user program to ask the operating system to perform tasks that are reserved to the operating system on the user program's behalf. Each such request is invoked by the user executing a privileged instruction. Such a request is known as a system call (also called a monitor call or an operating-system function call)

When a system call is executed, it is treated by the hardware as a software interrupt. Control passes through the interrupt vector to a service routine in the operating system, and the mode bit is set to monitor mode. The system-call service routine is a part of the operating system. The monitor examines the interrupting instruction to determine what system call has occurred; a parameter indicates what type of service the user program is requesting. Additional information needed for the request may be passed in registers, on the stack, or in memory (with pointers to the memory locations passed in registers). The monitor verifies that the parameters are correct and legal, executes the request, and returns control to the instruction following the system call.


The lack of a hardware-supported dual mode can cause serious shortcomings in an operating system. For instance, MS-DOS was written for the Intel 8088 architecture, which has no mode bit and, therefore, no dual mode. A user program running awry can wipe out the operating system by writing over it with data; and multiple programs are able to write to a device at the same time, with possibly disastrous results.

I/O Protection

To prevent users from performing illegal I/O, we define all I/O instructions to be privileged instructions. Thus, users cannot issue I/O instructions directly; they must do it through the operating system by means of a system call (Figure 2.8). The operating system, executing in monitor mode, checks to make sure that the request is valid and (if it is valid) performs the I/O requested. The operating system then returns to the user.

Consider a computer executing in user mode. It will switch to monitor mode whenever an interrupt or trap occurs, jumping to the address determined from the interrupt vector. If a user program, as part of its execution, stores a new address in the interrupt vector, this new address could overwrite the previous address with an address in the user program. Then, when a corresponding trap or interrupt occurred, the hardware would switch to monitor mode and would transfer control through the (modified) interrupt vector to the user program!


Memory Protection

We see, then, that we must provide memory protection at least for the interrupt vector and the interrupt-service routines of the operating system. In general, we want to protect the operating system from access by user programs and, in addition, to protect user programs from one another.

To separate each program's memory space from the others', we need the ability to determine the range of legal addresses that the program may access and to protect the memory outside that space. We can provide this protection by using two registers, usually a base and a limit, as illustrated in Figure 2.9. The base register holds the smallest legal physical memory address; the limit register contains the size of the range.


Any attempt by a program executing in user mode to access monitor memory or other users' memory results in a trap to the monitor, which treats the attempt as a fatal error (Figure 2.10).

The base and limit registers can be loaded only by the operating system, which uses a special privileged instruction. Since privileged instructions can be executed only in monitor mode, and since only the operating system executes in monitor mode, only the operating system can load the base and limit registers.


CPU Protection

We must prevent a user program from, for example,getting stuck in an infinite loop and never returning control to the operating system. To accomplish this goal, we can use a timer. A timer can be set to interrupt the computer after a specified period. The period may be fixed (for example, 1/60 second) or variable (for example, from 1 millisecond to 1 second). A variable timer is generally implemented by a fixed-rate clock and a counter. The operating system sets the counter. Every time the clock ticks, the counter is decremented. When the counter reaches 0, an interrupt occurs.


context switch

A more common use of a timer is to implement time sharing. In the most straightforward case, the timer could be set to interrupt every N milliseconds, where N is the time slice that each user is allowed to execute before the next user gets control of the CPU. The operating system is invoked at the end of each time slice to perform various housekeeping tasks, such as adding the value N to the record that specifies (for accounting purposes) the amount of time the user program has executed thus far. The operating system also saves registers, internal variables, and buffers and changes several other parameters to prepare for the next program to run. This procedure is known as a context switch

Another use of the timer is to compute the current time. A timer interrupt signals the passage of some period, allowing the operating system to compute the current time in reference to some initial time.

Tuesday, November 3, 2009

os-java:Introduction

An operating system is a program that manages the computer hardware.

Operating systems for hand-held computers are designed to provide an
environment in which a user can easily interface with the computer to execute programs.

Mainframe operating systems are designed primarily to optimize utilization of hardware.

Personal computer (PC) operating systems support complex games, business applications, and everything in between.

some operating systems are designed to be
convenient, others to be efficient, and others some combination of the two.


Abstract view of the components of a computer system.

(
Figure 1.1)

The hardware
  • the central processing unit (CPU), the memory, and the input/output (I/O) devices
  • provides the basic computing resources for the system.

The application programs
  • such as word processors, spreadsheets, compilers, and web browsers
  • define the ways in which these resources are used to solve users'computing problems.
The operating system controls and coordinates the use of the hardware among the various application programs for the various users.

An operating system is similar to a government.Like a government, it performs no useful function by itself. It simply provides an environment within which other programs can do useful work.

pc
  • In this case, the operating system is designed mostly for ease of use.
  • with some attention paid to performance and none paid to resource utilization.

mainframe or minicomputer
  • users are accessing the same computer through other terminals.
  • The operating system in such cases is designed to maximize resource utilization.
  • To assure that all available CPU time, memory, and I/O are used efficiently and that no individual user takes more than her fair share.
workstations
  • users sit at workstations connected to networks of other workstations and servers.
  • These users have dedicated resources at their disposal, but they also share resources such as networking and servers—file, compute and print servers.
  • Therefore, their operating system is designed to compromise between individual usability and resource utilization.
handheld
  • These devices are mostly standalone units used singly by individual users.
  • Because of power and interface limitations, they perform relatively few remote operations.
  • performance per amount of battery life is important as well.
embedded

  • May have numeric keypads and may turn indicator lights on or off to show status.
  • But mostly they and their operating systems are designed to run without user intervention.


Saturday, October 17, 2009

Patterns - 040: Behavioral Patterns ( State )


Patterns - 039: Behavioral Patterns ( Interpreter )



In general, languages are made up of a set of grammar rules. Different sentences can be constructed by following these grammar rules.

Sometimes an application may need to process repeated occurrences of similar requests that are a combination of a set of grammar rules.These requests are distinct but are similar in the sense that they are all composed using the same set of rules.

In such cases, instead of treating every distinct combination of rules as a separate case, it may be beneficial for the application to have the ability to interpret a generic combination of rules.

The Interpreter pattern can be used to design this ability in an application so that other applications and users can specify operations using a simple language defined by a set of grammar rules.


Applying the Interpreter pattern:

  • A class hierarchy can be designed to represent the set of grammar rules with every class in the hierarchy representing a separate grammar rule.
  • An Interpreter module can be designed to interpret the sentences constructed using the class hierarchy designed above and carry out the necessary operations.

A language with extensive, complex grammar rules requires a large number of classes. The Interpreter pattern works best when the grammar is simple. Having a simple grammar avoids the need to have many classes corresponding to the complex set of rules involved, which are hard to manage and maintain.


Example

Let us build a calculator application that evaluates a given arithmetic expression. For simplicity, let us consider only add, multiply and subtract operations.

The Interpreter pattern can be applied in two stages:
  • Define a representation for the set of rules that make up the grammar for arithmetic expressions.
  • Design an interpreter that makes use of the classes that represent different arithmetic grammar rules to understand and evaluate a given arithmetic expression.
Arithmetic Expressions – Grammar


  • ArithmeticExpression::= ConstantExpression | AddExpression |MultiplyExpression | SubtractExpression
  • ConstantExpression::= Integer/Double Value
  • AddExpression::= ArithmeticExpression ‘+’ ArithmeticExpression
  • MultiplyExpression::= ArithmeticExpression ‘*’ ArithmeticExpression
  • SubtractExpression::= ArithmeticExpression ‘-’ ArithmeticExpression
Class Hierarchy Representing Grammar Rules for Arithmetic Expressions

( Figure 34.1 )

See the additional notes for Post order and algorithms


Tuesday, October 13, 2009

Patterns - 038: Behavioral Patterns ( Observer )



The Observer pattern is useful for designing a consistent communication model between a set of dependent objects and an object that they are dependent on.

This allows the dependent objects to have their state synchronized with the object that they are dependent on.

The set of dependent objects are referred to as observers and the object that they are dependent on is referred to as the subject.

In order to accomplish this, the Observer pattern suggests a publisher-subscriber model leading to a clear boundary between the set of Observer objects and the Subject object.

Whenever the subject undergoes a change in its state, it notifies all of its
registered observers.

An observer can register or subscribe with multiple subjects.

Whenever an observer does not wish to be notified any further, it unregistered itself with the subject.

For this mechanism to work:
  • The subject should provide an interface for registering and unregistering for change notifications.
  • One of the following two must be true:
  1. – In the pull model — The subject should provide an interface that enables observers to query the subject for the required state information to update their state.
  2. – In the push model — The subject should send the state information that the observers may be interested in.
  • Observers should provide an interface for receiving notifications from the subject.

(Figure 33.1)

From this class diagram it can be seen that:
  • All subjects are expected to provide implementation for an interface similar to the Observable interface.
  • All observers are expected to have an interface similar to the Observer interface.
Several variations can be thought of while applying the Observer pattern, leading to different types of subject-observers such as observers that are interested only in specific types of changes in the subject.


Example

Let us build a sales reporting application for the management of a store with multiple departments.

Upon selecting a department, two types of reports are to be displayed:
  • – Monthly report — A list of all transactions for the current month for the selected department.
  • – YTD sales chart — A chart showing the year-to-date sales for the selected department by month.
Whenever a different department is selected, both of the reports should be refreshed with the data for the currently selected department.

Let us define three classes with the stated functionality as in follwing Table


ClassRoleFunctionality

ReportManager

Subject

Displays the necessary UI for the user to select a department.
Maintains the user selected department in an instance variable.
MonthlyReportObserver
Displays the monthly report for the selected department.

YTDChart

Observer

Displays the YTD sales chart for the selected department.


Observable Interface and Its Implementer


(Figure 33.2 )

Observer Class Hierarchy

(Figure 33.4 )

Example Application: Class Association

(Figure 33.5)
ReportManager User Interface

(Figure 33.3)
Logical Flow

  1. Using the ReportManager user interface whenever a user selects a particular department and clicks on the OK button, the ReportManager undergoes a change in its internal state (i.e., the value of its instance variable department changes).
  2. As soon as the new state is set, the ReportManager invokes the refreshData(Observable) method on both the curr ently registered MonthlyReport and the YTDChart objects.
  3. As part of refreshData method, both the report objects:a. Check to make sure that the subject that invoked the refreshData method is in fact the same Subject instance they have registered with. This is to prevent the observers from responding to unintended calls.b. Query the ReportManager for its current state using the getDepartment method.c. Retrieve appropriate data from the data file for display.

Monday, October 12, 2009

Patterns - 037: Behavioral Patterns ( Memento )



The state of an object can be defined as the values of its properties or attributes at any given point of time. The Memento patter n is useful for designing a
mechanism to capture and store the state of an object so that subsequently, when needed, the object can be put back to this (previous) state.

This is more like an undo operation.

The Memento pattern can be used to accomplish this without exposing the object’s internal structure.

The object whose state needs to be captured is referred to as the
originator.

When a client wants to save the state of the originator, it requests the current state from the originator. The originator stores all those attributes that are required for restoring its state in a separate object referred to as a
Memento and returns it to the client.

A Memento object must hide the originator variable values from all objects except the originator. In other words, it should protect its internal state against access by objects other than the originator.

Example

Let us consider one application where customer data needs to be moved from a flat file to a relational database.

Let us consider three attributes — first name, last name and the credit-cardinformation in the flat file.

Whenever an invalid customer record is found, the process stops and prompts the user to correct the data and restart the process.

When the user restarts the process, the conversion process state is restored from the Memento object and the process resumes from where it stopped, instead of starting from the beginning of the source data file.


Storing the Memento in the memory is not an option in this case. The Memento needs to be stored to persistent media instead.

Instead of storing valid customer records in a relational database, the application generates a text file consisting of SQL insert statements.

DataConverter (Originator)

The DataConverter class is the implementer of the data conversion process.

ID
The instance variable ID constitutes the state of the DataConverter. It represents the customer ID of the last successfully processed customer record.

(Figure 32.1)

Memento
The Memento class is defined as an inner class within the DataConverter. The Memento is defined with its constructor and other methods as private.

In Java, a class can access the private members of its inner classes.


The DataConverter will be able to access these methods while they remain inaccessible to other objects. Because the state of the DataConverter needs to be preserved even after the application ends, the Memento object needs to be serialized to a file. Hence the Memento is designed to implement the java.io.Serializable interface to identify itself as a Serializable class.


In Java, a Serializable class must:
  • III Explicitly specify nonserializable attributes using the transient keyword
  • III Implement the java.io.Serializable interface
  • III Have access to the first zero argument constructor of its first non-Serializable super class

The client DCClient uses a helper MementoHandler object to serialize this Memento instance to a file. Once the data is corrected and the client DCClient is run again:
  • The client DCClient invokes the getMemento method on the MementoHandler requesting it for the stored Memento object.
  • The MementoHandler deserializes the previously serialized Mementoobject from the file and returns it to the client.
  • The client passes it to the DataConverter as an argument to its setMemento method. The DataConverter puts itself back to the state stored in the memento and resumes with the data conversion process from where it stopped during the previous run.

(Figure 32.2)

(Figure 32.3)



public class DCClient {

  public static void main(String[] args) {
      MementoHandler objMementoHandler = new MementoHandler();
      DataConverter objConverter = new DataConverter();

      objConverter.setMemento(objMementoHandler.getMemento());

      if (!(objConverter.process())) {
          System.out.println("Description: Invalid data - " +
                  "Process Stopped");
          System.out.println("Please correct the Data and " +
                  "Run the Application Again");
          objMementoHandler.setMemento(
                  objConverter.createMemento());
      }
  }
}

Patterns - 036: Behavioral Patterns ( Mediator )



In general, object-oriented applications consist of a set of objects that interactwith each other for the purpose of providing a service.This interaction can be direct (point-to-point) as long as the number of objects referring to each other directly is very low.

As the number of objects increases, this type of direct interaction can lead to a complex maze of references among objects. which affects the maintainability of the application. Also, having an object directly referring to other objects greatly reduces the scope for reusing these objects because of higher coupling.

( Figure 31.2)

In such cases, the Mediator pattern can be used to design a controlled,coordinated communication model for a group of objects, eliminating the needfor objects to refer to each other directly


(Figure 31.3)
The Mediator pattern suggests abstracting all object interaction details into a separate class, referred to as a Mediator. with knowledge about the interacting group of objects.

Every object in the group is still responsible for offering the service it is designed for, but objects do not interact with each other directly for this purpose.

The interaction between any two different objects is routed through the Mediator class. All objects send their messages to the mediator. The mediator then sends messages to the appropriate objects as per the application’s requirements.

The resulting design has the following major advantages:

  • With all the object interaction behavior moved into a separate (mediator) object, it becomes easier to alter the behavior of object interrelationships, by replacing the mediator with one of its subclasses with extended or altered functionality.
  • Moving inter object dependencies out of individual objects results in enhanced object re usability.
  • Because objects do not need to refer to each other directly, objects can be unit tested more easily.
  • The resulting low degree of coupling allows individual classes to be modified without affecting other classes.


Example


Consider the The FTP client simulation application.

(Figure 30.4)

Consider following minor changes
  • When the UI is first displayed, all buttons except the Exit button should be disabled.
  • When a file name is selected from the JList control displaying the local
    file system:
  1. – The Upload and Delete buttons should be enabled.
  2. – Any selected item in the remote file system display should be deselected.
  3. – The Download button should be disabled.

shows the following object interaction.

(Figure 31.5 )

As more controls are added the direct communication between objects creates a complex maze of references among objects.

Applying the Mediator pattern, an abstraction for the object interaction details can be created. This abstraction can be designed as a separate Mediator class.

(Figure 31.6)

From the Mediator class implementation it can be seen that the Mediator offers methods for different UI objects to register themselves with the Mediator. The set of object interactions to be executed when each UI control is activated (or clicked) is designed as a separate method inside the Mediator.
Client Usage of the Mediator
The client creates an instance of the Mediator. Whenever a UI object is created, the client passes the Mediator instance to it. The UI object registers itself with this instance of the Mediator.
User Interface Objects:

Mediator Interaction Because all the object interaction details ar e removed from individual UI objects to the Mediator object, the processEvent method of each of these UI objects gets reduced to a simple call to an appropriate Mediator method.



class Mediator {
    private UploadButton btnUpload;
    private DownloadButton btnDownload;
    private DeleteButton btnDelete;
    private LocalList localList;
    private RemoteList remoteList;

    public void registerUploadButton(UploadButton inp_ib) {
        btnUpload = inp_ib;
    }

    public void registerDownloadButton(
            DownloadButton inp_dnb) {
        btnDownload = inp_dnb;
    }

    public void registerDeleteButton(DeleteButton inp_db) {
        btnDelete = inp_db;
    }

    public void registerLocalList(LocalList inp_arl) {
        localList = inp_arl;
    }

    public void registerRemoteList(RemoteList inp_drl) {
        remoteList = inp_drl;
    }

    public void UploadItem() {

        int index = localList.getSelectedIndex();
        String selectedItem =
                localList.getSelectedValue().toString();
        ((DefaultListModel) localList.getModel()).remove(
                index);

        ((DefaultListModel) remoteList.getModel()).addElement(
                selectedItem);

        btnUpload.setEnabled(false);
        btnDelete.setEnabled(false);
        btnDownload.setEnabled(false);
    }

    public void DownloadItem() {
        int index = remoteList.getSelectedIndex();
        String selectedItem =
                remoteList.getSelectedValue().toString();
        ((DefaultListModel) remoteList.getModel()).remove(
                index);

        ((DefaultListModel) localList.getModel()).addElement(
                selectedItem);

        btnUpload.setEnabled(false);
        btnDelete.setEnabled(false);
        btnDownload.setEnabled(false);
    }

    public void DeleteItem() {
        int index = localList.getSelectedIndex();
        if (index >= 0) {
            ((DefaultListModel) localList.getModel()).remove(
                    index);
        }

        index = remoteList.getSelectedIndex();
        if (index >= 0) {
            ((DefaultListModel) remoteList.getModel()).remove(
                    index);
        }
        btnUpload.setEnabled(false);
        btnDelete.setEnabled(false);
        btnDownload.setEnabled(false);

    }

    public void LocalListSelect() {
        remoteList.setSelectedIndex(-1);
        btnUpload.setEnabled(true);
        btnDelete.setEnabled(true);
        btnDownload.setEnabled(false);
    }

    public void RemoteListSelect() {
        localList.setSelectedIndex(-1);
        btnUpload.setEnabled(false);
        btnDelete.setEnabled(true);
        btnDownload.setEnabled(true);
    }
}

}// end of class

Sunday, October 4, 2009

Patterns - 035: Behavioral Patterns ( Command )


In general, an object-oriented application consists of a set of interacting objects each offering limited, focused functionality.

In terms of implementation, the application may depend on a designated object that invokes methods on these objects by passing the required data as arguments. This designated object can be referred to as an invoker as it invokes operations on different objects.

The invoker may be treated as part of the client application. The set of objects that actually contain the implementation to offer the services required for the request processing can be referred to as Receiver objects.


(client_invoker_receiver)


In this design, the application that forwards the request and the set of Receiver objects that offer the services required to process the request are closely tied to each other in that they interact with each other dir ectly. This could result in a set of conditional if statements in the implementation of the invoker.


     if (RequestType=TypeB){
//do something
}


When a new type of feature is to be added to the application, the existing code needs to be modified and it violates the basic object-oriented open-closed principle.


Using the Command pattern, the invoker that issues a request on behalf of the client and the set of service-rendering Receiver objects can be decoupled. The Command pattern suggests creating an abstraction for the processing to be carried out or the action to be taken in response to client requests.



A given Command object is responsible for offering the functionality required to process the request it represents, but it does not contain the actual implementation of the functionality. Command objects make use of Receiver objects in offering this functionality.


(client_invoker_receiver_abstraction)



When the client application needs to offer a service in response to user (or other application) interaction:


  • 1. It creates the necessary Receiver objects.
  • 2. It creates an appropriate Command object and configures it with the Receiver objects created in Step 1.
  • 3. It creates an instance of the invoker and configures it with the Command object created in Step 2.
  • 4. The invoker invokes the execute() method on the Command object.
  • 5. As part of its implementation of the execute method, a typical Command object invokes necessary methods on the Receiver objects it contains to provide the required service to its caller.

In the new design:


  • The client/invoker does not directly interact with Receiver objects and therefore, they are completely decoupled from each other.
  • When the application needs to offer a new feature, a new Command object can be added. This does not require any changes to the code of the invoker. Hence the new design conforms to the open-closed principle.
  • Because the request is designed in the form of an object, it opens up a whole new set of possibilities such as:

  • (1) – Storing a Command object to persistent media:

    – To be executed later.
    – To apply reverse processing to support the undo feature.

    (2) Grouping together different Command objects to be executed as a single unit.


Example


Let us build an application that simulates the working of an FTP client. In Java, a simple FTP client user interface can be designed using:

  • Two JList objects for the local and remote file systems display
  • Four JButton objects for initiating different types of requests such as upload, download, delete and exit

(command_pattern_gui_example)


Let us define an abstraction in the form of a CommandInterface interface for the functionality associated with different button objects in the FTP client UI for avoiding inelegant conditional statements and as more button and menu item objects are added to the FTP UI.
       interface CommandInterface {
 public void processEvent();
}

Different button objects themselves can implement this interface and behave as individual command objects. But this is not recommended as: so lets define it as follows.


(button_class_hirachy)


The FTP UI can be built using objects of this new set of JButton subclasses. The rest of the application remains unchanged and the actionPerformed method gets highly simplified to a mere two lines of code.

class buttonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
   CommandInterface CommandObj =
           (CommandInterface) e.getSource();
   CommandObj.processEvent();
}
}

In the new design whenever a new button or a menu item is to be added, a new Command object needs to be created as an implementer of the CommandInterface. The new Command object can be added to the application in a seamless manner without requiring changes to the existing actionPerformed method code. On the negative side, this results in a larger number of classes.

  class DownloadButton extends JButton
implements CommandInterface {
  public void processEvent() {
    int index = remoteList.getSelectedIndex();
    String selectedItem =
      remoteList.getSelectedValue().toString();
    ((DefaultListModel) remoteList.getModel()).remove(
      index);

    ((DefaultListModel) localList.getModel()).addElement(
      selectedItem);
  }
  public DownloadButton(String name) {
    super(name);
  }
}


Example 2

Let us build an application to manage items in a library item database. Typical library items include books, CDs, videos and DVDs. These items are grouped into categories and a given item can belong to one or more categories. For example, a new movie video may belong to both the Video category and the NewReleases category.

Let us define two classes Item and Category

let us suppose that the library item management application deals only with adding and deleting items. Applying the Command pattern, the action to be taken to process add item and delete item requests can be designed as implementers of a common CommandInterface interface.



The CommandInterface implementers AddCommand and DeleteCommand

(command_library_system_classes)


(command_library_system_seq)