hierarchy of applet class in java - yolakavediasir.yolasite.com/resources/hierarchy of applet...

43
Hierarchy of Applet Class IN java Random Access File IN java The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file system.Instances of this class support both reading and writing to a random access file. Class constructors S.N. Constructor & Description 1 RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. 2 RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and

Upload: others

Post on 15-Jul-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Hierarchy of Applet Class IN java

Random Access File IN javaThe Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file system.Instances of this class support both reading and writing to a random access file.

Class constructorsS.N. Constructor & Description

1RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

2RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Class methodsS.N. Method & Description

Page 2: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

1void close()   This method Closes this random access file stream and releases any system resources associated with the stream.

2FileChannel getChannel()   This method returns the unique FileChannel object associated with this file.

3FileDescriptor getFD()   This method returns the opaque file descriptor object associated with this stream.

4 long getFilePointer()   This method returns the current offset in this file.

5 long length()   This method returns the length of this file.

6 int read()   This method reads a byte of data from this file.

7int read(byte[] b)   This method reads up to b.length bytes of data from this file into an array of bytes.

8int read(byte[] b, int off, int len)   This method reads up to len bytes of data from this file into an array of bytes.

9 boolean readBoolean()   This method reads a boolean from this file.

10 byte readByte()   This method reads a signed eight-bit value from this file.

11 char readChar()   This method reads a character from this file.

12 double readDouble()   This method reads a double from this file.

13 float readFloat()   This method reads a float from this file.

14void readFully(byte[] b)   This method reads b.length bytes from this file into the byte array, starting at the current file pointer.

15void readFully(byte[] b, int off, int len)   This method reads exactly len bytes from this file into the byte array, starting at the current file pointer.

Page 3: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

16 int readInt()   This method reads a signed 32-bit integer from this file.

17 String readLine()   This method reads the next line of text from this file.

18 long readLong()   This method reads a signed 64-bit integer from this file.

19 short readShort()   This method reads a signed 16-bit number from this file.

20 int readUnsignedByte()   This method reads an unsigned eight-bit number from this file.

21 int readUnsignedShort()   This method reads an unsigned 16-bit number from this file.

22 String readUTF()   This method reads in a string from this file.

23void seek(long pos)   This method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

24 void setLength(long newLength)   This method sets the length of this file.

25int skipBytes(int n)   This method attempts to skip over n bytes of input discarding the skipped bytes.

26void write(byte[] b)   This method writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

27void write(byte[] b, int off, int len)   This method writes len bytes from the specified byte array starting at offset off to this file.

28 void write(int b)   This method writes the specified byte to this file..

29 void writeBoolean(boolean v)   This method writes a boolean to the file as a one-byte value.

30 void writeByte(int v)   This method writes a byte to the file as a one-byte value.

31 void writeBytes(String s)   This method writes the string to the file as a sequence of bytes.

Page 4: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

32void writeChar(int v)   This method writes a char to the file as a two-byte value, high byte first.

33 void writeChars(String s)   This method writes a string to the file as a sequence of characters.

34void writeDouble(double v)   This method converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.

35void writeFloat(float v)   This method converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.

36 void writeInt(int v)   This method writes an int to the file as four bytes, high byte first.

37 void writeLong(long v)   This method writes a long to the file as eight bytes, high byte first.

38 void writeShort(int v)   This method writes a short to the file as two bytes, high byte first.

39void writeUTF(String str)   This method writes a string to the file using modified UTF-8 encoding in a machine-independent manner.

Creating a RandomAccessFile

Before you can work with the RandomAccessFile class you must instantiate it. Here is how that looks:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

Notice the second input parameter to the constructor: "rw". This is the mode you want to open file in. "rw" means read/write mode. Check the JavaDoc for more details about what modes you can open a RandomAccessFile in.

Page 5: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Moving Around a RandomAccessFile

To read or write at a specific location in a RandomAccessFile you must first position the file pointer at the location to read or write. This is done using the seek() method. The current position of the file pointer can be obtained by calling thegetFilePointer() method.

Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.seek(200);

long pointer = file.getFilePointer();

file.close();

Reading from a RandomAccessFile

Reading from a RandomAccessFile is done using one of its many read() methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

int aByte = file.read();

file.close();

Page 6: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

The read() method reads the byte located a the position in the file currently pointed to by the file pointer in theRandomAccessFile instance.

Here is a thing the JavaDoc forgets to mention: The read() method increments the file pointer to point to the next byte in the file after the byte just read! This means that you can continue to call read() without having to manually move the file pointer.

Writing to a RandomAccessFile

Writing to a RandomAccessFile can be done using one it its many write() methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.write("Hello World".getBytes());

file.close();

Just like with the read() method the write() method advances the file pointer after being called. That way you don't have to constantly move the file pointer to write data to a new location in the file.

RandomAccessFile Exception Handling

The proper exception handling of a RandomAccessFile is left out of this text for clarity. However, aRandomAccessFile must be closed properly after use, just like with a stream or reader / writer. To lean more, see the text Java IO Exception Handling.

Example ava RandomAccessFile provides facility to read and write data to a file. RandomAccessFile works with file as large array of bytes and a cursor using which we can move the file pointer position.

Page 7: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

While creating the instance of RandomAccessFile, we need to provide the mode of the file, for example “r” if you only want to read the file and “rw” if you want to read and write to the file.

Using file pointer, we can read or write data from random access file at any position. To get the current file pointer, you can call getFilePointer() method and to set the file pointer index, you can call seek(int i) method.If we write data at any index where data is already present, it will override it.

Here is a simple java random access file example.

 import java.io.IOException;import java.io.RandomAccessFile; public class RandomAccessFileExample {     public static void main(String[] args) {        try {            String filePath = "/Users/pankaj/source.txt";            System.out.println(new String(readCharsFromFile(filePath, 1, 5)));                         writeData(filePath, "Data", 5);        } catch (IOException e) {            e.printStackTrace();        }    }     private static void writeData(String filePath, String data, int seek) throws IOException {        RandomAccessFile file = new RandomAccessFile(filePath, "rw");        file.seek(seek);        file.write(data.getBytes());        file.close();    }     private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException {        RandomAccessFile file = new RandomAccessFile(filePath, "r");

Page 8: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

        file.seek(seek);        byte[] bytes = new byte[chars];        file.read(bytes);        file.close();        return bytes;    } }

FILE classJava File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc.The File object represents the actual file/directory on the disk. There are following constructors to create a File object:Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.File(File parent, String child);Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.File(String pathname) Following syntax creates a new File instance from a parent pathname string and a child pathname string.File(String parent, String child) Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.File(URI uri) Once you have File object in hand then there is a list of helper methods which can be used manipulate the files.SN Methods with Description

1public String getName()Returns the name of the file or directory denoted by this abstract pathname.

2public String getParent()Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

3public File getParentFile()Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Page 9: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

4 public String getPath()Converts this abstract pathname into a pathname string.

5public boolean isAbsolute()Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise

6public String getAbsolutePath()Returns the absolute pathname string of this abstract pathname.

7

public boolean canRead()Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise.

8

public boolean canWrite()Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.

9public boolean exists()Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise

10public boolean isDirectory()Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.

11

public boolean isFile()Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.

12

public long lastModified()Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.

Page 10: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

13public long length()Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

14

public boolean createNewFile() throws IOExceptionAtomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.

15

public boolean delete()Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.

16public void deleteOnExit()Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

17public String[] list()Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

18public String[] list(FilenameFilter filter)Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

20public File[] listFiles()Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

21public File[] listFiles(FileFilter filter)Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

22public boolean mkdir()Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.

23

public boolean mkdirs()Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.

Page 11: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

24public boolean renameTo(File dest)Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise.

25public boolean setLastModified(long time)Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise.

26public boolean setReadOnly()Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.

27

public static File createTempFile(String prefix, String suffix, File directory) throws IOExceptionCreates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.

28

public static File createTempFile(String prefix, String suffix) throws IOExceptionCreates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.

29

public int compareTo(File pathname)Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.

30

public int compareTo(Object o)Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.

31

public boolean equals(Object obj)Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.

Page 12: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

32public String toString()Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.

Following is the example to demonstrate File object:package com.tutorialspoint;

import java.io.File;

public class FileDemo { public static void main(String[] args) { File f = null; String[] strs = {"test1.txt", "test2.txt"}; try{ // for each string in string array for(String s:strs ) { // create new file f= new File(s); // true if the file is executable boolean bool = f.canExecute(); // find the absolute path String a = f.getAbsolutePath(); // prints absolute path System.out.print(a); // prints System.out.println(" is executable: "+ bool); } }catch(Exception e){ // if any I/O error occurs e.printStackTrace(); } }}Consider there is an executable file test1.txt and another file test2.txt is non executable in current directory, Let us compile and run the above program, this will produce the following result:test1.txt is executable: truetest2.txt is executable: false

Page 13: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Examples and Sample Code of File ClassThe File class in the Java IO API gives you access to the underlying file system. Using the File class you can:Check if a file exists.Read the length of a file.Rename or move a file.Delete a file.Check if path is file or directory.Read list of files in a directory.

This text will tell you more about how.Note: The File only gives you access to the file and file system meta data. If you need to read or write the content of files, you should do so using either FileInputStream, FileOutputStream or RandomAccessFile.Note: If you are using Java NIO you will have to use the java.nio.FileChannel class instead (you can use both, but in case you want a pure Java NIO solution).

Instantiating a java.io.FileBefore you can do anything with the file system or File class, you must obtain a File instance. Here is how that is done:File file = new File("c:\\data\\input-file.txt");Simple, right? The File class also has a few other constructors you can use to instantiate File instances in different ways.

Check if File ExistsOnce you have instantiated a File object you can check if the corresponding file actually exists already. The File class constructor will not fail if the file does not already exists. You might want to create it now, right?

To check if the file exists, call the exists() method. Here is a simple example:File file = new File("c:\\data\\input-file.txt");

boolean fileExists = file.exists();File Length

To read the length of a file in bytes, call the length() method. Here is a simple example:File file = new File("c:\\data\\input-file.txt");

long length = file.length();Rename or Move File

Page 14: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

To rename (or move) a file, call the method renameTo() on the File class. Here is a simple example:File file = new File("c:\\data\\input-file.txt");

boolean success = file.renameTo(new File("c:\\data\\new-file.txt"));As briefly mentioned earlier, the renameTo() method can also be used to move a file to a different directory. The new file name passed to the renameTo() method does not have to be in the same directory as the file was already residing in.

The renameTo() method returns boolean (true or false), indicating whether the renaming was successful. Renaming of moving a file may fail for various reasons, like the file being open, wrong file permissions etc.Delete File

To delete a file call the delete() method. Here is a simple example:File file = new File("c:\\data\\input-file.txt");

boolean success = file.delete();

The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc.Check if Path is File or DirectoryA File object can point to both a file or a directory.

You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returnstrue if the File points to a directory, and false if the File points to a file. Here is a simple example:File file = new File("c:\\data");

boolean isDirectory = file.isDirectory();

Read List of Files in DirectoryYou can obtain a list of all the files in a directory by calling either the list() method or the listFiles() method. Thelist() method returns an array of String's with the file and / or directory names of directory the File object points to. ThelistFiles() returns an array of File objects representing the files and / or directories in the directory the File points to.Here is a simple example:File file = new File("c:\\data");

Page 15: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

String[] fileNames = file.list();

File[] files = file.listFiles();

ExamplesExample of How to Create File in JavaHere is a simple example of how to create file in Java:

import java.io.*;

public class FileExample {

public static void main(String[] args) {boolean flag = false;

// create File objectFile stockFile = new File("d://Stock/stockFile.txt");

try {    flag = stockFile.createNewFile();} catch (IOException ioe) {     System.out.println("Error while Creating File in Java" + ioe);}

System.out.println("stock file" + stockFile.getPath() + " created ");

}}

In this example of creating File in Java we have created one new file called stock file inside the stock directory on d drive first time when we execute this program it will check for the file if it will not get that file simply create the new file and flag will become true, next time when we again run this program the file is already get created inside d:\\stock folder so it will not create the file and flag value will be false.

Example of How to Create Directory in JavaJust like above example of creating file in Java we can create directory in Java, only difference is that we need to use mkdir() method to create directory in Java

import java.io.*;

public class DirectoryExample {

public static void main(String[] args) {

Page 16: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

boolean dirFlag = false;

// create File objectFile stockDir = new File("d://Stock/ stockDir ");

try {   dirFlag = stockDir.mkdir();} catch (SecurityException Se) {System.out.println("Error while creating directory in Java:" + Se);}

if (dirFlag)   System.out.println("Directory created successfully");else   System.out.println("Directory was not created successfully");}}

Synchronization Monitor and LOCK

A lock prevents more than one entity from accessing a shared resource. Each object in Java™ has an associated lock (gained by using a synchronized block or method). In the case of the JVM, threads compete for various resources in the JVM and locks on Java objects.

A monitor is a special kind of locking mechanism that is used in the JVM to allow flexible synchronization between threads. For the purpose of this section, read the terms monitor and lock interchangeably.

To avoid having a monitor on every object, the JVM usually uses a flag in a class or method block to indicate that the item is locked. Most of the time, a piece of code will transit some locked section without contention. Therefore, the guardian flag is enough to protect this piece of code. This is called a flat monitor. However, if another thread wants to access some code that is locked, a genuine contention has occurred. The JVM must now create (or inflate) the monitor object to hold the second thread and arrange for a signaling mechanism to coordinate access to the code section. This monitor is now called an inflated monitor.

Detailed Explaination (Nice)Thread Synchronization

One of the strengths of the Java programming language is its support for multithreading at the language level. Much of this support centers on synchronization: coordinating activities and data access among multiple threads. The mechanism that Java uses to support synchronization is the monitor. This chapter describes monitors and shows how they are used by the Java virtual machine. It describes how one aspect of monitors, the locking and unlocking of data, is supported in the instruction set.

Page 17: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Monitors

Java's monitor supports two kinds of thread synchronization: mutual exclusion and cooperation. Mutual exclusion, which is supported in the Java virtual machine via object locks, enables multiple threads to independently work on shared data without interfering with each other. Cooperation, which is supported in the Java virtual machine via the wait and notify methods of class Object, enables threads to work together towards a common goal.

A monitor is like a building that contains one special room that can be occupied by only one thread at a time. The room usually contains some data. From the time a thread enters this room to the time it leaves, it has exclusive access to any data in the room. Entering the monitor building is called "entering the monitor." Entering the special room inside the building is called "acquiring the monitor." Occupying the room is called "owning the monitor," and leaving the room is called "releasing the monitor." Leaving the entire building is called "exiting the monitor."

In addition to being associated with a bit of data, a monitor is associated with one or more bits of code, which in this book will be called monitor regions. A monitor region is code that needs to be executed as one indivisible operation with respect to a particular monitor. In other words, one thread must be able to execute a monitor region from beginning to end without another thread concurrently executing a monitor region of the same monitor. A monitor enforces this one-thread-at-a-time execution of its monitor regions. The only way a thread can enter a monitor is by arriving at the beginning of one of the monitor regions associated with that monitor. The only way a thread can move forward and execute the monitor region is by acquiring the monitor.

When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. The entry set is like the front hallway of the monitor building. If no other thread is waiting in the entry set and no other thread currently owns the monitor, the thread acquires the monitor and continues executing the monitor region. When the thread finishes executing the monitor region, it exits (and releases) the monitor.

If a thread arrives at the beginning of a monitor region that is protected by a monitor already owned by another thread, the newly arrived thread must wait in the entry set. When the current owner exits the monitor, the newly arrived thread must compete with any other

Page 18: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

threads also waiting in the entry set. Only one thread will win the competition and acquire the monitor.

The first kind of synchronization listed above, mutual exclusion, refers to the mutually exclusive execution of monitor regions by multiple threads. At any one time, only one thread can be executing a monitor region of a particular monitor. In general, mutual exclusion is important only when multiple threads are sharing data or some other resource. If two threads are not working with any common data or resource, they usually can't interfere with each other and needn't execute in a mutually exclusive way. On a Java virtual machine implementation that doesn't time slice, however, a higher priority thread that is never blocked will interfere with any lower priority threads, even if none of the threads share data. The higher priority thread will monopolize the CPU at the expense of the lower priority threads. Lower priority threads will never get any CPU time. In such a case, a monitor that protects no data may be used to orchestrate these threads to ensure all threads get some CPU time. Nevertheless, in most cases a monitor protects data that is accessed through the monitor region code. In cases where the data can be accessed only through the monitor regions, the monitor enforces mutually exclusive access to that data.

The other kind of synchronization listed above as supported by monitors is cooperation. Whereas mutual exclusion helps keep threads from interfering with one another while sharing data, cooperation helps threads to work together towards some common goal.

Cooperation is important when one thread needs some data to be in a particular state and another thread is responsible for getting the data into that state. For example, one thread, a "read thread," may be reading data from a buffer that another thread, a "write thread," is filling. The read thread needs the buffer to be in a "not empty" state before it can read any data out of the buffer. If the read thread discovers that the buffer is empty, it must wait. The write thread is responsible for filling the buffer with data. Once the write thread has done some more writing, the read thread can do some more reading.

The form of monitor used by the Java virtual machine is called a "Wait and Notify" monitor. (It is also sometimes called a "Signal and Continue" monitor.) In this kind of monitor, a thread that currently owns the monitor can suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it releases the monitor and enters a wait set. The thread will stay suspended in the wait set until some time after another thread executes a notify command inside the monitor. When a thread executes a notify, it

Page 19: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

continues to own the monitor until it releases the monitor of its own accord, either by executing a wait or by completing the monitor region. After the notifying thread has released the monitor, the waiting thread will be resurrected and will reacquire the monitor.

The kind of monitor used in the Java virtual machine is sometimes called a Signal and Continue monitor because after a thread does a notify (the signal) it retains ownership of the monitor and continues executing the monitor region (the continue). At some later time, the notifying thread releases the monitor and a waiting thread is resurrected. Presumably, the waiting thread suspended itself because the data protected by the monitor wasn't in a state that would allow the thread to continue doing useful work. Also, the notifying thread presumably executed the notify command after it had placed the data protected by the monitor into the state desired by the waiting thread. But because the notifying thread continued, it may have altered the state after the notify such that the waiting thread still can't do useful work. Alternatively, a third thread may have acquired the monitor after the notifying thread released it but before the waiting thread acquired it, and the third thread may have changed the state of the protected data. As a result, a notify must often be considered by waiting threads merely as a hint that the desired state may exist. Each time a waiting thread is resurrected, it may need to check the state again to determine whether it can move forward and do useful work. If it finds the data still isn't in the desired state, the thread could execute another wait or give up and exit the monitor.

As an example, consider once again the scenario described above that involves a buffer, a read thread, and a write thread. Assume the buffer is protected by a monitor. When a read thread enters the monitor that protects the buffer, it checks to see if the buffer is empty. If the buffer is not empty, the read thread reads (and removes) some data from the buffer. Satisfied, it exits the monitor. On the other hand, if the buffer is empty, the read thread executes a wait command. As soon as it executes the wait, the read thread is suspended and placed into the monitor's wait set. In the process, the read thread releases the monitor, which becomes available to other threads. At some later time, the write thread enters the monitor, writes some data into the buffer, executes a notify, and exits the monitor. When the write thread executes the notify, the read thread is marked for eventual resurrection. After the write thread has exited the monitor, the read thread is resurrected as the owner of the monitor. If there is any chance that some other thread has come along and consumed the data left by the write thread, the read thread must explicitly check to make sure the buffer is not empty. If there is no chance that any other thread has consumed the data, then the read thread can just assume

Page 20: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

the data exists. The read thread reads some data from the buffer and exits the monitor.

A graphical depiction of the kind of monitor used by a Java virtual machine is shown in Figure 20-1. This figure shows the monitor as three rectangles. In the center, a large rectangle contains a single thread, the monitor's owner. On the left, a small rectangle contains the entry set. On the right, another small rectangle contains the wait set. Active threads are shown as dark gray circles. Suspended threads are shown as light gray circles.

Figure 20-1 also shows several numbered doors that threads must "pass through" to interact with the monitor. When a thread arrives at the start of a monitor region, it enters the monitor via the leftmost door, door number one, and finds itself in the rectangle that houses the entry set. If no thread currently owns the monitor and no other threads are waiting in the entry set, the thread passes immediately through the next door, door number two, and becomes the owner of the monitor. As the monitor owner, the thread continues executing the monitor region. If, on the other hand, there is another thread currently claiming ownership of the monitor, the newly arrived thread must wait in the entry set, possibly along with other threads already waiting there. The newly arrived thread is blocked and therefore doesn't execute any further into the monitor region.

Page 21: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Figure 20-1 shows three threads suspended in the entry set and four threads suspended in the wait set. These threads will remain where they are until the current owner of the monitor--the active thread--releases the monitor. The active thread can release the monitor in either of two ways: it can complete the monitor region it is executing or it can execute a wait command. If it completes the monitor region, it exits the monitor via the door at the bottom of the central rectangle, door number five. If it executes a wait command, it releases the monitor as it travels through door number three, the door to the wait set.

If the former owner did not execute a notify before it released the monitor (and none of the waiting threads were previously notified and were waiting to be resurrected), then only the threads in the entry set will compete to acquire the monitor. If the former owner did execute a notify, then the entry set threads will have to compete with one or more threads from the wait set. If a thread from the entry set wins the competition, it passes through door number two and becomes the new owner of the monitor. If a thread from the wait set wins the competition, it exits the wait set and reacquires the monitor as it passes through door number four. Note that doors three and four are the only ways a thread can enter or exit the wait set. A thread can only execute a wait command if it currently owns the monitor, and it can't leave the wait set without automatically becoming again the owner of the monitor.

In the Java virtual machine, threads can optionally specify a timeout when they execute a wait command. If a thread does specify a timeout, and no other thread executes a notify before the timeout expires, the waiting thread in effect receives an automatic notify from the virtual machine. After the timeout expires, the waiting thread will be resurrected even if no other thread has executed an explicit notify.

The Java virtual machine offers two kinds of notify commands: "notify" and "notify all." A notify command selects one thread arbitrarily from the wait set and marks it for eventual resurrection. A notify all command marks all threads currently in the wait set for eventual resurrection.

To a great extent, the manner in which a Java virtual machine implementation selects the next thread from the wait or entry sets is a decision of individual implementation designers. For example, implementation designers can decide how to select: o a thread from the wait set given a notify command o the order to resurrect threads from the wait set given a notify all command o the order to allow threads from the entry set to acquire the monitor o how to choose

Page 22: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

between threads suspended in the wait set versus the entry set after a notify command You might think it would make sense to implement entry set and wait sets as first-in-first-out (FIFO) queues, so that the thread that waits the longest will be the first chosen to acquire the monitor. Alternatively, it might make sense to have ten FIFO queues, one for each priority a thread can have inside the Java virtual machine. The virtual machine could then choose the thread that has been waiting the longest in the highest priority queue that contains any waiting threads. Implementations may take approaches such as these, but you can't depend on it. Implementations are free to implement the entry and wait sets as last-in-first-out (LIFO) queues, to select lower priority threads before higher priority threads, or to do anything else that may not seem to make sense. In short, implementations are free to select threads in an arbitrary manner that defies analysis and yields surprising orderings.

As a programmer, you must not rely on any particular selection algorithm or treatment of priorities, at least if you are trying to write a Java program that is platform independent. For example, because you don't know what order threads in the wait set will be chosen for resurrection by the notify command, you should use notify (as opposed to notify all) only when you are absolutely certain there will only be one thread suspended in the wait set. If there is a chance more than one thread will be suspended in the wait set at any one time, you should probably use notify all. Otherwise, on some Java virtual machine implementations a particular thread may be stuck in the wait set for a very long time. If a notify always selects the most recent arrival from the wait set and the wait set always contains multiple threads, some threads that have been waiting the longest may never be resurrected.

Synchronization Support in the Instruction SetAs mentioned earlier, the language provides two built-in ways to identify monitor regions in your programs: synchronized statements and synchronized methods. These two mechanisms, which implement the mutual exclusion aspect of synchronization, are supported by the Java virtual machine's instruction set.

Synchronized Statements

Page 23: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

To create a synchronized statement, you use the synchronized keyword with an expression that evaluates to an object reference, as in the reverseOrder() method below:

// On CD-ROM in file threads/ex1/KitchenSync.javaclass KitchenSync {

private int[] intArray = new int[10];

void reverseOrder() { synchronized (this) { int halfWay = intArray.length / 2; for (int i = 0; i < halfWay; ++i) { int upperIndex = intArray.length - 1 - i; int save = intArray[upperIndex]; intArray[upperIndex] = intArray[i]; intArray[i] = save; } } } // ...}

In the above case, the statements contained within the synchronized block will not be executed until a lock is acquired on the current object (this). If instead of a this reference, the expression yielded a reference to another object, the lock associated with that object would be acquired before the thread continued. If the expression yields a reference to an instance of class Class, the lock associated with the class is acquired.

Inter Thread CommunicationJava - Interthread CommunicationIf you are aware of interprocess communication then it will be easy for you to understand inter thread communication. Inter thread communication is important when you develop an application where two or more threads exchange some information.

There are simply three methods and a little trick which makes thread communication possible. First let's see all the three methods listed below:

S Methods with Description

Page 24: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

N

1public void wait()Causes the current thread to wait until another thread invokes the notify().

2public void notify()Wakes up a single thread that is waiting on this object's monitor.

3 public void notifyAll()Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.Example:This examples shows how two thread can communicate using wait() and notify() method. You can create a complex system using the same concept.class Chat { boolean flag = false; public synchronized void Question(String msg) { if (flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = true; notify(); } public synchronized void Answer(String msg) { if (!flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = false;

Page 25: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

notify(); }}class T1 implements Runnable { Chat m; String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" }; public T1(Chat m1) { this.m = m1; new Thread(this, "Question").start(); } public void run() { for (int i = 0; i < s1.length; i++) { m.Question(s1[i]); } }}class T2 implements Runnable { Chat m; String[] s2 = { "Hi", "I am good, what about you?", "Great!" }; public T2(Chat m2) { this.m = m2; new Thread(this, "Answer").start(); } public void run() { for (int i = 0; i < s2.length; i++) { m.Answer(s2[i]); } }}public class TestThread { public static void main(String[] args) { Chat m = new Chat(); new T1(m); new T2(m); }}

When above program is complied and executed, it produces following result:

Page 26: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

HiHiHow are you ?I am good, what about you?I am also doing fine!Great!

Page 27: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:

wait() notify() notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException

waits until object is notified.

public final void wait(long timeout)throws InterruptedException

waits for the specified amount of time.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:

Page 28: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.2. Lock is acquired by on thread.3. Now thread goes to waiting state if you call wait() method on the

object. Otherwise it releases the lock and exits.4. If you call notify() or notifyAll() method, thread moves to the

notified state (runnable state).5. Now thread is available to acquire lock.6. After completion of the task, thread releases the lock and exits

the monitor state of the object.

Page 29: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() methods

after the specified amount of time, sleep is completed.

Example of inter thread communication in java

Let's see the simple example of inter thread communication.

class Customer{  int amount=10000;    synchronized void withdraw(int amount){  System.out.println("going to withdraw...");    if(this.amount<amount){  System.out.println("Less balance; waiting for deposit...");  try{wait();}catch(Exception e){}  }  this.amount-=amount;  System.out.println("withdraw completed...");  

Page 30: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

}    synchronized void deposit(int amount){  System.out.println("going to deposit...");  this.amount+=amount;  System.out.println("deposit completed... ");  notify();  }  }    class Test{  public static void main(String args[]){  final Customer c=new Customer();  new Thread(){  public void run(){c.withdraw(15000);}  }.start();  new Thread(){  public void run(){c.deposit(10000);}  }.start();    }}  

Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed

Difference between multitasking multiprogramming and multithreading?

Multiprogramming is a rudimentary form of parallel processing in which several programs are run at the same time on a uniprocessor.Since there is only one processor, there can be no true simultaneous execution of different programs. Instead, the operating system executes part of one program, then part of another, and so on. To the user it appears that all programs are executing at the same time.

Multitasking, in an operating system, is allowing a user to perform more than one computer task (such as the operation of an application program) at a time. The operating system is able to keep track of where you are in these tasks and go from one to the other without losing information

Page 31: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

Multithreading is the ability of a program or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the program running in the computerUnderstands the difference between multi processing and multi threading

Multithreading and multiprocessing, both refer to the ability of doing multiple things within a context. Multiprocessing refers to the ability to run multiple programs (or processes) simultaneously within one operating system. Multithreading on the other hand refers to the ability to run multiple threads simultaneously within a process.

When we run a browser, an email client, and a word processor simultaneously on the same operating system, it is an example of multiprocessing. However, each of these processes, can have multiple threads, which may be run simultaneously within that process.

Typically, multiprocessing allows us to run multiple programs at the same time, and multithreading helps us in making our programs more efficient and responsive.

Multiprogramming 

In multiprogramming more than one program reside in the main memory. When one job is unable to execute because of I/O operation to complete , it switches to other program and allow that program to run .

 

Page 32: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

As you can see in above figure there are three program in the main memory but only one programming is running(or one program is assigned to CPU) at a time .The main motive of multiprogramming is to utilize the CPU efficiently. 

Multitasking(Time shared)

In multitasking operating system more than one program is assigned to the CPU or switches between the program occurs so fast that it seems like more than one program is running . In multitasking more than program is assigned to CPU at the same time. The main motive of multitasking is to utilize the CPU efficiently and reduce the response time.    

Multiprocessing

In multiprocessing operating system a task is divided between more than one processor(CPU) so that parallelism can be achieved.    

Multithreading 

Sometime a program need to do multiple task at the same time. It is an extension of multiprogramming . In multi threading the program is divided into multiple task .

Various Level of Access Protection available for PackageJava provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

Visible to the package. the default. No modifiers are needed.

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Default Access Modifier - No keyword:Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

Page 33: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

Example:Variables and methods can be declared without any modifiers, as in the following examples:

String version = "1.5.1";boolean processOrder() { return true;}Private Access Modifier - private:Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:The following class uses private access control:

public class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; }}Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.

Page 34: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.Public Access Modifier - public:A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However if the public class we are trying to access is in a different package, then the public class still need to be imported.

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example:The following function uses public access control:

public static void main(String[] arguments) { // ...}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example:The following parent class uses protected access control, to allow its child class override openSpeaker()method:class AudioPlayer { protected boolean openSpeaker(Speaker sp) {

Page 35: Hierarchy of Applet Class IN java - Yolakavediasir.yolasite.com/resources/Hierarchy of Applet Cla…  · Web viewRandomAccessFile Exception Handling. The proper exception handling

// implementation details }}class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { // implementation details }}Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.Access Control and Inheritance:The following rules for inherited methods are enforced:

Methods declared public in a superclass also must be public in all subclasses.

Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.

Methods declared without access control (no modifier was used) can be declared more private in subclasses.

Methods declared private are not inherited at all, so there is no rule for them.