Cracking OCPJP 7 exam made easy!
What is this reference card all about? If you are preparing to appear for Oracle Certified Professional Java SE 7 Programmer (OCPJP 7) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam. What is covered in this reference card? The first few pages of this reference card provides overall information on the OCPJP 7 exam. The main meat is in the summary for each exam topic, organized by the exam sub-topics.You’ll also find tables and class hierarchies which will help you remember key points and crack the exam with ease. Why did we create this reference card? OCPJP 7 covers broad range of topics with reasonable depth of understanding required by the candidate to crack the exam. As authors of the first book on OCPJP 7 exam preparation, we found through our experience that revising key concepts from exam topics will significantly helps a candidate to crack the exam, and so, we prepared this!




• We can have overloaded constructors. and types of arguments. • Polymorphism: interpreting the same message (i. • Overload resolution is the process by which the compiler looks for resolving a call when overloaded definitions of a method are available. method call) with different meanings depending on the context. • You can access public methods of a class from any other class. We can call a constructor of the same class in another constructor using the “this” keyword.e. Furthermore. you cannot overload methods based on return type or exception specification alone. Class Foundations • A “class” is a template (or blueprint) and an “object” is an instance of a class. number of arguments.Java Class Design Foundations of OOP • Encapsulation: combining data and the functions operating on it as a single unit.. • Inheritance: creating hierarchical relationships between among related classes. • Yo u c a n a c c e s s t h e protected method either from a class in the same package (just like package private or default) as well as from a derived class. • Yo u c a n o v e r l o a d methods with same name but with different signatures. member methods or fields of an interface cannot be declared as private or protected. Since return type and exception specification are not part of the signature. • A constructor does not have a return type. • You can also access a method with default access modifier if it is in the same package. • Abstraction: hiding lowerlevel details and exposing only the essential and relevant details to the users. Overloading • The signature of a method is made up of the method name. • You cannot access the private methods of the base class in the derived class. • A class (or interface) cannot be declared as private or protected. .

• We can use super keyword for referring to the base class members also. • @Override annotation can be provided before a method definition to aid our understanding that the method is overridden. • In covariant return types. • Static import only imports static members of the specified package or class. . An upcast will always succeed. the compiler cannot predict the result of the cast . • If the compiler can use only the static type information of the source and target types and infer it as an invalid cast.e. So we can use the “instanceof“ operator to see if a downcast is valid. • We u s e t h e “ s u p e r ” keyword for calling base class methods. because they are not inherited. A downcast may fail. • Resolving a method call based on the dynamic type of the object is referred as runtime polymorphism. • We don't need to do an explicit cast for doing an upcast. If the success/failure of the cast depends on the dynamic type of the object. • You can also use wildcard character “*” to import all static members of a specified package of class. • The type of the base class reference is known as the “static type” of the object and the actual object pointed by the reference at runtime is known as the “dynamic type” of the object.. Java Packages • A package is a scoping construct to categorize your classes and to provide namespace management. • We need to do an explicit cast for doing a downcast. we can use a member without explicitly qualifying it).Java Class Design Inheritance • Inheritance is also called an "is-a" relationship. • Overloading is an example of static polymorphism (early binding) while overriding is an example of dynamic polymorphism (late binding). in that case. Such a call should be the first statement in a constructor if it is used.it becomes a runtime exception. it need not be the first statement in the method body. Private methods cannot be overridden. • You cannot override a method if you do not inherit it. you can provide the derived class of the return type in the overriding method. • We can use the static members of the imported package or class as if we have defined the static member in the current class (i. it becomes a compiler error.

The value of a final parameter cannot be changed once assigned. otherwise the compiler will complain. • An abstract class need not declare an abstract method. • All methods of a final class are implicitly final (i. .. • A final method is a nonoverridable method (i. but you cannot change the reference itself. it should be declared as an abstract class. you cannot inherit from a final class). otherwise you need to declare that subclass as an abstract class.. • An abstract class can be derived from a concrete class! Though the language allows it. • An abstract class can extend another abstract class or can implement an interface. Using “final” Keyword • A final class is a noninheritable class (i. subclasses cannot override a final method). Therefore.e. it is important to note that the "value" is implicitly understood for primitive types. You can however create reference variables of an abstract class type.e. • The keyword final can be applied to parameters. If a variable declaration defines a variable as final but did not initialize it. non-overridable). Here.Advanced Class Design Abstract Classes • Abstract classes define an abstraction and leave concrete implementation details to subclasses. • An abstract class cannot be instantiated. You need to initialize a blank final in the constructor. then it is referred to as blank final. In fine. However.e. • An abstract class may have methods or fields declared static. if a class has an abstract method. However. and runtime polymorphism in turn enables loose coupling. not its state.. • Abstract classes enable runtime polymorphism. the "value" for an object refers to the object reference. which means it is not necessary for an abstract class to have methods declared as abstract. you can create objects of the classes derived from an abstract class and make the abstract class references refer to the created derived class objects. you can change the internal state of the passed final object. it is not a good idea to do so. • A final variable can be assigned only once. • The abstract keyword can be applied to a class or a method but not to a field. • A subclass of an abstract class needs to provide implementation of all the abstract methods.

• When you define an enumeration. • Local classes (both local inner classes and anonymous inner classes) can access all variables declared in the outer scope (whether a method. and anonymous inner classes.lang.Enum. static nested classes can access only static members of outer class. • Static nested classes and inner classes can access members of an outer class (even private members). Enums • Enums are typesafe way to achieve restricted input from users. whereas the other flavors of nested classes can’t. • Enumeration constants cannot be cloned attempt to do so will result in a CloneNotSupportedExce ption. Internally. • If you declare an enum within a class. and final. or a statement block).Advanced Class Design Flavors of Nested Classes • Java supports four types of nested classes: static nested classes. inner classes. • You can apply the valueOf() and name() methods to the enum element to return the name of the enum element. When an enumeration constant's toString() method is invoked. the equals() method does not return true. static. Further. • Enums are implicitly declared public. . it implicitly inherits from java. constructor. it prints the name of the enumeration constant. which means you cannot extend them. even inside the enum class. However. • Static nested classes may have static members. enumerations are converted to classes. • The static values() method in the Enum class returns an array of the enumeration constants when called on an enumeration type. • We can compare two enumerations for equality using == operator. then it is by default static. local inner classes. • You cannot use the new operator on enum data types. enumeration constants are instances of the enumeration class for which the constant is declared as a member. • If enumeration constants are from two different enumerations.

Object Oriented Design Principles Interfaces • An interface cannot be instantiated. If you want. If you declare a data member in an interface. such interfaces are known as nested interfaces. Use the extends (and not the implements) keyword for this. and all such data members are implicitly treated as “public static final” members. • A DAO design pattern essentially separates your core business logic from your persistence logic. and a global single point of access to that object.util defines the interface EventListner without a body. • You cannot declare members as protected or private. interface implies is-like-a. • You can only declare (and not define) methods in an interface. Only public access is allowed for members of an interface. an interface without any members. • An interface can be declared with empty body (i. • The singleton design pattern offers two things: one and only one instance of the class. For example. . it should be initialized. java.e. • Interfaces cannot contain instance variables. Object Composition • Inheritance implies is-a. and composition implies has-a relationships. • You should consider using the abstract factory design pattern when you have a family of objects to be created. • The factory design pattern “manufactures” the required type of product on demand. or private. Design Patterns • Design patterns are reusable solutions of frequently recurring design problems. so that runtime polymorphism can be used. Such interfaces are useful for defining a common parent. not to an implementation. • An interface can extend another interface. especially in a multi-threaded environment. • The observer design pattern improves loose coupling between subject and observers. Such interfaces are known as tagging interfaces (or marker interfaces). • An interface cannot declare static methods. • An interface can be declared within another interface or class. a nested interface can be declared as public.. you can explicitly use the abstract qualifier for the method. • All methods declared in an interface are implicitly considered to be abstract. • Program to an interface. • Making sure that an intended singleton implementation is indeed singleton is a non-trivial task. • Unlike top-level interfaces that can have only public or default access. protected. • Favor composition over inheritance whenever feasible. It can only declare instance methods.

<? extends Runnable> specifies that ? can match any type as long as it is Runnable or any of its derived types. ? will match types. For example. subtyping doesn’t work with generics. we cannot assign a derived generic type parameter to a base type parameter. For specifying multiple base types we use the & symbol. in List<? extends X & Y>. For example. . That is. Hence. The compiler will infer the types from the type declaration. generics offer generic implementation with type safety. For example.Generics and Collections Generics • Generics will ensure that any attempts to add elements of types other than the specified type(s) will be caught at compile time itself. extending both the types X and Y. • Generics are not covariant. • Java 7 has introduced “diamond” syntax where the type parameters (after new operator and class name) can be omitted. • We use extends keyword for both class type as well as an interface while specifying bounded types in generics. • Wildcards can be bounded. • The <?> Specifies an unknown type in generics and is known as a wildcard. List<?> refers to list of unknowns.

stack.Generics and Collections Collections Framework which return null and it would be • The methods hashCode() and equals() need to be consistent for a difficult for you to distinguish • Avoid mixing raw types with generic class. methods in the Deque interface . Comparator interface. In other cases. if you collection(s) refers to containers like have multiple alternative ways to map. the type safety manually. so we cannot It is not recommended that you store • use primitive types with any of the null as an argument. for your classes where a natural and collection are different. For practical purposes.Collection<E> for them. make sure of that you follow this one rule: The method call.Collections—is a utility HashMap.util. etc. queue. if the equals() method returns true order is possible. hashCode() method should return • Implement the Comparable interface the same hash value for two objects • The terms Collection. • references to objects. since there are collection classes. Collections— containers like HashSet or “natural ordering” present for your java. Also. then create separate class that contains only static the hashCode() and equals() classes implementing the methods. If you want to Collection— java. The general term methods correctly. Collections. then go for the the Collection interface. • The Map interface does not extend decide the order.util. compare the objects other than the —is the root interface in the If you’re using an object in “natural order” or if there is no • collection hierarchy. The container classes store Comparator interface. ensure between the success or failure of the types. make sure you override class type.

lastIndexOf() for backward searching a string. These groups can also split() method available in the String be used to specify back-reference. • To convert from a primitive type value to String type object. % sign. search pattern which can be used to execute operations such as string • Each format specifier starts with the search and string manipulation. Parsing. corresponding wrapper types of the primitive types. you can make use of the parse methods available for primitive types in the • You can form groups within a regex. you can make use of the overloaded valueOf() method which takes a primitive type value as argument and returns the String object. . and this argument is a String Formatting regular expression. they information are optional while the % are more efficient and faster than sign and data type specifier are any other way to perform search/ mandatory. and ending • Use the Pattern and Matcher classes with a data type specifier. followed by flags. class. you can use the whole regex. It takes a delimiter as an argument. These groups can be used to specify quantifiers on a desired subset of the • For parsing a string. To convert from the String type object to a primitive type value. and precision or replace on strings heavily. and regionMatches() for comparing a “region” of text within a string. and precision information. width. width. replace in Java. flags. • The method printf() (and the Regular Expressions method format() in the String class) uses string formatting flags to format • A regular expression defines a strings. and Building Strings • You can use the overloaded versions of the method indexOf() in the String class for forward searching in a string.String Processing Searching. In this whenever you are performing search string.

String Processing .

and use the right stream for a given task at hand. It is recommended to use are called input streams and output Array’s fill() method to “empty” the streams respectively (represented by password read into the character the abstract classes InputStream and array (to avoid malicious access to OutputStream). this method will supporting both character streams fail and return null. you’ll get nasty bugs. • Serialization: The process of converting the objects in memory in to a series of bytes. Byte streams are can use the printf() and format() used for data-based I/O. methods available in the Console class to print formatted text. These buffer classes are provided as wrapper classes for the underlying streams. the • Character streams for reading and overloaded readLine() and writing are called readers and readPassword() methods take writers respectively (represented by format strings as arguments. the abstract classes Reader and Writer). If you try using one type of stream instead of another. • For both byte as well as character streams. you can use data streams. • We should only use character The methods in the Console class streams for processing text files (or • have better support for “special human readable files).Java I/O Fundamentals Reading and Writing Data to Console characters” when compared to printing text through PrintStreams. and byte streams for data files. the typed passwords). So. . your program won’t work as you would expect. you can use buffering.console() Streams method.. • Many methods are provided in You can use character streams for Console support formatted I/O: You • text based I/O. • Persistence: The mechanism of storing objects in memory in to files. • You can use object streams for object persistence (i. don’t mix-up streams. and byte streams. even if it works by chance. reading and writing objects in memory to files and vice versa). Read and Write to Files with • You can obtain reference to the console using the System.e.io package has classes with any console. Using buffering will speedup the I/O when performing bulk I/ O operations. • Use the readPassword() method for reading secure strings such as • Byte streams for reading and writing passwords. • For processing data with primitive data types and Strings. if the JVM is not associated • The java.

Java I/O Fundamentals .

Java I/O Fundamentals .

all the directories (except the last one if you are copying a directory) in the specified path must exist to avoid NoSuchFileException. then you can simply extend your implementation from the SimpleFileVisitor class. . • Use the delete() method to delete a file. • You can retrieve attributes of a file using the getAttributes() method. isWriteable(). the method move() can be used to move a file from one location to another. or execute programmatically. Performing Operations on Files/ Directories • You can check the existence of a file using the exists() method of the Files class.2) Working with the Path Class • A Path object is a programming abstraction to represent a path of a file/directory. • You can get an instance of Path using the get() method of the Paths class. Walking a File Tree • The FileVisitor interface allows you to perform certain operations at certain key junctures. the program to read. use the deleteIfExists() method to delete a file only if it exists. • Path provides you two methods to use to compare Path objects: equals() and compareTo(). • While copying. • If you do not want to implement all four methods in the FileVisitor interface. • You can register a Path object using a watch service along with certain event types. Similarly. • The Files class provides the methods • The Files class provides two flavors isReadable(). an event is sent to the registered program.Java File I/O (NIO. Whenever any file in the specified directory changes. it is not guaranteed that you will get true from the equals() method. Even if two Path objects point to the same file/directory. • You can use the readAttributes() method of the Files class to read attributes of a file in bulk. You can specify the pattern using glob or regex. and of walkFileTree() to enable us to isExecutable() to check the ability of walk through a file system. • The method copy() can be used to copy a file from one location to another. write. Finding a File • The PathMatcher interface is useful when you want to find a file satisfying a certain pattern. Watching a Directory for Changes • Directory watch service can notify you when a watched file is changed by some other program.

• Type 2 (Native-API drivers): These drivers use client-side libraries of a specific database and convert JDBC calls to native database calls. • Type 4 (Native-protocol drivers): The driver directly makes databasespecific calls over the network without any support of additional client-side libraries.sql.0. • There are four types of drivers: • Type 1 (JDBC-ODBC bridge drivers): JDBC driver calls ODBC (Open Database Connectivity) native calls using the Java Native Interface (JNI). The <protocol> jdbc is the same for all DBMSs. Connect to a Database by Using a JDBC driver • The java. and password string. username string. <subprotocol> will differ for each DBMS. • Type 3 (Network-protocol drivers): These drivers call database middleware and the middleware actually converts JDBC calls to database-specific native calls. . • Prior to JDBC 4. An example of a URL string is "jdbc:mysql:// localhost:3306/". • If the JDBC API is not able to locate the JDBC driver. • JDBC hides all the heterogeneity of all the DBMSs and offers a single set of APIs to interact with all types of databases. we would have to explicitly load the JDBC driver using the Class.forName() statement. • The syntax of the URL (which needs to be specified to get the Connection object) is "<protocol>:<subprotocol>:// <server>:<port>/". it will throw a SQLException. • The getConnection() method in the DriverManager class takes three arguments: the URL string. with JDBC 4. hence all the details and complications are hidden by the JDBC API from the application developer. If there are jars for the drivers available. • The complexity of heterogeneous interactions is delegated to JDBC driver manager and JDBC drivers. then they need to be included in the classpath to enable the JDBC API to locate the driver. <server> depends on the location in which we host the database.Connection interface provides a channel through which the application and the database communicate.0 and above. this statement is not needed and the JDBC API will load the driver from the details given in the URL string. and each DBMS uses a specific <port> number.Building Database Applications with JDBC Define the Layout of the JDBC API • JDBC (Java DataBase Connectivity) APIs provided by Java are meant for programmatic access to DataBase Management Systems (DBMSs).

• By default auto-commit mode is set • A ResultSet is a table with column to true. • The column index in the ResultSet object starts from 1 (not from 0). we need to . all. These milestones are referred to as Savepoints. • JdbcRowSet is a connected RowSet while other sub-interfaces of RowSet (i. There are three types • By calling the getMetaData() of Statements: method in the Connection interface. • A Statement is a SQL statement • You need to call updateRow() after which could be used to communicate modifying the row contents in a a SQL statement to the connected ResultSet. and RowSet Interfaces • RowSet is a special ResultSet that supports the JavaBean component model. This way you may save the changes to a database up to a milestone once the milestone is achieved. Initially. • We can divide a big transaction into multiple milestones. then there will be no change in the database. next() method to advance the cursor position by one row. • Use the JDBC 4. • RowSetProvider provides APIs to get a RowSetFactory implementation. parameters.. CachedRowSet. RowSetFactory. the cursor is set to just to enable manual commits. which can in turn be used to instantiate a relevant RowSet implementation. SQL statement to the database • Customize the Transaction Behavior without any parameter. otherwise changes made database and receive results from to the ResultSet object will be lost. • CallableStatement: Used to execute Transaction-related methods are stored procedures. • If the commit() method does not execute in manual commit mode. committed automatically to the database. and FilteredRowSet) are disconnected RowSets. of JDBC and Commit Transactions • PreparedStatement: Represents a • A transaction is a set of SQL precompiled SQL statement which operations that needs to be either can be customized using IN executed all successfully or not at parameters. can handle IN as • supported in the Connection well as OUT and INOUT interface. WebRowSet. so all changes we make heading and associated values through the connection are requested by the query. JoinRowSet.e.1 RowSetProvider. explicitly commit or rollback transactions. the database. • You can use setAutoCommit(false). With before the first row. • A ResultSet object maintains a cursor pointing to the current row.Building Database Applications with JDBC Update and Query a Database • JDBC supports two classes for querying and updating: Statement and Resultset. calling the auto-commit not enabled. you can examine the capabilities of • Statement: You need to use Statement when you need to send a the underlying database.

etc. • A try block can have multiple catch handlers.lang. Only Throwable and its derived classes can be used with Java exception handling keywords such as try. • You can programmatically access the stack trace using the methods such as printStackTrace() and getStackTrace(). which can be called on any exception object. • The RuntimeException and Error classes and derived classes are known as unchecked exceptions. If a try block throws an exception. it is meaningful to handle these exceptions in catch blocks. the typical best course of action is to terminate the program. Providing base exception handlers before the derived handlers will result in a compiler error. These resources need to be separated by semicolons in the try-with-resources statement header. you can consider combining the handlers and make it into a multi-catch block. You can use a try-with-resources statement to simplify your code and auto-close resources. in some cases. either the JVM has detected a serious abnormal condition or has run out of resources. then the exceptions thrown in the finally block will be added as suppressed exceptions to the exception that gets thrown out of the try block to the caller. and throws. • While providing multiple exception handlers (stacked catch handlers). When an Error occurs. They can be thrown anywhere in the program (without being declared that the segment of code can throw these exceptions). These exceptions represent exceptional conditions that can be reasonably expected to occur when the program executes. • You can auto-close multiple resources within a try-withresources statement. • The Exception class (except its subhierarchy of the RuntimeException class) and its derived classes are known as checked exceptions. hence they must be handled. data base handles. For a resource to be usable in a try-with-resources statement. the JVM looks for a matching catch handler from the list of catch handlers in the method callchain. This makes a finally block the most suitable place to release resources. However. • The code inside a finally block will be executed irrespective of whether a try block has successfully executed or resulted in an exception. . specific exception handlers should be provided before general exception handlers. Exception Types • The class Throwable is the root class of the exception hierarchy. • Because you can use multiple resources within a try-withresources statement. Try-with-Resources • Forgetting to release resources by explicitly calling the close() method is a common mistake.Exceptions and Assertions Introduction to Exception Handling • When an exception is thrown from a try block.AutoCloseable interface and define the close() method. and a finally block also throws exception(s). catch. network streams. • A catch block should either handle the exception or rethrow it. • The Error classes and derived classes represent exceptions that arise because of JVM errors. and the handling code is also similar. If the cause of two or more exceptions is similar. such as file handles. the class of that resource must implement the java. To hide or swallow an exception by catching an exception and doing nothing is really a bad practice. the possibility of more than one exception getting thrown from the try block and the finally block is high. • The RuntimeException classes and derived classes represent programming mistakes (logical mistakes) and are not generally expected to be caught and handled in the program. A method that contains some code segment that can throw a checked exception must either provide a catch handler to handle it or declare that exception in its throws clause. If no matching handler is found. that unhandled exception will result in crashing the application.

From the thrown more specific throws clause than the exception. • It is recommended that you derive custom exceptions from either the Exception or RuntimeException class. • Static initialization blocks cannot throw any checked exceptions. You can use the commandline arguments of –ea (for enabling asserts) and –da (for disabling asserts) and their variants when you invoke the JVM. • If the Boolean condition given in the assert argument fails (i. used for explicitly checking the . assertions are disabled at runtime. Creation of custom exceptions by extending the Throwable class (too generic) or the Error class (exceptions of this type are reserved for JVM and the Java APIs to throw) is not recommended. Custom Exceptions • You can define your own exception classes (known as custom exceptions) in your programs. evaluates to false). These provide the same throw clause as the two exceptions become chained base method’s throws clause or a exceptions.e. • By default. overriding method cannot provide a Assertions more general throws clause or declare to throw additional checked • Assertions are condition checks in exceptions when compared to the the program and are meant to be base method’s throws clause. all the constructors should declare that exception in their throws clause. The the exception. It is not advisable to catch and recover from when an AssertionError is thrown by the program. you can get the cause of base method’s throws clause. assumptions you make while writing programs. • The assert statement is of two forms: one that takes a Boolean argument and one that takes an additional string argument. An overriding method can throw it as another exception. • A method’s throws clause is part of the contract that its overriding methods in derived classes should • You can wrap one exception and obey. the program will terminate after throwing an AssertionError.Exceptions and Assertions Throws Clause • The throws clause for a method is meant for listing the checked exceptions that the method body can throw. however. Nonstatic initialization blocks can throw checked exceptions..

Build a Resource Bundle for Each Locale • A resource bundle is a set of classes or property files that help define a set of keys and map those keys to locale-specific values. the Locale class in Java provides an abstraction for this concept. • Step 1: The search starts by looking for an exact match for the resource bundle with the full name. • There are many ways to create or get a Locale object corresponding to a locale: • Use the constructor of the Locale class.Builder and then call setLanguageTag() from that object. • Each locale can have three entries: the language.Localization Read and Set the Locale Using the Locale Object • A locale represents a language. • The class ResourceBundle has two derived classes: PropertyResourceBundle and ListResourceBundle. you can provide variant strings based on your need. You can change this default locale to another locale by using the setDefault() method. For each locale. and getVariant()— return codes. and values can be any objects. and variant. • To add support for a new locale. You can use only Strings as keys and values. Otherwise. or country. you specify the keys and values in a property file for that locale. If they don’t match. You can use ResourceBundle. you have to override the Object [][] getContents() method. You can use standard codes available for language and country to form locale tags. • Here is the search sequence to look for a matching resource bundle. and getDisplayVariant() return names. getCountry(). • Load a Resource Bundle in an Application • The process of finding a matching resource bundle is same for classes extended from ListResourceBundles as for property files defined for PropertyResourceBundles. • Use the predefined static final constants for locales in the Locale class. the resource bundle is loaded. you can extend the ListResourceBundle class. . • When passing the key string to the getObject() method to fetch the matching value in the resource bundle.bundlename + "_" + language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions.getBundle() to automatically load a bundle for a given locale. The returned array must have the list of keys and values. • Step 3: The search is restarted using the full name of the bundle for the default locale. you'll get a MissingResourceException. • The getDefault() method in Locale returns the default locale set in the JVM. If at any step the search finds a match. There are no standard tags for variants. The keys must be Strings. • Step 2: The last component (the part separated by _) is dropped and the search is repeated with the resulting shorter name. Search starts from Step 1. the search proceeds to the next step. country. make sure that the passed keys and the key in the resource bundle exactly match (the keyname is case sensitive). • Build a Locale object by instantiating Locale. In this derived class. • Use the forLanguageTag(String languageTag) method in the Locale class. • The PropertyResourceBundle class provides support for multiple locales in the form of property files. • The getter methods in the Locale class—such as getLanguage(). getDisplayLanguage(). This process is repeated till the last locale modifier is left. whereas the similar methods of getDisplayCountry(). • The naming convention for a fully qualified resource bundle name is packagequalifier. culture.

Localization .

another thread has acquired that another lock and waits for the first lock to be released. we cannot reproduce protected access to shared resources . The default run() method in running. • The runnable state has two states [Leave it to the JVM to call the internally (at the OS level): ready run() method. • Every thread has thread name. the default thread will be in the timed_waiting toString() method implementation in state when timeout is given for calls Thread prints them. we can use a wait/notify mechanism as a communication mechanism between threads. the thread does not release value). and thread-group when waiting to acquire a lock. access shared values and avoid data races. problems like deadlocks or data races every time. Java provides thread • Threads are also non-deterministic: synchronization features to provide in many cases. • Threads execute asynchronously: we • We have to use thread cannot predict the order in which synchronization (i. runnable and terminated. it’s in terminated state. When a thread is just created. the lock and it holds on to the lock. operations result in invalid thread In general. Thread does nothing. like wait. • “interrupt” feature in threads. it is in runnable state. • A thread will be in the blocked state priority. The thread will be in the waiting state when. Thread States —namely. When the thread dies. the process will hang and will never terminate. if you are not using the state transitions. So. The Wait/Notify Mechanism • When a thread has to wait for a particular condition or event to be satisfied by another thread. we can either call wait() with or without timeout value specified. • You will get an • We can use the join() method to IllegalThreadStateException if your wait for another thread to terminate. problem.. • Call the start() method and not the run() method directly in code. synchronized blocks and synchronized methods. when it is ready to run or • Always implement the run() method. • Using locks can introduce problems such as deadlocks. it is in new state. it is Concurrent Access Problems safe ignore InterruptedException. no progress is made the program deadlocks. When a deadlock happens. • To avoid notifications getting lost. ensure that they are acquired in the same order in all the places in the program. locks) to the threads run.] and running states. The associated with it. When we have to acquire such multiple locks. however it’s better still to log or • Concurrent reads and writes to print the stack trace if that exception resources may lead to the “data race” occurs.e. it is better to avoid acquiring multiple locks. When one thread has acquired one lock and waits for another lock. it is better to always use notifyAll() instead of notify(). • There are three basic thread states: new. • A deadlock typically happens when two threads acquire locks in opposite order. • To avoid deadlocks. • If we call the sleep() method of a wait() is called (without time out thread.Threads Introduction to Concurrent Programming • We can create classes that is capable of multi-threading by implementing the Runnable interface or by extending the Thread class. for example. • When a thread needs to wait for a particular condition/event.

Threads .

that other of the ExecutorService interface and thread could notify once the provides an easy.to-use concurrent condition is met.concurrent Collections • A Semaphore controls access to shared resources. • CyclicBarrier helps provide a synchronization point where threads may need to wait at a predefined execution point till all other threads reach that point. Using the Parallel Fork/Join Framework • Conditions support thread • The fork/join framework is a notification mechanisms. • The Executors hierarchy abstracts the lower-level details of multithreaded programming and offers high-level user-friendly concurrency constructs. the call() method of a Callable implementation returns a value.util.Concurrency Using java. It is a thread pool for running fork/join • ThreadFactory is an interface that is tasks—i. Applying Atomic Variables and Locks • A lock ensures that only one thread accesses a shared resource at a time. it executes an instance of meant for creating threads instead of • Java provides an efficient ForkJoinTask. it takes (or “steals”) work from other threads that are still busy doing some work.e. • The Exchanger class is meant for exchanging data between two threads. • This framework is very useful for modeling "divide and conquer" problems. thread-like entity representing a task which defines methods such as fork() and join(). . This class is useful when two threads need to synchronize between them and continuously exchange data. • Future represents objects that contain a value that is returned by a thread in future. when a worker thread completes its work and is free. • CountDownLatch allows one or more threads to wait for a countdown to complete.. Once the task completes. When a portable means of executing a certain condition is not satisfied. • The fork/join framework uses the work-stealing algorithm—i. variables where one needs to acquire new Thread(). a program with decent parallelism. platform in order to exploit multiple Using Executors and ThreadPools processors.. • A thread pool is a collection of threads that can execute tasks. It executes tasks and alternative in the form of atomic explicitly creating threads by calling manages their lifecycles.e. • The work-stealing technique results in a decent load balancing thread management with minimal synchronization cost. • Phaser is useful feature when few independent threads have to work in phases to complete a task. and release a lock just to carry out • ForkJoinTask<V> is a lightweight primitive operations on variables. thread can wait for another thread to • The framework is an implementation satisfy that condition. • ForkJoinPool is the most important class for the fork/join framework. • The Callable interface represents a task that needs to be completed by a thread. A semaphore maintains a counter to specify number of resources that the semaphore controls.

Concurrency .

Title Authors Edition & Publication Date Pages Publisher ISBN-13 List Price Amazon URL Blog Apress URL Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805 S G Ganesh and Tushar Sharma 1 edition (February 27.99 http://amzn.blogspot.com/9781430247647 A MUST READ FOR CRACKING THE OCPJP 7 EXAM WITH EASE! .apress.in http://www.com/1430247649 http://ocpjp7. 2013) 656 Apress 978-1430247647 US $45.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.