| Author |
Two questions uppon a deitel's project
|
Nick Petas
Ranch Hand
Joined: Jan 31, 2007
Posts: 38
|
|
I am reading a deitel book and I am in the chapter 26 about multithreading.
There is a project there with the following code :
SharedBufferTest.java
Buffer.java
Producer.java
Consumer.java
UnsynchronizedBuffer.java
My first question is why we declare the InterruptedException in the interface and the second question is when we can use object without declaration as we do in SharedBufferTest.java with Producer and Consumer objects.
Thank you.
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3035
|
|
Declaring the InterruptedException indicates the task may take some time, may block execution, and may be interrupted by some other process. The InterruptedException is a checked exception, which means it needs to be handled by client code, and having as part of the method signature in the interface suggests to users of the interface that they need to handle cases where the InterruptedException may occur. Not all implementations will use throw the exception, but perhaps one may throw it, so the caller has to be able to handle it.
and the second question is when we can use object without declaration as we do in SharedBufferTest.java with Producer and Consumer objects.
You can do it whenever you need to create an Object but don't need to hold on to a local reference to it. The main method in the test class needs to create the Producer and Consumer in order to call the 'execute' command, but main method doesn't do anything else with the Producer/Consumer objects. The main method just needs to pass the references to other classes/methods. So why hold on to a reference itself?
|
Steve
|
 |
Nick Petas
Ranch Hand
Joined: Jan 31, 2007
Posts: 38
|
|
|
Probably the author is doing so because he uses the same interface with other class implementations provided by java api that have corresponding methods thate throw InterruptedException errors like ArrayBlockingQueue put() and take().
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3035
|
|
Nick Petas wrote:Probably the author is doing so because he uses the same interface with other class implementations provided by java api that have corresponding methods thate throw InterruptedException errors like ArrayBlockingQueue put() and take().
Possibly, but that is an implementation detail. All it says for certain is that the task can be interrupted via Thread#interrupt(), and that the method itself does not handle the interruption, the caller needs to.
|
 |
 |
|
|
subject: Two questions uppon a deitel's project
|
|
|