it 2 mark

Upload: kanchana-murugaiyan

Post on 07-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 It 2 Mark

    1/20

    Two marksUnit -I

    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 executionenvironment that provides services such as security, portability across operatingsystems,and automatic garbage collection.

    2)List out the advantages of java?

    SimplePortableObject OrientedInterpretedNetwork-SavvyHigh PerformanceRobust

  • 8/3/2019 It 2 Mark

    2/20

    MultithreadedSecureDynamic

    Architecture Neutral

    3)case sensitive?

    The standard naming convention (which we follow in the name FirstSample) is thatclass names are nouns that start with an uppercase letter. If a name consists of multiplewords, use an initial uppercase letter in each of the words. (This use of uppercaseletters 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 typesin Java

    int 4 bytesshort 2 byteslong 8 bytesbyte 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 changea character in an existing string.Ifyou want to turn greeting into "Help!", you cannot directly change the last positions ofgreetinginto '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 thesubstringthat 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 nomultidimensional arrays at all, only one-dimensionalarrays. Multidimensional arrays are faked as arrays of arrays.

  • 8/3/2019 It 2 Mark

    3/20

    7)how to identify three key characteristics of objects.

    The objects behaviorWhat can you do with this object, or what methods can youapply to it? The objects stateHow does the object react when you apply those methods? The objects

    identity

    How is the object distinguished from others that may have thesame behavior and state?

    8)relationship between classes.

    Relationships between ClassesThe 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 classis the template or blueprint from which objects are made.When you constructan

    object from

    a class, you are said to have created an instanceof the class.

    ii)pre defined class

    The standard Java library supplies several thousand classes for such diverse purposesas user interfacedesign, 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.

  • 8/3/2019 It 2 Mark

    4/20

    11)Static FieldsIf you define a field as static, then there is only one such field per class. In contrast,eachobject has its own copy of all instance fields.

    12) Static MethodsStatic methods are methods that do not operate on objects. For example, the powmethodof the Math class is a static method. The expressionMath.pow(x, a)computes the power xa. It does not use any Math object to carry out its task. In otherwords, it has no implicit parameter.You can think of static methods as methods that dont have a this parameter. (In anonstaticmethod, the this parameter refers to the implicit parameter of the methodsee thesection Implicit and Explicit Parameters on page 127.)

    Because static methods dont operate on objects, you cannot access instance fieldsfroma static method. But static methods can access the static fields in their class. Here is anexample 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 wouldneed 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 thefinalize Methodnotably C++, have explicit destructormethods 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 forobjects.Because Java does automatic garbage collection, manual memory reclamation is notneeded and so Java does not support destructors.

    You can add a finalize method to any class. The finalize method will be called beforethe

  • 8/3/2019 It 2 Mark

    5/20

    garbage collector sweeps away the object. In practice, do not rely on thefinalizemethodforrecycling any resources that are in short supplyyou simply cannot know when thismethod will be called.

    15) Packages.Java allows you to group classes in a collection called a package. Packages areconvenientfor organizing your work and for separating your work from code librariesprovided 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 ofhierarchical packages. Just as you have nested subdirectories on your hard disk, youcan organize packages by using levels of nesting. All standard Java packages areinside the java and javax package hierarchies.

    16)Class ImportationA class can use all classes from its own package and all publicclasses from otherpackages.You can access the public classes in another package in two ways. The first is simply toadd the full package name in front of everyclass name. For example:java.util.Date today = new java.util.Date();That is obviously tedious. The simpler, and more common, approach is to use theimportstatement. The point of the import statement is simply to give you a shorthand to refer totheclasses in the package. Once you use import, you no longer have to give the classestheir fullnames.You can import a specific class or the whole package. You place import statements atthetop of your source files (but below any package statements). For example, you canimportall classes in the java.util package with the statementimport java.util.*;Then you can useDate 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 ScopeYou have already encountered the access modifiers public and private. Features taggedaspublic can be used by any class. Private features can be used only by the class thatdefines them. If you dont specify eitherpublic or private, the feature (that is, the class,

  • 8/3/2019 It 2 Mark

    6/20

    method, or variable) can be accessed by all methods in the same package.

    18)Comment InsertionThe 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 anexisting class. The existing class is called the superclass, base class, or parent class.The newclass is called the subclass, derived class, or child class. The terms superclass andsubclassare those most commonly used by Java programmers,java supports only two types of

    inheritancethey arei)singleii)multilevel

    19)Define polymorphism.The fact that an object variable (such as the variable e) can refer to multiple actualtypesis called polymorphism. Automatically selecting the appropriate method at runtime isdynamic binding

    20)Dynamic BindingIt 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 differentparameter 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 methodscalled 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 exactlywhich method to call. (The final modifier is explained in the next section.) This iscalled static binding. Otherwise, the method to be called depends on the actual type ofthe implicit parameter, and dynamic binding must be used at runtimeruntime. In ourexample, the compiler would generate an instruction to call f(String) with dynamicbinding.

    21)Preventing Inheritance: Final Classes and MethodsOccasionally, you want to prevent someone from forming a subclass from one of your

  • 8/3/2019 It 2 Mark

    7/20

    classes. Classes that cannot be extended are called finalclasses, and you use the finalmodifier in the definition of the class to indicate this. For example, let us suppose wewant to prevent others from subclassing the Executive class. Then, we simply declaretheclass 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 subclasscanoverride that method. (All methods in a final class are automatically final.) For example:class Employee{. . .

    public final String getName(){return name;}. . .}

    22) Abstract ClassesA 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, noobjects of that class can be created.you can create objects of concrete subclasses.Note that you can still create object variablesof an abstract class, but such a variablemustrefer 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 thenonabstractsubclass 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) Theequals MethodThe equals method in the Object class tests whether one object is considered equal toanother.

  • 8/3/2019 It 2 Mark

    8/20

    The equals method, as implemented in the Object class, determines whether two objectreferencesare identical. This is a pretty reasonable defaultif two objects are identical, theyshould 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 onlyify.equals(x) returns true.3. It is transitive: For any references x, y, and z, if x.equals(y) returns true andy.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 repeatedcalls 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 typeshave class counterparts. For example, a class Integer corresponds to the primitive typeint.These kinds of classes are usually called wrappers. The wrapper classes have obviousnames: Integer, Long, Float, Double, Short, Byte, Character, Void, and Boolean. (Thefirst six inheritfrom the common superclass Number.) The wrapper classes are immutableyoucannotchange a wrapped value after the wrapper has been constructed. They are also final, soyou cannot subclass them.

    26)ReflectionThe reflection librarygives you a very rich and elaborate toolset to write programsthat manipulate Java code dynamically.A program that can analyze the capabilities of classes is called reflective. The reflectionmechanism 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 worksfor allclasses; Implement generic array manipulation code; and Take advantage ofMethod objects that work just like function pointers in languagessuch as C++.

    27)Types of exception.There are two kinds of exceptions: uncheckedexceptions and checkedexceptions. Withchecked exceptions, the compiler checks that you provide a handler. However, manycommon exceptions, such as accessing a null reference, are unchecked. The compilerdoes not check whether you provide a handler for these errorsafter all, you should

  • 8/3/2019 It 2 Mark

    9/20

    spend your mental energy on avoiding these mistakes rather than coding handlers forthem.

    28)define interface in java.

    Interface is a keyword. A class can implementone or more interfaces. You can thenuse objects of these implementing classes anytime that conformance to the interface isrequired. After we cover interfaces,Interface contain both abstract and non abstractmethod.All methods of an interface are automatically public. For that reason, it is not necessarytosupply the keyword public when declaring a method in an interface.The variables in interface are public static final by default and the methods are publicstatic 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 InterfacesInterfaces are not classes. In particular, you can never use the new operator toinstantiatean interface:x = new Comparable(. . .); // ERRORHowever, even though you cant construct interface objects, you can still declareinterface variables.Comparable x; // OKAn interface variable must refer to an object of a class that implements the interface:x = new Employee(. . .); // OK provided Employee implements ComparableNext, just as you use instanceof to check whether an object is of a specific class, youcanuse 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 formultiple chains of interfaces that go from a greater degree of generality to a greaterdegree 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();}

  • 8/3/2019 It 2 Mark

    10/20

    Although you cannot put instance fields or static methods in an interface, you cansupplyconstants 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 alwayspublic static final.

    30)clone method.Quite frequently, however, subobjects are mutable, and you must redefine the clonemethod to make a deep copythat clones the subobjects as well. In our example, thehireDayfield is a Date, which is mutable.

    For every class, you need to decide whether1. The default clone method is good enough;2. The default clone method can be patched up by calling clone on the mutablesubobjects; and3. clone should not be attempted.The third option is actually the default. To choose either the first or the second option, aclass must1. Implement the Cloneable interface; and2. Redefine the clone method with the public access modifier.

    31)Inner ClassesAn inner classis a class that is defined inside another class. Why would you want to dothat? There are three reasons: Inner class methods can access the data from the scope in which they are definedincluding data that would otherwise be private. Inner classes can be hidden from other classes in the same package. Anonymousinner classes are handy when you want to define callbacks without writinga lot of code.

    32) Special Syntax Rules for Inner ClassesIn the preceding section, we explained the outer class reference of an inner class bycallingit outer. Actually, the proper syntax for the outer reference is a bit more complex. TheexpressionOuterClass.thisdenotes the outer class reference. For example, you can write the actionPerformedmethodof the TimePrinter inner class aspublic void actionPerformed(ActionEvent event){

  • 8/3/2019 It 2 Mark

    11/20

    . . .if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep();}Conversely, you can write the inner object constructor more explicitly, using the syntaxouterObject.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 thethisreference of the method that creates the inner class object. This is the most commoncase.As always, the this. qualifier is redundant. However, it is also possible to set the outerclass reference to another object by explicitly naming it. For example, becauseTimePrinteris 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 asOuterClass.InnerClass

    33)Static Inner ClassesOccasionally, you want to use an inner class simply to hide one class inside another,butyou dont need the inner class to have a reference to the outer class object. You cansuppressthe 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 thecompiler, and then load the resulting class file. Naturally, this is slow, and it alsorequires deployment of the compiler together with the program. The proxymechanismis a better solution. The proxy class can create brand-new classes at runtime. Such aproxy class implements the interfaces that you specify. In particular, the proxy class hasthe 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 toplatform-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.

  • 8/3/2019 It 2 Mark

    12/20

    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 eventoccurs. The listener objects will then use the information in the event object to determine

    their reaction to the event.

    37)Adapter ClassesNot all events are as simple to handle as button clicks. In a non-toy program, you willwant to monitor when the user tries to close the main frame because you dont wantyourusers to lose unsaved work. When the user closes the frame, you want to put up adialogand exit the program only when the user agrees.When the program user tries to close a frame window, the JFrame object is the sourceof a

    WindowEvent. If you want to catch that event, you must have an appropriate listenerobjectand add it to the frames list of window listene rs.

    38) ActionsIt is common to have multiple ways to activate the same command. The user canchoosea certain function through a menu, a keystroke, or a button on a toolbar. This is easy toachieve in the AWT event model: link all events to the same listener. For example,supposeblueAction is an action listener whose actionPerformed method changes thebackgroundcolor 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+BThen the color change command is handled in a uniform way, no matter whether it wascaused by a button click, a menu selection, or a key press.The Swing package provides a very useful mechanism to encapsulate commands andtoattach them to multiple event sources: the Action interface. An actionis an object thatencapsulates

    39) Mouse EventsYou do not need to handle mouse events explicitly if you just want the user to be able toclick on a button or menu. These mouse operations are handled internally by thevariouscomponents in the user interface. However, if you want to enable the user to drawwith the mouse, you will need to trap mouse move, click, and drag events.

  • 8/3/2019 It 2 Mark

    13/20

    40)Semantic and Low-Level EventsThe AWT makes a useful distinction between low-leveland semanticevents. Asemantic eventis one that expresses what the user is doing, such as clicking that button; hence, anAction-

    Event is a semantic event. Low-level events are those events that make this possible. Inthe caseof 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 treecontrol.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 moderatelycomplexinteraction among these characteristics. Obviously, the visual appearance of a buttondepends on the look and feel.

    42) Border LayoutThe border layout manageris the default layout manager of the content pane of everyJFrame. Unlike the flow layout manager, which completely controls the position of eachcomponent, the border layout manager lets you choose where you want to place eachcomponent.

    43) Grid LayoutThe grid layout arranges all components in rows and columns like a spreadsheet. Allcomponents are given the same size. The calculator program in Figure 912 uses a gridlayout to arrange the calculator buttons. When you resize the window, the buttons growand shrink, but all buttons have identical sizes

    44) Choice ComponentsYou now know how to collect text input from users, but there are many occasions forwhich you would rather give users a finite set of choices than have them enter the datain a text component. Using a set of buttons or a list of items tells your users whatchoicesthey have. (It also saves you the trouble of error checking.) In this section, you learnhow to program checkboxes, radio buttons, lists of choices, and sliders.

    45)CheckboxesIf you want to collect just a yes or no input, use a checkbox component. Checkboxesautomatically come with labels that identify them. The user usually checks the box by

  • 8/3/2019 It 2 Mark

    14/20

    clicking inside it and turns off the check mark by clicking inside the box again. To togglethe check mark, the user can also press the space bar when the focus is in thecheckbox.

    46) Combo BoxesIf you have more than a handful of alternatives, radio buttons are not a good choicebecause they take up too much screen space. Instead, you can use a combo box.Whenthe user clicks on the component, a list of choices drops down, and the user can thenselect one of them

    47) MenusWe started this chapter by introducing the most common components that you mightwant to place into a window, such as various kinds of buttons, text fields, and comboboxes. Swing also supports another type of user interface element, the pull-down

    menus that are familiar from GUI applications.A menu baron top of the window contains the names of the pull-down menus. Clickingon a name opens the menu containing menu itemsand submenus

    48) The Grid Bag LayoutThe grid bag layout is the mother of all layout managers. You can think of a grid baglayout as a grid layout without the limitations. In a grid bag layout, the rows and columnscan have variable sizesConsider 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 andprint 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 tracemessages, and then go back to the user interface processing loop. (When you aredebugging a graphically based program, it is a good idea to keep the console availableon the screen and not minimized.)To catch an exception, you set up a try/catch block. The simplest form of the try block isas follows:try{codemore codemore code}catch (ExceptionTypee)

  • 8/3/2019 It 2 Mark

    15/20

    {handler for this type}If any of the code inside the try block throws an exception of the class specified in thecatch 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)Thefinally ClauseWhen your code throws an exception, it stops processing the remaining code in yourmethod and exits the method. This is a problem if the method has acquired some localresource that only it knows about and if that resource must be cleaned up. One solutionis to catch and rethrow all exceptions. But this solution is tedious because you need toclean up the resource allocation in two places, in the normal code and in the exceptioncode.

    51)possible states of finally clause.Let us look at the three possible situations in which the program will execute thefinally clause.1. The code throws no exceptions. In this event, the program first executes all thecode 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, anIOException. For this, the program executes all code in the try block, up to the pointat 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 inthe finally clause.If the catch clause does not throw an exception, the program executes the first line afterthe finally clause. In this scenario, execution passes through points 1, 3, 4, 5, and 6Letus look at the three possible situations in which the program will execute thefinally clause.1. The code throws no exceptions. In this event, the program first executes all thecode 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, anIOException. For this, the program executes all code in the try block, up to the pointat 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 inthe finally clause.

    52) Why Generic Programming?Generic programmingmeans to write code that can be reused for objects of manydifferent

  • 8/3/2019 It 2 Mark

    16/20

    types. For example, you dont want to program separate classes to collect String andFileobjects. 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 ClassA generic classis a class with one or more type variables. In this chapter, we use asimplePair class as an example. This class allows us to focus on generics without beingdistractedby data storage details. Here is the code for the generic Pair class:public class Pair{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 MethodsIn the preceding section, you have seen how to define a generic class. You can alsodefine a single method with type parameters.class ArrayAlg{public static 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 aconsequence, 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 separatethreads. This program animates a bouncing ball by continually moving the ball, finding

  • 8/3/2019 It 2 Mark

    17/20

    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 theRunnable

    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 ThreadsA thread terminates when its run method returns, by executing a return statement, afterexecuting the last statement in the method body, or if an exception occurs that is notcaught in the method. In the initial release of Java, there also was a stop method thatanother thread could call to terminate a thread.

    59) Thread StatesThreads can be in one of six states: New Runnable Blocked Waiting Timed waiting Terminated

    60) New ThreadsWhen you create a thread with the new operatorfor example, new Thread(r)thethread isnot yet running. This means that it is in the newstate. When a thread is in the newstate,

  • 8/3/2019 It 2 Mark

    18/20

    the program has not started executing code inside of it. A certain amount ofbookkeepingneeds to be done before a thread can run.

    61)Runnable Threads

    Once you invoke the start method, the thread is in the runnablestate. A runnablethread may or may not actually be running. It is up to the operating system to givethe 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 ThreadsWhen 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 becomesblocked. (We discuss java.util.concurrent locks in the section Lock Objects onpage 742 and intrinsic object locks in the section The synchronized Keyword onpage 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 ThreadsA 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 methodthrows a ThreadDeath error object that kills the thread. However, the stop method isdeprecated, and you should never call it in your own code.

    64)Thread PrioritiesIn the Java programming language, every thread has a priority. By default, a threadinherits the priority of the thread that constructed it. You can increase or decrease thepriority of any thread with the setPriority method. You can set the priority to any valuebetween MIN_PRIORITY (defined as 1 in the Thread class) and MAX_PRIORITY(defined as 10).NORM_PRIORITY is defined as 5.

    65) Daemon ThreadsYou can turn a thread into a daemon threadby callingt.setDaemon(true);There is nothing demonic about such a thread. A daemon is simply a thread that hasno other role in life than to serve others. Examples are timer threads that send regulartimer ticks to other threads or threads that clean up stale cache entries. Whenonly daemon threads remain, the virtual machine exits. There is no point in keepingthe program running if all remaining threads are daemons.

    66) Define SynchronizationIn most practical multithreaded applications, two or more threads need to share access

  • 8/3/2019 It 2 Mark

    19/20

    to the same data. What happens if two threads have access to the same object andeachcalls a method that modifies the state of the object? As you might imagine, the threadscan step on each others toes. Depending on the order in which the data wereaccessed,

    corrupted objects can result. Such a situation is often called a race condition.

    67) Thesynchronized KeywordIn the preceding sections, you saw how to use Lock and Condition objects. Before goinganyfurther, 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 ahighdegree 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 synchronizedmethods?with synchronized methods. Use Lock/Condition if you specifically need the additional power that these constructsgive you.Listing 14967)void notifyAll()unblocks the threads that called wait on this object. This method can only becalled from within a synchronized method or block. The method throws anIllegalMonitorStateException 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 thisobject. This method can only be called from within a synchronized method orblock. The method throws an IllegalMonitorStateException if the current thread is notthe owner of the objects lock.

    69)void wait()causes a thread to wait until it is notified. This method can only be called fromwithin a synchronized method. It throws an IllegalMonitorStateException if the

  • 8/3/2019 It 2 Mark

    20/20

    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(), thenthe lock for obj is automatically acquired at the beginning of the method call andrelinquished when the method returns. Because all fields are private, this arrangementensures that no thread can access the fields while another thread manipulatesthem. The lock can have any number of associated conditions.

    71)However, a Java object differs from a monitor in three important ways,

    compromisingthread 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)DeadlocksLocks and conditions cannot solve all problems that might arise in multithreading.Considerthe following situation:Account 1: $200Account 2: $300Thread 1: Transfer $300 from Account 1 to Account 2Thread 2: Transfer $400 from Account 2 to Account 1

    Threads 1 and 2 are clearly blocked. Neither can proceedbecause 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.