Let us quickly review whatever we learnt about Design Patterns in the previous few chapters
• A design pattern describes a proven solution to a recurring design problem, placing particular emphasis on the context and forces surrounding the problem, and the consequences and impact of the solution
• There are 5 design patterns in the SCWCD Exam:
o Value Object Pattern
o Data Access Object Pattern
o Business Delegate Pattern
o Model View Controller Pattern &
o Front Controller Pattern
• The Value Object pattern provides the best way to exchange data across tiers or system boundaries, especially when there is network communication involved. This is a pattern that solves performance issues around network latency
• The DAO pattern provides the connection between the business logic tier and the resource (usually a database) tier. The Data Access Object represents a general interface to the resources layer: It handles all calls to it. JDBC is the most commonly used example of this
• The Business Delegate pattern reduces the dependency between tiers. It is an attempt to make tiers interchangeable so one can access or utilize the services of any other
• The Model-View-Controller architecture compartmentalizes the data and business logic (model) from the presentation (view) from the user action interpreter (controller).
• The Front Controller pattern presents one entry point to a Web site or service. It provides a centralized entry point that controls and manages Web request handling. It eliminates the dependency of the user on a direct resource.
The Key Terms we learnt in the previous few chapters are:
• Design Patterns
• Model-View-Controller
• Value Object
• Data Access Object
• Front Controller
• Business Delegate
Previous Chapter: Chapter 58 - Other Design Patterns
Next Chapter: Self Test - Chapters 51 to 58
Topics Covered in the Blog - Synopsis
Showing posts with label quick review. Show all posts
Showing posts with label quick review. Show all posts
Friday, April 29, 2011
Quick Recap: Chapters 47 to 50
Let us quickly review what we learnt about the Web Application Deployment and the Deployment Descriptor web.xml in the previous few chapters.
Web Application Folder Structure:
1. The WEB-INF is the root directory of any Web Application
2. This directory contains two folders /classes – to hold all the class files and /lib to hold all the JAR files
3. The web.xml file also resides in WEB-INF Folder
Elements of a Deployment Descriptor:
The deployment descriptor has 77 elements but the most important ones are:
1. C = < context-param >
2. L = < listener >
3. S = < servlet >
4. S = < servlet-mapping >
5. S = < session-config >
6. W = < welcome-file-list >
7. E = < error-page >
8. T = < taglib >
9. S = < security-constraint >
10. L = < login-config >
11. S = < security-role >
Exception Handling:
You can specify the exception handling declaratively in the deployment descriptor. You do this with the error-page element and the exception-type subelement like so:
< web-app >
< error-page >
< exception-type > javax.servlet.ServletException < / exception-type >
< location > /servlet/ErrorDisplay < / location >
< / error-page >
< / web-app >
Application Security:
• Application Security is an important aspect of any web application. Our application should be prepared to handle atleast a minimum level of attack.
• Authentication is the process by which the system verifies if a user is who he really says he is
• Authorization is the process by which we place access control restrictions on the various resources of the system
• Authentication can be of 4 types:
o HTTP Basic Authentication
o HTTP Digest Authentication
o HTTPS Client Authentication &
o Form Based Authentication
Key Terms we learnt in these chapters are:
• Web application
• Web archive file
• WebApp deployment descriptor
• Authentication, authorization
• Security constraint
Previous Chapter: Chapter 50 - Web Application Security
Next Chapter: Self Test - Chapters 47 to 50
Web Application Folder Structure:
1. The WEB-INF is the root directory of any Web Application
2. This directory contains two folders /classes – to hold all the class files and /lib to hold all the JAR files
3. The web.xml file also resides in WEB-INF Folder
Elements of a Deployment Descriptor:
The deployment descriptor has 77 elements but the most important ones are:
1. C = < context-param >
2. L = < listener >
3. S = < servlet >
4. S = < servlet-mapping >
5. S = < session-config >
6. W = < welcome-file-list >
7. E = < error-page >
8. T = < taglib >
9. S = < security-constraint >
10. L = < login-config >
11. S = < security-role >
Exception Handling:
You can specify the exception handling declaratively in the deployment descriptor. You do this with the error-page element and the exception-type subelement like so:
< web-app >
< error-page >
< exception-type > javax.servlet.ServletException < / exception-type >
< location > /servlet/ErrorDisplay < / location >
< / error-page >
< / web-app >
Application Security:
• Application Security is an important aspect of any web application. Our application should be prepared to handle atleast a minimum level of attack.
• Authentication is the process by which the system verifies if a user is who he really says he is
• Authorization is the process by which we place access control restrictions on the various resources of the system
• Authentication can be of 4 types:
o HTTP Basic Authentication
o HTTP Digest Authentication
o HTTPS Client Authentication &
o Form Based Authentication
Key Terms we learnt in these chapters are:
• Web application
• Web archive file
• WebApp deployment descriptor
• Authentication, authorization
• Security constraint
Previous Chapter: Chapter 50 - Web Application Security
Next Chapter: Self Test - Chapters 47 to 50
Labels:
authentication,
authorization,
deployment of web application,
getting scwcd certified,
quick recap,
quick review,
scwcd certification
| Reactions: |
Tuesday, March 1, 2011
Quick Recap: Chapters 1 to 5
Let us quickly go over the concepts we have covered in the past few chapters.
JSP & Servlet History
• ARPANET was the initial backbone based on which Internet was built
• Tim Berners Lee paved the way for the current day Internet and World Wide Web
• CGI helped people transfer data from one computer to another
• Because CGI was not scalable, people looked out for better alternatives
• JSP and Servlets became an easier and a more scalable alternative to CGI
Advantages of Using Servlets
a. They are faster than CGI scripts because each CGI script produces an entirely new process that takes a lot of time to execute, whereas a servlet creates only a new thread.
b. Servlet API is standard and available easily on the internet (like JSPs)
c. Servlets have the advantages like ease of development & platform independence (like Java)
d. They can access all the J2SE and J2EE APIs
e. Can take the full advantage & capabilities of the Java programming language
Advantages of Using JSPs
a. Write Once, Run Anywhere
b. Code Re-use
c. Support for Scripting
d. Supports Actions
e. Supports both Static & Dynamic Content
f. Supports N-tier Enterprise Application Architecture
g. Superior Quality Documentation & Examples (All over the internet)
h. Reusable Tag Libraries
Web Servers & Servlet Containers
• A web server is the server on which our J2EE application runs
• A Servlet container is similar to a JVM for java programs and executes our Servlets
• Data is transferred using the request/response model
JSP to Servlet Conversion
• A JSP file gets converted into a Servlet at run time
• The web server (Ex: Tomcat) does the conversion of the JSP
• The web server invokes the converted Servlet version of the JSP page, every time the JSP is invoked.
Previous Chapter: Chapter 5 - JSP to Servlet Conversion
Next Chapter: Self Test - Chapters 1 to 5
JSP & Servlet History
• ARPANET was the initial backbone based on which Internet was built
• Tim Berners Lee paved the way for the current day Internet and World Wide Web
• CGI helped people transfer data from one computer to another
• Because CGI was not scalable, people looked out for better alternatives
• JSP and Servlets became an easier and a more scalable alternative to CGI
Advantages of Using Servlets
a. They are faster than CGI scripts because each CGI script produces an entirely new process that takes a lot of time to execute, whereas a servlet creates only a new thread.
b. Servlet API is standard and available easily on the internet (like JSPs)
c. Servlets have the advantages like ease of development & platform independence (like Java)
d. They can access all the J2SE and J2EE APIs
e. Can take the full advantage & capabilities of the Java programming language
Advantages of Using JSPs
a. Write Once, Run Anywhere
b. Code Re-use
c. Support for Scripting
d. Supports Actions
e. Supports both Static & Dynamic Content
f. Supports N-tier Enterprise Application Architecture
g. Superior Quality Documentation & Examples (All over the internet)
h. Reusable Tag Libraries
Web Servers & Servlet Containers
• A web server is the server on which our J2EE application runs
• A Servlet container is similar to a JVM for java programs and executes our Servlets
• Data is transferred using the request/response model
JSP to Servlet Conversion
• A JSP file gets converted into a Servlet at run time
• The web server (Ex: Tomcat) does the conversion of the JSP
• The web server invokes the converted Servlet version of the JSP page, every time the JSP is invoked.
Previous Chapter: Chapter 5 - JSP to Servlet Conversion
Next Chapter: Self Test - Chapters 1 to 5
Labels:
arpanet,
internet history,
j2ee history,
jsp,
jsp and servlets,
quick recap,
quick review,
scwcd,
scwcd certification,
scwcd exam,
servlets,
servlets and jsps
| Reactions: |
Saturday, February 26, 2011
Self Test: Chapters 55 to 61
This is going to be the last self test chapter in our SCJP Exam series. The following questions will help you judge your expertise about threads that you learnt just now.
Questions:
Question 1
The following block of code creates a Thread using a Runnable target:
Runnable r = new MyRunnable();
Thread SimpleThreadExample = new Thread(r);
Which of the following classes can be used to create the target, so that the preceding code compiles correctly?
A. public class MyRunnable extends Runnable{public void run(){}}
B. public class MyRunnable extends Object{public void run(){}}
C. public class MyRunnable implements Runnable{public void run(){}}
D. public class MyRunnable implements Runnable{void run(){}}
E. public class MyRunnable implements Runnable{public void start(){}}
Question 2
Given:
3. class SimpleThreadExample extends Thread {
4. public static void main(String [] args) {
5. SimpleThreadExample t = new SimpleThreadExample();
6. Thread x = new Thread(t);
7. x.start();
8. }
9. public void run() {
10. for(int i=0;i<3;++i) {
11. System.out.print(i + "..");
12. }
13. }
14. }
What is the result of this code?
A. Compilation fails
B. 1..2..3..
C. 0..1..2..3..
D. 0..1..2..
E. An exception occurs at runtime
Question 3
Given:
3. class Test {
4. public static void main(String [] args) {
5. printStuff(args);
6. }
7. public static void printStuff(String[] lines) {
8. for(int i=0;i < lines.length;i++){
9. System.out.println(lines[i]);
10. Thread.currentThread().sleep(1000);
11. }
12. }
13. }
The static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?
A. Each String in the array lines will output, with a 1-second pause between lines
B. Each String in the array lines will output, with no pause in between because this method is not executed in a Thread
C. Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread
D. This code will not compile
E. Each String in the lines array will print, with at least a one-second pause between lines
Question 4
Assume you have a class that holds two private variables: x and y. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)
A. public int read(){return x+y;}
B. public void set(int x, int y){this.x=x;this.y=y;}
C. public synchronized int read(){return x+y;}
D. public synchronized void set(int x, int y){this.x=x;this.y=y;}
E. public int read(){synchronized(x){return x+y;}}
F. public void set(int x, int y){synchronized(x){this.x=x;this.y=y;}}
G. public int read(){synchronized(x){return x+y;}}
H. public void set(int x, int y){synchronized(y){this.x=x;this.y=y;}}
I. public synchronized(this) int read(){return x+y;}
J. public synchronized(this) void set(int x, int y){this.x=x;this.y=y;}
K. public int read(){synchronized(this){return x+y;}}
L. public void set(int x, int y){synchronized(this){this.x=x;this.y=y;}}
Question 5
Given:
1. public class TestWaitMethod {
2. public static void main(String [] args) {
3. System.out.print("1 ");
4. synchronized(args){
5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. }
13. }
What is the result of trying to compile and run this program?
A. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7
B. 1 2 3
C. 1 3
D. 1 2
E. At runtime, it throws an IllegalMonitorStateException when trying to wait
F. It will fail to compile because it has to be synchronized on the this object
Question 6
Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
A. After object B is notified, or after two seconds
B. After the lock on B is released, or after two seconds
C. Two seconds after object B is notified
D. Two seconds after lock B is released
Question 7
Which are true? (Choose all that apply.)
A. The notifyAll() method must be called from a synchronized context
B. To call wait(), an object must own the lock on the thread
C. The notify() method is defined in class java.lang.Thread
D. When a thread is waiting as a result of wait(), it releases its lock
E. The notify() method causes a thread to immediately release its lock
F. The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they’re waiting on
Question 8
Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:
public class MyErrorLoggingUtilClass {
private StringBuilder contents = new StringBuilder();
public void log(String message) {
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());
contents.append(message);
contents.append("\n");
}
public String getLogMessages() { return contents.toString(); }
}
How can we ensure that instances of this class can be safely used by multiple threads?
A. This class is already thread-safe
B. Replacing StringBuilder with StringBuffer will make this class thread-safe
C. Synchronize the log() method only
D. Synchronize the getLogMessages() method only
E. Synchronize both log() and getLogMessages()
F. This class cannot be made thread-safe
Question 9
Given:
public static synchronized void main(String[] args) throws
InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}
What is the result of this code?
A. It prints X and exits
B. It prints X and never exits
C. It prints XY and exits almost immeditately
D. It prints XY with a 10-second delay between X and Y
E. It prints XY with a 10000-second delay between X and Y
F. The code does not compile
G. An exception is thrown at runtime
Question 10
Given:
class SimpleThreadExample extends Thread {
SimpleThreadExample() {
System.out.print(" SimpleThreadExample");
}
public void run() {
System.out.print(" aaa");
}
public void run(String s) {
System.out.print(" bbb");
}
}
public class TestThreads {
public static void main (String [] args) {
Thread t = new SimpleThreadExample() {
public void run() {
System.out.print(" ccc");
}
};
t.start();
} }
What is the result?
A. ccc
B. SimpleThreadExample ccc
C. SimpleThreadExample aaa
D. ccc aaa
E. ccc aaa bbb
F. aaa ccc
G. Compilation fails
H. An exception is thrown at runtime
Question 11
Given:
public class ExampleThread {
synchronized void a() { doSomething(); }
static synchronized void b() { doSomething(); }
static void doSomething() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
public static void main(String[] args) {
final ExampleThread x = new ExampleThread();
final ExampleThread y = new ExampleThread();
Runnable runnable = new Runnable() {
public void run() {
int option = (int) (Math.random() * 4);
switch (option) {
case 0: x.a(); break;
case 1: x.b(); break;
case 2: y.a(); break;
case 3: y.b(); break;
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
Which of the following pairs of method invocations could NEVER be executing at the same time? (Choose all that apply.)
A. x.a() in thread1, and x.a() in thread2
B. x.a() in thread1, and x.b() in thread2
C. x.a() in thread1, and y.a() in thread2
D. x.a() in thread1, and y.b() in thread2
E. x.b() in thread1, and x.a() in thread2
F. x.b() in thread1, and x.b() in thread2
G. x.b() in thread1, and y.a() in thread2
H. x.b() in thread1, and y.b() in thread2
Question 12
Given:
public class MultipleThreadExample {
static Thread cena, orton;
public static void main(String[] args) {
cena = new Thread() {
public void run() {
System.out.println("A");
try {
orton.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
orton = new Thread() {
public void run() {
System.out.println("D");
try {
cena.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
cena.start();
orton.start();
}
}
Which letters will eventually appear somewhere in the output? (Choose all that apply.)
A. A
B. B
C. C
D. D
E. E
F. F
G. The answer cannot be reliably determined
H. The code does not compile
Question 13
Given:
3. public class Runner implements Runnable {
4. void go(long id) {
5. System.out.println(id);
6. }
7. public static void main(String[] args) {
8. System.out.print(Thread.currentThread().getId() + " ");
9. // insert code here
10. }
11. public void run() { go(Thread.currentThread().getId()); }
12. }
And given the following five fragments:
I. new Runner().run();
II. new Runner().start();
III. new Thread(new Runner());
IV. new Thread(new Runner()).run();
V. new Thread(new Runner()).start();
When the five fragments are inserted, one at a time at line 9, which are true? (Choose all that apply.)
A. All five will compile
B. Only one might produce the output 4 4
C. Only one might produce the output 4 2
D. Exactly two might produce the output 4 4
E. Exactly two might produce the output 4 2
F. Exactly three might produce the output 4 4
G. Exactly three might produce the output 4 2
Question 14
Given:
3. public class Awesome implements Runnable {
4. public static void main(String[] args) {
5. Thread t = new Thread(new Awesome());
6. t.start();
7. System.out.print("a1 ");
8. t.join();
9. System.out.print("a2 ");
10. }
11. public void run() {
12. System.out.print("b1 ");
13. System.out.print("b2 ");
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output could be b1 b2 a1 a2
C. The output could be a1 a2 b1 b2
D. The output could be a1 b1 b2 a2
E. The output could be a1 b1 a2 b2
F. An exception is thrown at runtime
Question 15
Given:
3. class Friends {
4. static long flag = 0;
5. // insert code here
6. if(flag == 0) flag = id;
7. for(int x = 1; x < 3; x++) {
8. if(flag == id) System.out.print("yo ");
9. else System.out.print("Friend ");
10. }
11. }
12. }
13. public class FriendsHangOut implements Runnable {
14. static Friends d;
15. public static void main(String[] args) {
16. new FriendsHangOut().go();
17. }
18. void go() {
19. d = new Friends();
20. new Thread(new FriendsHangOut()).start();
21. new Thread(new FriendsHangOut()).start();
22. }
23. public void run() {
24. d.chat(Thread.currentThread().getId());
25. }
26. }
And given these two fragments:
I. synchronized void chat(long id) {
II. void chat(long id) {
When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be yo Friend Friend yo
E. With fragment I, the output could be Friend Friend yo yo
F. With fragment II, the output could be yo Friend Friend yo
Answers:
Answer 1
C is correct. The class implements the Runnable interface with a legal run() method.
A is incorrect because interfaces are implemented, not extended. B is incorrect because even though the class has a valid public void run() method, it does not implement the Runnable interface. D is incorrect because the run() method must be public. E is incorrect because the method to implement is run(), not start().
Answer 2
D is correct. The thread SimpleThreadExample will start and loop three times (from 0 to 2).
A is incorrect because the Thread class implements the Runnable interface; therefore, in line 5, Thread can take an object of type Thread as an argument in the constructor (this is NOT recommended). B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.
Answer 3
D is correct. The sleep() method must be enclosed in a try/catch block, or the method printStuff() must declare it throws the InterruptedException.
E is incorrect, but it would be correct if the InterruptedException was dealt with (A is too precise). B is incorrect (even if the InterruptedException was dealt with) because all Java code, including the main() method, runs in threads. C is incorrect. The sleep() method is static, it always affects the currently executing thread.
Answer 4
B and F are correct. By marking the methods as synchronized, the threads will get the lock of the this object before proceeding. Only one thread will be setting or reading at any given moment, thereby assuring that read() always returns the addition of a valid pair.
A is incorrect because it is not synchronized; therefore, there is no guarantee that the values added by the read() method belong to the same pair. C and D are incorrect; only objects can be used to synchronize on. E fails—it is not possible to select other objects (even this) to synchronize on when declaring a method as synchronized.
Answer 5
D is correct. 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. It’s frozen at line 7.
A is incorrect; IllegalMonitorStateException is an unchecked exception. B and C are incorrect; 3 will never be printed, since this program will wait forever. E is incorrect because IllegalMonitorStateException will never be thrown because the wait() is done on args within a block of code synchronized on args. F is incorrect because any object can be used to synchronize on and this and static don’t mix.
Answer 6
A is correct. Either of the two events will make the thread a candidate for running again.
B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. C is incorrect because the thread will become a candidate immediately after notification. D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released.
Answer 7
A is correct because notifyAll() (and wait() and notify()) must be called from within a synchronized context. D is a correct statement.
B is incorrect because to call wait(), the thread must own the lock on the object that wait() is being invoked on, not the other way around. C is wrong because notify() is defined in java.lang.Object. E is wrong because notify() will not cause a thread to release its locks. The thread can only release its locks by exiting the synchronized code. F is wrong because notifyAll() notifies all the threads waiting on a particular locked object, not all threads waiting on any object.
Answer 8
E is correct. Synchronizing the public methods is sufficient to make this safe, so F is false. This class is not thread-safe unless some sort of synchronization protects the changing data.
B is not correct because although a StringBuffer is synchonized internally, we call append() multiple times, and nothing would prevent two simultaneous log() calls from mixing up their messages. C and D are not correct because if one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse.
Answer 9
G is correct. The code does not acquire a lock on t before calling t.wait(), so it throws an IllegalMonitorStateException. The method is synchronized, but it’s not synchronized on t so the exception will be thrown. If the wait were placed inside a synchronized(t) block, then the answer would have been D.
Answer 10
B is correct. The first line of main we’re constructing an instance of an anonymous inner class extending from SimpleThreadExample. So the SimpleThreadExample constructor runs and prints SimpleThreadExample. Next, main() invokes start() on the new thread instance, which causes the overridden run() method (the run() method in the anonymous inner class) to be invoked.
Answer 11
A, F, and H. A is a right answer because when synchronized instance methods are called on the same instance, they block each other. F and H can’t happen because synchronized static methods in the same class block each other, regardless of which instance was used to call the methods. (An instance is not required to call static methods; only the class.)
C could happen because synchronized instance methods called on different instances do not block each other. B, D, E, and G could all happen because instance methods and static methods lock on different objects, and do not block each other.
Answer 12
A, C, D, E, and F are correct. This may look like cena and orton are battling to cause the other to sleep() or wait()—but that’s not the case. Since sleep() is a static method, it affects the current thread, which is cena (even though the method is invoked using a reference to orton). That’s misleading but perfectly legal, and the Thread cena is able to sleep with no exception, printing A and C (after at least a 1-second delay). Meanwhile orton tries to call cena.wait()—but orton has not synchronized on cena, so calling cena.wait() immediately causes an IllegalMonitorStateException, and so orton prints D, E, and F. Although the order of the output is somewhat indeterminate (we have no way of knowing whether A is printed before D, for example) it is guaranteed that A, C, D, E, and F will all be printed in some order, eventually—so G is incorrect.
Answer 13
C and D are correct. Fragment I doesn’t start a new thread. Fragment II doesn’t compile. Fragment III creates a new thread but doesn’t start it. Fragment IV creates a new thread and invokes run() directly, but it doesn’t start the new thread. Fragment V creates and starts a new thread.
Answer 14
A is correct. The join() must be placed in a try/catch block. If it were, answers B and D would be correct. The join() causes the main thread to pause and join the end of the other thread, meaning "a2" must come last.
Answer 15
F is correct. With fragment I, the chat method is synchronized, so the two threads can’t swap back and forth. With either fragment, the first output must be yo.
Previous Chapter: Quick Review - Threads
Next Chapter: Other Topics of Importance
Questions:
Question 1
The following block of code creates a Thread using a Runnable target:
Runnable r = new MyRunnable();
Thread SimpleThreadExample = new Thread(r);
Which of the following classes can be used to create the target, so that the preceding code compiles correctly?
A. public class MyRunnable extends Runnable{public void run(){}}
B. public class MyRunnable extends Object{public void run(){}}
C. public class MyRunnable implements Runnable{public void run(){}}
D. public class MyRunnable implements Runnable{void run(){}}
E. public class MyRunnable implements Runnable{public void start(){}}
Question 2
Given:
3. class SimpleThreadExample extends Thread {
4. public static void main(String [] args) {
5. SimpleThreadExample t = new SimpleThreadExample();
6. Thread x = new Thread(t);
7. x.start();
8. }
9. public void run() {
10. for(int i=0;i<3;++i) {
11. System.out.print(i + "..");
12. }
13. }
14. }
What is the result of this code?
A. Compilation fails
B. 1..2..3..
C. 0..1..2..3..
D. 0..1..2..
E. An exception occurs at runtime
Question 3
Given:
3. class Test {
4. public static void main(String [] args) {
5. printStuff(args);
6. }
7. public static void printStuff(String[] lines) {
8. for(int i=0;i < lines.length;i++){
9. System.out.println(lines[i]);
10. Thread.currentThread().sleep(1000);
11. }
12. }
13. }
The static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?
A. Each String in the array lines will output, with a 1-second pause between lines
B. Each String in the array lines will output, with no pause in between because this method is not executed in a Thread
C. Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread
D. This code will not compile
E. Each String in the lines array will print, with at least a one-second pause between lines
Question 4
Assume you have a class that holds two private variables: x and y. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)
A. public int read(){return x+y;}
B. public void set(int x, int y){this.x=x;this.y=y;}
C. public synchronized int read(){return x+y;}
D. public synchronized void set(int x, int y){this.x=x;this.y=y;}
E. public int read(){synchronized(x){return x+y;}}
F. public void set(int x, int y){synchronized(x){this.x=x;this.y=y;}}
G. public int read(){synchronized(x){return x+y;}}
H. public void set(int x, int y){synchronized(y){this.x=x;this.y=y;}}
I. public synchronized(this) int read(){return x+y;}
J. public synchronized(this) void set(int x, int y){this.x=x;this.y=y;}
K. public int read(){synchronized(this){return x+y;}}
L. public void set(int x, int y){synchronized(this){this.x=x;this.y=y;}}
Question 5
Given:
1. public class TestWaitMethod {
2. public static void main(String [] args) {
3. System.out.print("1 ");
4. synchronized(args){
5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. }
13. }
What is the result of trying to compile and run this program?
A. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7
B. 1 2 3
C. 1 3
D. 1 2
E. At runtime, it throws an IllegalMonitorStateException when trying to wait
F. It will fail to compile because it has to be synchronized on the this object
Question 6
Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
A. After object B is notified, or after two seconds
B. After the lock on B is released, or after two seconds
C. Two seconds after object B is notified
D. Two seconds after lock B is released
Question 7
Which are true? (Choose all that apply.)
A. The notifyAll() method must be called from a synchronized context
B. To call wait(), an object must own the lock on the thread
C. The notify() method is defined in class java.lang.Thread
D. When a thread is waiting as a result of wait(), it releases its lock
E. The notify() method causes a thread to immediately release its lock
F. The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they’re waiting on
Question 8
Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:
public class MyErrorLoggingUtilClass {
private StringBuilder contents = new StringBuilder();
public void log(String message) {
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());
contents.append(message);
contents.append("\n");
}
public String getLogMessages() { return contents.toString(); }
}
How can we ensure that instances of this class can be safely used by multiple threads?
A. This class is already thread-safe
B. Replacing StringBuilder with StringBuffer will make this class thread-safe
C. Synchronize the log() method only
D. Synchronize the getLogMessages() method only
E. Synchronize both log() and getLogMessages()
F. This class cannot be made thread-safe
Question 9
Given:
public static synchronized void main(String[] args) throws
InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}
What is the result of this code?
A. It prints X and exits
B. It prints X and never exits
C. It prints XY and exits almost immeditately
D. It prints XY with a 10-second delay between X and Y
E. It prints XY with a 10000-second delay between X and Y
F. The code does not compile
G. An exception is thrown at runtime
Question 10
Given:
class SimpleThreadExample extends Thread {
SimpleThreadExample() {
System.out.print(" SimpleThreadExample");
}
public void run() {
System.out.print(" aaa");
}
public void run(String s) {
System.out.print(" bbb");
}
}
public class TestThreads {
public static void main (String [] args) {
Thread t = new SimpleThreadExample() {
public void run() {
System.out.print(" ccc");
}
};
t.start();
} }
What is the result?
A. ccc
B. SimpleThreadExample ccc
C. SimpleThreadExample aaa
D. ccc aaa
E. ccc aaa bbb
F. aaa ccc
G. Compilation fails
H. An exception is thrown at runtime
Question 11
Given:
public class ExampleThread {
synchronized void a() { doSomething(); }
static synchronized void b() { doSomething(); }
static void doSomething() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
public static void main(String[] args) {
final ExampleThread x = new ExampleThread();
final ExampleThread y = new ExampleThread();
Runnable runnable = new Runnable() {
public void run() {
int option = (int) (Math.random() * 4);
switch (option) {
case 0: x.a(); break;
case 1: x.b(); break;
case 2: y.a(); break;
case 3: y.b(); break;
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
Which of the following pairs of method invocations could NEVER be executing at the same time? (Choose all that apply.)
A. x.a() in thread1, and x.a() in thread2
B. x.a() in thread1, and x.b() in thread2
C. x.a() in thread1, and y.a() in thread2
D. x.a() in thread1, and y.b() in thread2
E. x.b() in thread1, and x.a() in thread2
F. x.b() in thread1, and x.b() in thread2
G. x.b() in thread1, and y.a() in thread2
H. x.b() in thread1, and y.b() in thread2
Question 12
Given:
public class MultipleThreadExample {
static Thread cena, orton;
public static void main(String[] args) {
cena = new Thread() {
public void run() {
System.out.println("A");
try {
orton.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
orton = new Thread() {
public void run() {
System.out.println("D");
try {
cena.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
cena.start();
orton.start();
}
}
Which letters will eventually appear somewhere in the output? (Choose all that apply.)
A. A
B. B
C. C
D. D
E. E
F. F
G. The answer cannot be reliably determined
H. The code does not compile
Question 13
Given:
3. public class Runner implements Runnable {
4. void go(long id) {
5. System.out.println(id);
6. }
7. public static void main(String[] args) {
8. System.out.print(Thread.currentThread().getId() + " ");
9. // insert code here
10. }
11. public void run() { go(Thread.currentThread().getId()); }
12. }
And given the following five fragments:
I. new Runner().run();
II. new Runner().start();
III. new Thread(new Runner());
IV. new Thread(new Runner()).run();
V. new Thread(new Runner()).start();
When the five fragments are inserted, one at a time at line 9, which are true? (Choose all that apply.)
A. All five will compile
B. Only one might produce the output 4 4
C. Only one might produce the output 4 2
D. Exactly two might produce the output 4 4
E. Exactly two might produce the output 4 2
F. Exactly three might produce the output 4 4
G. Exactly three might produce the output 4 2
Question 14
Given:
3. public class Awesome implements Runnable {
4. public static void main(String[] args) {
5. Thread t = new Thread(new Awesome());
6. t.start();
7. System.out.print("a1 ");
8. t.join();
9. System.out.print("a2 ");
10. }
11. public void run() {
12. System.out.print("b1 ");
13. System.out.print("b2 ");
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output could be b1 b2 a1 a2
C. The output could be a1 a2 b1 b2
D. The output could be a1 b1 b2 a2
E. The output could be a1 b1 a2 b2
F. An exception is thrown at runtime
Question 15
Given:
3. class Friends {
4. static long flag = 0;
5. // insert code here
6. if(flag == 0) flag = id;
7. for(int x = 1; x < 3; x++) {
8. if(flag == id) System.out.print("yo ");
9. else System.out.print("Friend ");
10. }
11. }
12. }
13. public class FriendsHangOut implements Runnable {
14. static Friends d;
15. public static void main(String[] args) {
16. new FriendsHangOut().go();
17. }
18. void go() {
19. d = new Friends();
20. new Thread(new FriendsHangOut()).start();
21. new Thread(new FriendsHangOut()).start();
22. }
23. public void run() {
24. d.chat(Thread.currentThread().getId());
25. }
26. }
And given these two fragments:
I. synchronized void chat(long id) {
II. void chat(long id) {
When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be yo Friend Friend yo
E. With fragment I, the output could be Friend Friend yo yo
F. With fragment II, the output could be yo Friend Friend yo
Answers:
Answer 1
C is correct. The class implements the Runnable interface with a legal run() method.
A is incorrect because interfaces are implemented, not extended. B is incorrect because even though the class has a valid public void run() method, it does not implement the Runnable interface. D is incorrect because the run() method must be public. E is incorrect because the method to implement is run(), not start().
Answer 2
D is correct. The thread SimpleThreadExample will start and loop three times (from 0 to 2).
A is incorrect because the Thread class implements the Runnable interface; therefore, in line 5, Thread can take an object of type Thread as an argument in the constructor (this is NOT recommended). B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.
Answer 3
D is correct. The sleep() method must be enclosed in a try/catch block, or the method printStuff() must declare it throws the InterruptedException.
E is incorrect, but it would be correct if the InterruptedException was dealt with (A is too precise). B is incorrect (even if the InterruptedException was dealt with) because all Java code, including the main() method, runs in threads. C is incorrect. The sleep() method is static, it always affects the currently executing thread.
Answer 4
B and F are correct. By marking the methods as synchronized, the threads will get the lock of the this object before proceeding. Only one thread will be setting or reading at any given moment, thereby assuring that read() always returns the addition of a valid pair.
A is incorrect because it is not synchronized; therefore, there is no guarantee that the values added by the read() method belong to the same pair. C and D are incorrect; only objects can be used to synchronize on. E fails—it is not possible to select other objects (even this) to synchronize on when declaring a method as synchronized.
Answer 5
D is correct. 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. It’s frozen at line 7.
A is incorrect; IllegalMonitorStateException is an unchecked exception. B and C are incorrect; 3 will never be printed, since this program will wait forever. E is incorrect because IllegalMonitorStateException will never be thrown because the wait() is done on args within a block of code synchronized on args. F is incorrect because any object can be used to synchronize on and this and static don’t mix.
Answer 6
A is correct. Either of the two events will make the thread a candidate for running again.
B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. C is incorrect because the thread will become a candidate immediately after notification. D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released.
Answer 7
A is correct because notifyAll() (and wait() and notify()) must be called from within a synchronized context. D is a correct statement.
B is incorrect because to call wait(), the thread must own the lock on the object that wait() is being invoked on, not the other way around. C is wrong because notify() is defined in java.lang.Object. E is wrong because notify() will not cause a thread to release its locks. The thread can only release its locks by exiting the synchronized code. F is wrong because notifyAll() notifies all the threads waiting on a particular locked object, not all threads waiting on any object.
Answer 8
E is correct. Synchronizing the public methods is sufficient to make this safe, so F is false. This class is not thread-safe unless some sort of synchronization protects the changing data.
B is not correct because although a StringBuffer is synchonized internally, we call append() multiple times, and nothing would prevent two simultaneous log() calls from mixing up their messages. C and D are not correct because if one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse.
Answer 9
G is correct. The code does not acquire a lock on t before calling t.wait(), so it throws an IllegalMonitorStateException. The method is synchronized, but it’s not synchronized on t so the exception will be thrown. If the wait were placed inside a synchronized(t) block, then the answer would have been D.
Answer 10
B is correct. The first line of main we’re constructing an instance of an anonymous inner class extending from SimpleThreadExample. So the SimpleThreadExample constructor runs and prints SimpleThreadExample. Next, main() invokes start() on the new thread instance, which causes the overridden run() method (the run() method in the anonymous inner class) to be invoked.
Answer 11
A, F, and H. A is a right answer because when synchronized instance methods are called on the same instance, they block each other. F and H can’t happen because synchronized static methods in the same class block each other, regardless of which instance was used to call the methods. (An instance is not required to call static methods; only the class.)
C could happen because synchronized instance methods called on different instances do not block each other. B, D, E, and G could all happen because instance methods and static methods lock on different objects, and do not block each other.
Answer 12
A, C, D, E, and F are correct. This may look like cena and orton are battling to cause the other to sleep() or wait()—but that’s not the case. Since sleep() is a static method, it affects the current thread, which is cena (even though the method is invoked using a reference to orton). That’s misleading but perfectly legal, and the Thread cena is able to sleep with no exception, printing A and C (after at least a 1-second delay). Meanwhile orton tries to call cena.wait()—but orton has not synchronized on cena, so calling cena.wait() immediately causes an IllegalMonitorStateException, and so orton prints D, E, and F. Although the order of the output is somewhat indeterminate (we have no way of knowing whether A is printed before D, for example) it is guaranteed that A, C, D, E, and F will all be printed in some order, eventually—so G is incorrect.
Answer 13
C and D are correct. Fragment I doesn’t start a new thread. Fragment II doesn’t compile. Fragment III creates a new thread but doesn’t start it. Fragment IV creates a new thread and invokes run() directly, but it doesn’t start the new thread. Fragment V creates and starts a new thread.
Answer 14
A is correct. The join() must be placed in a try/catch block. If it were, answers B and D would be correct. The join() causes the main thread to pause and join the end of the other thread, meaning "a2" must come last.
Answer 15
F is correct. With fragment I, the chat method is synchronized, so the two threads can’t swap back and forth. With either fragment, the first output must be yo.
Previous Chapter: Quick Review - Threads
Next Chapter: Other Topics of Importance
Quick Review: Chapters 55 to 61 (Threads)
This is going to be the last quick recap chapter in this SCJP Series. This will cover the important points about Threads.
Defining, Instantiating, and Starting Threads
* Threads can be created by extending Thread and overriding the public void run() method.
* Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. The Runnable object is said to be the target of the thread.
* You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException.
* It is legal to create many Thread objects using the same Runnable object as the target.
* When a Thread object is created, it does not become a thread of execution until its start() method is invoked. When a Thread object exists but hasn’t been started, it is in the new state and is not considered alive.
Transitioning Between Thread States
* Once a new thread is started, it will always enter the runnable state.
* The thread scheduler can move a thread back and forth between the runnable state and the running state.
* For a typical single-processor machine, only one thread can be running at a time, although many threads may be in the runnable state.
* There is no guarantee that the order in which threads were started determines the order in which they’ll run.
* There’s no guarantee that threads will take turns in any fair way. It’s up to the thread scheduler, as determined by the particular virtual machine implementation. If you want a guarantee that your threads will take turns regardless of the underlying JVM, you can use the sleep() method. This prevents one thread from hogging the running process while another thread starves.
* A running thread may enter a blocked/waiting state by a wait(), sleep(), or join() call.
* A running thread may enter a blocked/waiting state because it can’t acquire the lock for a synchronized block of code.
* When the sleep or wait is over, or an object’s lock becomes available, the thread can only reenter the runnable state. It will go directly from waiting to running (well, for all practical purposes anyway).
* A dead thread cannot be started again.
Sleep, Yield, and Join
* Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
* A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it’s interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.
* The sleep() method is a static method that sleeps the currently executing thread’s state. One thread cannot tell another thread to sleep.
* The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.
* If not explicitly set, a thread’s priority will have the same priority as the priority of the thread that created it.
* The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.
* The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.
* When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed. Think of the join() method as saying, “Hey thread, I want to join on to your end. Let me know when you’re done, so I can enter the runnable state.”
Synchronization
* synchronized methods prevent more than one thread from accessing an object’s critical method code simultaneously.
* You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.
* To synchronize a block of code, you must specify an argument that is the object whose lock you want to synchronize on.
* While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object’s unsynchronized code.
* When a thread goes to sleep, its locks will be unavailable to other threads.
* static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.
Thread Communication
* The wait() method lets a thread say, “I got nothing to do, so put me in your waiting pool and notify me when something happens that I care about.”
* The notify() method is used to send a signal to one and only one of the threads that are waiting in that same object’s waiting pool.
* The notify() method can NOT specify which waiting thread to notify.
* The method notifyAll() works in the same way as notify(), only it sends the signal to all of the threads waiting on the object.
* All three methods—wait(), notify(), and notifyAll()—must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.
Deadlocks
* Deadlocking is when thread execution grinds to a halt because the code is waiting for locks to be removed from objects.
* Deadlocking can occur when a locked object attempts to access another locked object that is trying to access the first locked object. In other words, both threads are waiting for each other’s locks to be released; therefore, the locks will never be released!
Previous Chapter: Chapter 61 - Thread Interaction
Next Chapter: Self Test - Chapters 55 to 61
Defining, Instantiating, and Starting Threads
* Threads can be created by extending Thread and overriding the public void run() method.
* Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. The Runnable object is said to be the target of the thread.
* You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException.
* It is legal to create many Thread objects using the same Runnable object as the target.
* When a Thread object is created, it does not become a thread of execution until its start() method is invoked. When a Thread object exists but hasn’t been started, it is in the new state and is not considered alive.
Transitioning Between Thread States
* Once a new thread is started, it will always enter the runnable state.
* The thread scheduler can move a thread back and forth between the runnable state and the running state.
* For a typical single-processor machine, only one thread can be running at a time, although many threads may be in the runnable state.
* There is no guarantee that the order in which threads were started determines the order in which they’ll run.
* There’s no guarantee that threads will take turns in any fair way. It’s up to the thread scheduler, as determined by the particular virtual machine implementation. If you want a guarantee that your threads will take turns regardless of the underlying JVM, you can use the sleep() method. This prevents one thread from hogging the running process while another thread starves.
* A running thread may enter a blocked/waiting state by a wait(), sleep(), or join() call.
* A running thread may enter a blocked/waiting state because it can’t acquire the lock for a synchronized block of code.
* When the sleep or wait is over, or an object’s lock becomes available, the thread can only reenter the runnable state. It will go directly from waiting to running (well, for all practical purposes anyway).
* A dead thread cannot be started again.
Sleep, Yield, and Join
* Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
* A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it’s interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.
* The sleep() method is a static method that sleeps the currently executing thread’s state. One thread cannot tell another thread to sleep.
* The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.
* If not explicitly set, a thread’s priority will have the same priority as the priority of the thread that created it.
* The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.
* The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.
* When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed. Think of the join() method as saying, “Hey thread, I want to join on to your end. Let me know when you’re done, so I can enter the runnable state.”
Synchronization
* synchronized methods prevent more than one thread from accessing an object’s critical method code simultaneously.
* You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.
* To synchronize a block of code, you must specify an argument that is the object whose lock you want to synchronize on.
* While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object’s unsynchronized code.
* When a thread goes to sleep, its locks will be unavailable to other threads.
* static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.
Thread Communication
* The wait() method lets a thread say, “I got nothing to do, so put me in your waiting pool and notify me when something happens that I care about.”
* The notify() method is used to send a signal to one and only one of the threads that are waiting in that same object’s waiting pool.
* The notify() method can NOT specify which waiting thread to notify.
* The method notifyAll() works in the same way as notify(), only it sends the signal to all of the threads waiting on the object.
* All three methods—wait(), notify(), and notifyAll()—must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.
Deadlocks
* Deadlocking is when thread execution grinds to a halt because the code is waiting for locks to be removed from objects.
* Deadlocking can occur when a locked object attempts to access another locked object that is trying to access the first locked object. In other words, both threads are waiting for each other’s locks to be released; therefore, the locks will never be released!
Previous Chapter: Chapter 61 - Thread Interaction
Next Chapter: Self Test - Chapters 55 to 61
Labels:
deadlock,
deadlocks,
java threads,
making threads sleep,
quick recap,
quick review,
runnable,
running,
synchronization,
thread deadlocks,
threads,
thread synchronization,
waiting
| Reactions: |
Friday, February 25, 2011
Quick Review: Chapters 52 to 55 (Inner classes)
Below is a quick recap/review of the previous chapters that we had about inner classes. So, lets get started!!!
Inner Classes
* A “regular” inner class is declared inside the curly braces of another class, but outside any method or other code block.
* An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers. (Never both abstract and final together—remember that abstract must be subclassed, whereas final cannot be subclassed).
* An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class’s members, including those marked private.
* To instantiate an inner class, you must have a reference to an instance of the outer class.
* From code within the enclosing class, you can instantiate the inner class using only the name of the inner class, as follows:
MyInner mi = new MyInner();
* From code outside the enclosing class’s instance methods, you can instantiate the inner class only by using both the inner and outer class names, and a reference to the outer class as follows:
MyOuter mo = new MyOuter();
MyOuter.MyInner inner = mo.new MyInner();
* From code within the inner class, the keyword this holds a reference to the inner class instance. To reference the outer this (in other words, the instance of the outer class that this inner instance is tied to) precede the keyword this with the outer class name as follows: MyOuter.this;
Method-Local Inner Classes
* A method-local inner class is defined within a method of the enclosing class.
* For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code.
* A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final.
* The only modifiers you can apply to a method-local inner class are abstract and final. (Never both at the same time, though.)
Anonymous Inner Classes
* Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.
* An anonymous inner class is always created as part of a statement; don’t forget to close the statement after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a semicolon.
* Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.
* An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.
* An argument-defined inner class is declared, defined, and automatically instantiated as part of a method invocation. The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });
Static Inner Classes
* Static Inner classes are inner classes marked with the static modifier.
* A static nested class is not an inner class, it’s a top-level nested class.
* Because the nested class is static, it does not share any special relationship with an instance of the outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
* Instantiating a static nested class requires using both the outer and nested class names as follows:
BigOuter.Nested n = new BigOuter.Nested();
* A static nested class cannot access non-static members of the outer class, since it does not have an implicit reference to any outer instance (in other words, the nested class instance does not get an outer this reference).
Previous Chapter: Chapter 55 - Static Inner Classes
Next Chapter: Self Test - Chapters 52 to 55
Inner Classes
* A “regular” inner class is declared inside the curly braces of another class, but outside any method or other code block.
* An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers. (Never both abstract and final together—remember that abstract must be subclassed, whereas final cannot be subclassed).
* An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class’s members, including those marked private.
* To instantiate an inner class, you must have a reference to an instance of the outer class.
* From code within the enclosing class, you can instantiate the inner class using only the name of the inner class, as follows:
MyInner mi = new MyInner();
* From code outside the enclosing class’s instance methods, you can instantiate the inner class only by using both the inner and outer class names, and a reference to the outer class as follows:
MyOuter mo = new MyOuter();
MyOuter.MyInner inner = mo.new MyInner();
* From code within the inner class, the keyword this holds a reference to the inner class instance. To reference the outer this (in other words, the instance of the outer class that this inner instance is tied to) precede the keyword this with the outer class name as follows: MyOuter.this;
Method-Local Inner Classes
* A method-local inner class is defined within a method of the enclosing class.
* For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code.
* A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final.
* The only modifiers you can apply to a method-local inner class are abstract and final. (Never both at the same time, though.)
Anonymous Inner Classes
* Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.
* An anonymous inner class is always created as part of a statement; don’t forget to close the statement after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a semicolon.
* Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.
* An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.
* An argument-defined inner class is declared, defined, and automatically instantiated as part of a method invocation. The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });
Static Inner Classes
* Static Inner classes are inner classes marked with the static modifier.
* A static nested class is not an inner class, it’s a top-level nested class.
* Because the nested class is static, it does not share any special relationship with an instance of the outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
* Instantiating a static nested class requires using both the outer and nested class names as follows:
BigOuter.Nested n = new BigOuter.Nested();
* A static nested class cannot access non-static members of the outer class, since it does not have an implicit reference to any outer instance (in other words, the nested class instance does not get an outer this reference).
Previous Chapter: Chapter 55 - Static Inner Classes
Next Chapter: Self Test - Chapters 52 to 55
Labels:
anonymous inner class,
inner class,
inner classes,
method local inner class,
quick recap,
quick review,
static inner class
| Reactions: |
Subscribe to:
Posts (Atom)
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.
