It 2 Mark
It 2 Mark
It 2 Mark
1)Why java is a platform independent language? Java was never just a language. There are lots of programming languages out there, and few of them make much of a splash. Java is a whole platform, with a huge library, containing lots of reusable code, and an execution environment that provides services such as security, portability across operating systems, and automatic garbage collection.
2)List out the advantages of java? Simple Portable Object Oriented Interpreted Network-Savvy High Performance Robust
Multithreaded Secure Dynamic Architecture Neutral 3)case sensitive? The standard naming convention (which we follow in the name FirstSample) is that class names are nouns that start with an uppercase letter. If a name consists of multiple words, use an initial uppercase letter in each of the words. (This use of uppercase letters in the middle of a word is sometimes called camel case or, self-referentially, CamelCase.) 4)what are the primitives available in java? There are eight primitive types in Java int 4 bytes short 2 bytes long 8 bytes byte 1 byte float 4 bytes double 8 bytes char 2 bytes Boolean 5)why Strings are immutable? The String class gives no methods that let you change a character in an existing string. If you want to turn greeting into "Help!", you cannot directly change the last positions of greeting into 'p' and '!'. If you are a C programmer, this will make you feel pretty helpless. How are you going to modify the string? In Java, it is quite easy: Concatenate the substring that you want to keep with the characters that you want to replace. greeting = greeting.substring(0, 3) + "p!"; This declaration changes the current value of the greeting variable to "Help!". 6)why java does not have a multidimensional array. Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as arrays of arrays.
7)how to identify three key characteristics of objects. The objects behaviorWhat can you do with this object, or what methods can you apply to it? The objects stateHow does the object react when you apply those methods? The objects identityHow is the object distinguished from others that may have the same behavior and state? 8)relationship between classes. Relationships between Classes The most common relationships between classes are Dependence (usesa) Aggregation (hasa) Inheritance (isa)
9)Define class. all code that you write in Java is inside a class Ther e are two types i)user defined class and pre defined class i)user defined class A class is the template or blueprint from which objects are made.When you construct an object from a class, you are said to have created an instance of the class. ii)pre defined class The standard Java library supplies several thousand classes for such diverse purposes as user interface design, dates and calendars, and network programming.
10)define constructor. A constructor has the same name as the class. A class can have more than one constructor. A constructor can take zero, one, or more parameters. A constructor has no return value. A constructor is always called with the new operator.
11)Static Fields If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. 12) Static Methods Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression Math.pow(x, a) computes the power xa. It does not use any Math object to carry out its task. In other words, it has no implicit parameter. You can think of static methods as methods that dont have a this parameter. (In a nonstatic method, the this parameter refers to the implicit parameter of the methodsee the section Implicit and Explicit Parameters on page 127.) Because static methods dont operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method: public static int getNextId() { return nextId; // returns static field } To call this method, you supply the name of the class: int n = Employee.getNextId(); Could you have omitted the keyword static for this method? Yes, but then you would need to have an object reference of type Employee to invoke the method. 13) use static methods in two situations: When a method doesnt need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow) When a method only needs to access static fields of the class (example: Employee.getNextId 14) Object Destruction and the finalize Method notably C++, have explicit destructor methods for any cleanup code that may be needed when an object is no longer used. The most common activity in a destructor is reclaiming the memory set aside for objects. Because Java does automatic garbage collection, manual memory reclamation is not needed and so Java does not support destructors. You can add a finalize method to any class. The finalize method will be called before the
garbage collector sweeps away the object. In practice, do not rely on the finalize method for recycling any resources that are in short supplyyou simply cannot know when this method will be called. 15) Packages. Java allows you to group classes in a collection called a package. Packages are convenient for organizing your work and for separating your work from code libraries provided by others. The standard Java library is distributed over a number of packages, including java.lang, java.util, java.net, and so on. The standard Java packages are examples of hierarchical packages. Just as you have nested subdirectories on your hard disk, you can organize packages by using levels of nesting. All standard Java packages are inside the java and javax package hierarchies. 16)Class Importation A class can use all classes from its own package and all public classes from other packages. You can access the public classes in another package in two ways. The first is simply to add the full package name in front of every class name. For example: java.util.Date today = new java.util.Date(); That is obviously tedious. The simpler, and more common, approach is to use the import statement. The point of the import statement is simply to give you a shorthand to refer to the classes in the package. Once you use import, you no longer have to give the classes their full names. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement import java.util.*; Then you can use Date today = new Date(); without a package prefix. You can also import a specific class inside a package: import java.util.Date; The java.util.* syntax is less tedious. It has no negative effect on code size 17)Package Scope You have already encountered the access modifiers public and private. Features tagged as public can be used by any class. Private features can be used only by the class that defines them. If you dont specify either public or private, the feature (that is, the class,
method, or variable) can be accessed by all methods in the same package. 18)Comment Insertion The javadoc utility extracts information for the following items: Packages Public classes and interfaces Public and protected methods Public and protected fields 19)what is meant by inheritance in java. The keyword extends indicates that you are making a new class that derives from an existing class. The existing class is called the superclass, base class, or parent class. The new class is called the subclass, derived class, or child class. The terms superclass and subclass are those most commonly used by Java programmers,java supports only two types of inheritance they are i)single ii)multilevel 19)Define polymorphism. The fact that an object variable (such as the variable e) can refer to multiple actual types is called polymorphism. Automatically selecting the appropriate method at runtime is dynamic binding 20)Dynamic Binding It is important to understand what happens when a method call is applied to an object. Here are the details: 1. The compiler looks at the declared type of the object and the method name. Lets say we call x.f(param), and the implicit parameter x is declared to be an object of class C. Note that there may be multiple methods, all with the same name, f, but with different parameter types. For example, there may be a method f(int) and a method f(String). The compiler enumerates all methods called f in the class C and all public methods called f in the superclasses of C. Now the compiler knows all possible candidates for the method to be called. If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. (The final modifier is explained in the next section.) This is called static binding. Otherwise, the method to be called depends on the actual type of the implicit parameter, and dynamic binding must be used at runtimeruntime. In our example, the compiler would generate an instruction to call f(String) with dynamic binding. 21)Preventing Inheritance: Final Classes and Methods Occasionally, you want to prevent someone from forming a subclass from one of your
classes. Classes that cannot be extended are called final classes, and you use the final modifier in the definition of the class to indicate this. For example, let us suppose we want to prevent others from subclassing the Executive class. Then, we simply declare the class by using the final modifier as follows: final class Executive extends Manager { ... } You can also make a specific method in a class final. If you do this, then no subclass can override that method. (All methods in a final class are automatically final.) For example: class Employee { ... public final String getName() { return name; } ... } 22) Abstract Classes A class can even be declared as abstract even though it has no abstract methods. Abstract classes cannot be instantiated. That is, if a class is declared as abstract, no objects of that class can be created. you can create objects of concrete subclasses. Note that you can still create object variables of an abstract class, but such a variable must refer to an object of a nonabstract subclass. For example: Person p = new Student("Vince Vu", "Economics"); Here p is a variable of the abstract type Person that refers to an instance of the nonabstract subclass Student. 23) Here is a summary of the four access modifiers in Java that control visibility: 1. Visible to the class only (private). 2. Visible to the world (public). 3. Visible to the package and all subclasses (protected). 4. Visible to the packagethe (unfortunate) default. No modifiers are needed. 23) The equals Method The equals method in the Object class tests whether one object is considered equal to another.
The equals method, as implemented in the Object class, determines whether two object references are identical. This is a pretty reasonable defaultif two objects are identical, they should certainly be equal. 24) requires that the equals method has the following properties: 1. It is reflexive: For any non-null reference x, x.equals(x) should return true. 2. It is symmetric: For any references x and y, x.equals(y) should return true if and only if y.equals(x) returns true. 3. It is transitive: For any references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. 4. It is consistent: If the objects to which x and y refer havent changed, then repeated calls to x.equals(y) return the same value. 5. For any non-null reference x, x.equals(null) should return false. 25)Wrapper class. Occasionally, you need to convert a primitive type like int to an object. All primitive types have class counterparts. For example, a class Integer corresponds to the primitive type int. These kinds of classes are usually called wrappers. The wrapper classes have obvious names: Integer, Long, Float, Double, Short, Byte, Character, Void, and Boolean. (The first six inherit from the common superclass Number.) The wrapper classes are immutableyou cannot change a wrapped value after the wrapper has been constructed. They are also final, so you cannot subclass them. 26)Reflection The reflection library gives you a very rich and elaborate toolset to write programs that manipulate Java code dynamically. A program that can analyze the capabilities of classes is called reflective. The reflection mechanism is extremely powerful. As the next sections show, you can use it to Analyze the capabilities of classes at runtime; Inspect objects at runtime, for example, to write a single toString method that works for all classes; Implement generic array manipulation code; and Take advantage of Method objects that work just like function pointers in languages such as C++. 27)Types of exception. There are two kinds of exceptions: unchecked exceptions and checked exceptions. With checked exceptions, the compiler checks that you provide a handler. However, many common exceptions, such as accessing a null reference, are unchecked. The compiler does not check whether you provide a handler for these errorsafter all, you should
spend your mental energy on avoiding these mistakes rather than coding handlers for them.
28)define interface in java. Interface is a keyword. A class can implement one or more interfaces. You can then use objects of these implementing classes anytime that conformance to the interface is required. After we cover interfaces,Interface contain both abstract and non abstract method. All methods of an interface are automatically public. For that reason, it is not necessary to supply the keyword public when declaring a method in an interface. The variables in interface are public static final by default and the methods are public static by default.. 29) To make a class implement an interface, you carry out two steps: 1. You declare that your class intends to implement the given interface. 2. You supply definitions for all methods in the interface. 29) Properties of Interfaces Interfaces are not classes. In particular, you can never use the new operator to instantiate an interface: x = new Comparable(. . .); // ERROR However, even though you cant construct interface objects, you can still declare interface variables. Comparable x; // OK An interface variable must refer to an object of a class that implements the interface: x = new Employee(. . .); // OK provided Employee implements Comparable Next, just as you use instanceof to check whether an object is of a specific class, you can use instanceof to check whether an object implements an interface: if (anObject instanceof Comparable) { . . . } Just as you can build hierarchies of classes, you can extend interfaces. This allows for multiple chains of interfaces that go from a greater degree of generality to a greater degree of specialization. For example, suppose you had an interface called Moveable. public interface Moveable { void move(double x, double y); } Then, you could imagine an interface called Powered that extends it: public interface Powered extends Moveable { double milesPerGallon(); }
Although you cannot put instance fields or static methods in an interface, you can supply constants in them. For example: public interface Powered extends Moveable { double milesPerGallon(); double SPEED_LIMIT = 95; // a public static final constant } Just as methods in an interface are automatically public, fields are always public static final. 30)clone method. Quite frequently, however, subobjects are mutable, and you must redefine the clone method to make a deep copy that clones the subobjects as well. In our example, the hireDay field is a Date, which is mutable. For every class, you need to decide whether 1. The default clone method is good enough; 2. The default clone method can be patched up by calling clone on the mutable subobjects; and 3. clone should not be attempted. The third option is actually the default. To choose either the first or the second option, a class must 1. Implement the Cloneable interface; and 2. Redefine the clone method with the public access modifier. 31)Inner Classes An inner class is a class that is defined inside another class. Why would you want to do that? There are three reasons: Inner class methods can access the data from the scope in which they are defined including data that would otherwise be private. Inner classes can be hidden from other classes in the same package. Anonymous inner classes are handy when you want to define callbacks without writing a lot of code. 32) Special Syntax Rules for Inner Classes In the preceding section, we explained the outer class reference of an inner class by calling it outer. Actually, the proper syntax for the outer reference is a bit more complex. The expression OuterClass.this denotes the outer class reference. For example, you can write the actionPerformed method of the TimePrinter inner class as public void actionPerformed(ActionEvent event) {
... if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep(); } Conversely, you can write the inner object constructor more explicitly, using the syntax outerObject.new InnerClass(construction parameters) For example: ActionListener listener = this.new TimePrinter(); Here, the outer class reference of the newly constructed TimePrinter object is set to the this reference of the method that creates the inner class object. This is the most common case. As always, the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicitly naming it. For example, because TimePrinter is a public inner class, you can construct a TimePrinter for any talking clock: TalkingClock jabberer = new TalkingClock(1000, true); TalkingClock.TimePrinter listener = jabberer.new TimePrinter(); Note that you refer to an inner class as OuterClass.InnerClass 33)Static Inner Classes Occasionally, you want to use an inner class simply to hide one class inside another, but you dont need the inner class to have a reference to the outer class object. You can suppress the generation of that reference by declaring the inner class static. 34)proxy. To overcome this problem, some programs generate code, place it into a file, invoke the compiler, and then load the resulting class file. Naturally, this is slow, and it also requires deployment of the compiler together with the program. The proxy mechanism is a better solution. The proxy class can create brand-new classes at runtime. Such a proxy class implements the interfaces that you specify. In particular, the proxy class has the following methods: All methods required by the specified interfaces; and All methods defined in the Object class (toString, equals, and so on). 35)advantages of swing Swing has a rich and convenient set of user interface elements. Swing has few dependencies on the underlying platform; it is therefore less prone to platform-specific bugs. Swing gives a consistent user experience across platforms. 36)how event handling in the AWT works: A listener object is an instance of a class that implements a special interface called (naturally enough) a listener interface.
An event source is an object that can register listener objects and send them event objects. The event source sends out event objects to all registered listeners when that event occurs. The listener objects will then use the information in the event object to determine their reaction to the event. 37)Adapter Classes Not all events are as simple to handle as button clicks. In a non-toy program, you will want to monitor when the user tries to close the main frame because you dont want your users to lose unsaved work. When the user closes the frame, you want to put up a dialog and exit the program only when the user agrees. When the program user tries to close a frame window, the JFrame object is the source of a WindowEvent. If you want to catch that event, you must have an appropriate listener object and add it to the frames list of window listeners. 38) Actions It is common to have multiple ways to activate the same command. The user can choose a certain function through a menu, a keystroke, or a button on a toolbar. This is easy to achieve in the AWT event model: link all events to the same listener. For example, suppose blueAction is an action listener whose actionPerformed method changes the background color to blue. You can attach the same object as a listener to several event sources: A toolbar button labeled Blue A menu item labeled Blue A keystroke CTRL+B Then the color change command is handled in a uniform way, no matter whether it was caused by a button click, a menu selection, or a key press. The Swing package provides a very useful mechanism to encapsulate commands and to attach them to multiple event sources: the Action interface. An action is an object that encapsulates 39) Mouse Events You do not need to handle mouse events explicitly if you just want the user to be able to click on a button or menu. These mouse operations are handled internally by the various components in the user interface. However, if you want to enable the user to draw with the mouse, you will need to trap mouse move, click, and drag events.
40)Semantic and Low-Level Events The AWT makes a useful distinction between low-level and semantic events. A semantic event is one that expresses what the user is doing, such as clicking that button; hence, an ActionEvent is a semantic event. Low-level events are those events that make this possible. In the case of a button click, this is a mouse down, a series of mouse moves, and a mouse up
41)Define components interface. Interface component such as a button, a checkbox, a text field, or a sophisticated tree control. Every component has three characteristics: Its content, such as the state of a button (pushed in or not), or the text in a text field Its visual appearance (color, size, and so on) Its behavior (reaction to events) Even a seemingly simple component such as a button exhibits some moderately complex interaction among these characteristics. Obviously, the visual appearance of a button depends on the look and feel. 42) Border Layout The border layout manager is the default layout manager of the content pane of every JFrame. Unlike the flow layout manager, which completely controls the position of each component, the border layout manager lets you choose where you want to place each component. 43) Grid Layout The grid layout arranges all components in rows and columns like a spreadsheet. All components are given the same size. The calculator program in Figure 912 uses a grid layout to arrange the calculator buttons. When you resize the window, the buttons grow and shrink, but all buttons have identical sizes 44) Choice Components You now know how to collect text input from users, but there are many occasions for which you would rather give users a finite set of choices than have them enter the data in a text component. Using a set of buttons or a list of items tells your users what choices they have. (It also saves you the trouble of error checking.) In this section, you learn how to program checkboxes, radio buttons, lists of choices, and sliders. 45)Checkboxes If you want to collect just a yes or no input, use a checkbox component. Checkboxes automatically come with labels that identify them. The user usually checks the box by
clicking inside it and turns off the check mark by clicking inside the box again. To toggle the check mark, the user can also press the space bar when the focus is in the checkbox.
46) Combo Boxes If you have more than a handful of alternatives, radio buttons are not a good choice because they take up too much screen space. Instead, you can use a combo box. When the user clicks on the component, a list of choices drops down, and the user can then select one of them 47) Menus We started this chapter by introducing the most common components that you might want to place into a window, such as various kinds of buttons, text fields, and combo boxes. Swing also supports another type of user interface element, the pull-down menus that are familiar from GUI applications. A menu bar on top of the window contains the names of the pull-down menus. Clicking on a name opens the menu containing menu items and submenus 48) The Grid Bag Layout The grid bag layout is the mother of all layout managers. You can think of a grid bag layout as a grid layout without the limitations. In a grid bag layout, the rows and columns can have variable sizes Consider the font selector of Figure 929. It consists of the following components: Two combo boxes to specify the font face and size Labels for these two combo boxes Two checkboxes to select bold and italic A text area for the sample string 49)exception. If an exception occurs that is not caught anywhere, the program will terminate and print a message to the console, giving the type of the exception and a stack trace. Graphics programs (both applets and applications) catch exceptions, print stack trace messages, and then go back to the user interface processing loop. (When you are debugging a graphically based program, it is a good idea to keep the console available on the screen and not minimized.) To catch an exception, you set up a try/catch block. The simplest form of the try block is as follows: try { code more code more code } catch (ExceptionType e)
{ handler for this type } If any of the code inside the try block throws an exception of the class specified in the catch clause, then 1. The program skips the remainder of the code in the try block. 2. The program executes the handler code inside the catch clause 50)The finally Clause When your code throws an exception, it stops processing the remaining code in your method and exits the method. This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up. One solution is to catch and rethrow all exceptions. But this solution is tedious because you need to clean up the resource allocation in two places, in the normal code and in the exception code. 51)possible states of finally clause. Let us look at the three possible situations in which the program will execute the finally clause. 1. The code throws no exceptions. In this event, the program first executes all the code in the try block. Then, it executes the code in the finally clause. Afterwards, execution continues with the first statement after the finally clause. In other words, execution passes through points 1, 2, 5, and 6. 2. The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. The program then executes the code in the matching catch clause, then the code in the finally clause. If the catch clause does not throw an exception, the program executes the first line after the finally clause. In this scenario, execution passes through points 1, 3, 4, 5, and 6Let us look at the three possible situations in which the program will execute the finally clause. 1. The code throws no exceptions. In this event, the program first executes all the code in the try block. Then, it executes the code in the finally clause. Afterwards, execution continues with the first statement after the finally clause. In other words, execution passes through points 1, 2, 5, and 6. 2. The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. The program then executes the code in the matching catch clause, then the code in the finally clause. 52) Why Generic Programming? Generic programming means to write code that can be reused for objects of many different
types. For example, you dont want to program separate classes to collect String and File objects. And you dont have tothe single class ArrayList collects objects of any class. This is one example of generic programming.
53) Definition of a Simple Generic Class A generic class is a class with one or more type variables. In this chapter, we use a simple Pair class as an example. This class allows us to focus on generics without being distracted by data storage details. Here is the code for the generic Pair class: public class Pair<T> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } private T first; private T second; } 54)Generic Methods In the preceding section, you have seen how to define a generic class. You can also define a single method with type parameters. class ArrayAlg { public static <T> T getMiddle(T[] a) { return a[a.length / 2]; } } 55)translation of Java generics: There are no generics in the virtual machines, only ordinary classes and methods. All type parameters are replaced by their bounds. Bridge methods are synthesized to preserve polymorphism. Casts are inserted as necessary to preserve type safety. 56)What Are Threads? Let us start by looking at a program that does not use multiple threads and that, as a consequence, makes it difficult for the user to perform several tasks with that program. After we dissect it, we then show you how easy it is to have this program run separate threads. This program animates a bouncing ball by continually moving the ball, finding
out if it bounces against a wall, and then redrawing it. 57) Here is a simple procedure for running a task in a separate thread: 1. Place the code for the task into the run method of a class that implements the Runnable interface. That interface is very simple, with a single method: public interface Runnable { void run(); } You simply implement a class, like this: class MyRunnable implements Runnable { public void run() { task code } } 2. Construct an object of your class: Runnable r = new MyRunnable(); 3. Construct a Thread object from the Runnable: Thread t = new Thread(r); 4. Start the thread: t.start(); 58) Interrupting Threads A thread terminates when its run method returns, by executing a return statement, after executing the last statement in the method body, or if an exception occurs that is not caught in the method. In the initial release of Java, there also was a stop method that another thread could call to terminate a thread. 59) Thread States Threads can be in one of six states: New Runnable Blocked Waiting Timed waiting Terminated 60) New Threads When you create a thread with the new operatorfor example, new Thread(r)the thread is not yet running. This means that it is in the new state. When a thread is in the new state,
the program has not started executing code inside of it. A certain amount of bookkeeping needs to be done before a thread can run. 61)Runnable Threads Once you invoke the start method, the thread is in the runnable state. A runnable thread may or may not actually be running. It is up to the operating system to give the thread time to run. (The Java specification does not call this a separate state, though. A running thread is still in the runnable state.) 62) Blocked and Waiting Threads When the thread tries to acquire an intrinsic object lock (but not a Lock in the java.util.concurrent library) that is currently held by another thread, it becomes blocked. (We discuss java.util.concurrent locks in the section Lock Objects on page 742 and intrinsic object locks in the section The synchronized Keyword on page 750.) The thread becomes unblocked when all other threads have relinquished the lock and the thread scheduler has allowed this thread to hold it.
63) Terminated Threads A thread is terminated for one of two reasons: It dies a natural death because the run method exits normally. It dies abruptly because an uncaught exception terminates the run method. In particular, you can kill a thread by invoking its stop method. That method throws a ThreadDeath error object that kills the thread. However, the stop method is deprecated, and you should never call it in your own code. 64)Thread Priorities In the Java programming language, every thread has a priority. By default, a thread inherits the priority of the thread that constructed it. You can increase or decrease the priority of any thread with the setPriority method. You can set the priority to any value between MIN_PRIORITY (defined as 1 in the Thread class) and MAX_PRIORITY (defined as 10). NORM_PRIORITY is defined as 5. 65) Daemon Threads You can turn a thread into a daemon thread by calling t.setDaemon(true); There is nothing demonic about such a thread. A daemon is simply a thread that has no other role in life than to serve others. Examples are timer threads that send regular timer ticks to other threads or threads that clean up stale cache entries. When only daemon threads remain, the virtual machine exits. There is no point in keeping the program running if all remaining threads are daemons. 66) Define Synchronization In most practical multithreaded applications, two or more threads need to share access
to the same data. What happens if two threads have access to the same object and each calls a method that modifies the state of the object? As you might imagine, the threads can step on each others toes. Depending on the order in which the data were accessed, corrupted objects can result. Such a situation is often called a race condition. 67) The synchronized Keyword In the preceding sections, you saw how to use Lock and Condition objects. Before going any further, let us summarize the key points about locks and conditions: A lock protects sections of code, allowing only one thread to execute the code at a time. A lock manages threads that are trying to enter a protected code segment. A lock can have one or more associated condition objects. Each condition object manages threads that have entered a protected code section but that cannot proceed. The Lock and Condition interfaces were added to Java SE 5.0 to give programmers a high degree of control over locking. 66)The intrinsic locks and conditions have some limitations. Some Among them are: You cannot interrupt a thread that is trying to acquire a lock. You cannot specify a timeout when trying to acquire a lock. Having a single condition per lock can be inefficient. What should you use in your codeLock and Condition objects or synchronized methods? with synchronized methods. Use Lock/Condition if you specifically need the additional power that these constructs give you. Listing 149 67)void notifyAll() unblocks the threads that called wait on this object. This method can only be called from within a synchronized method or block. The method throws an IllegalMonitorStateException if the current thread is not the owner of the objects lock. 68)void notify() unblocks one randomly selected thread among the threads that called wait on this object. This method can only be called from within a synchronized method or block. The method throws an IllegalMonitorStateException if the current thread is not the owner of the objects lock. 69)void wait() causes a thread to wait until it is notified. This method can only be called from within a synchronized method. It throws an IllegalMonitorStateException if the
current thread is not the owner of the objects lock. 70)a monitor has these properties: A monitor is a class with only private fields. Each object of that class has an associated lock. All methods are locked by that lock. In other words, if a client calls obj.method(), then the lock for obj is automatically acquired at the beginning of the method call and relinquished when the method returns. Because all fields are private, this arrangement ensures that no thread can access the fields while another thread manipulates them. The lock can have any number of associated conditions.
71)However, a Java object differs from a monitor in three important ways, compromising thread safety: Fields are not required to be private. Methods are not required to be synchronized. The intrinsic lock is available to clients. 72) In summary, concurrent access to a field is safe in these three conditions: The field is final, and it is accessed after the constructor has completed. Every access to the field is protected by a common lock. The field is volatile.
72)Deadlocks Locks and conditions cannot solve all problems that might arise in multithreading. Consider the following situation: Account 1: $200 Account 2: $300 Thread 1: Transfer $300 from Account 1 to Account 2 Thread 2: Transfer $400 from Account 2 to Account 1 Threads 1 and 2 are clearly blocked. Neither can proceed because the balances in Accounts 1 and 2 are insufficient. Is it possible that all threads are blocked because each is waiting for more money? Such a situation is called a deadlock.