Java is a powerful programming language and, in order to become a productive programmer, one of the best books to read is Effective Java by Joshua Bloch. In it, one can learn about how to use the object-oriented capabilities of the language to build software with quality attributes such as maintability and flexibility.
Generics
Since version 5, Java also provides constructs for generic programming which we are going to explore now.
Generics allow programmers to construct generic data structures. Java already provides generic lists and maps which we have been using in the previous applications we wrote. They are called generic simply because they allow for any kind of objects without any constraints.
Generic Memorizer
Write a Java class which implements a generic memorizer class that remembers the last five values it was asked to memorize. A test program should instantiate an Integer as well as a String memorizer, make them memorize ten values (of course, only the last five values are going to be memorized) and display their contents on screen.
RandomElement
Write a Java class called RandomElement which contains one method called takeOne which return a random element from any collection passed as a parameter. A test program should then create a collection of a specific kind and check whether takeOne works as expected. (takeOne needs to be a generic method).
Concurrency
Java provides various constructs and libraries which allow the programmer to write concurrent programs. The basic capabilities include Threads and Runnables.
MultithreadedCounter
Write a concurrent Java program which creates two distinct threads that respectively increments and decrements a volatile integer variable initialised to 0, waits for 10 seconds then stops the two threads and displays the value stored in the variable.
Modify the program to create 50 incrementer threads and 50 decrementer threads. What do you notice?
Modify the program to use an Executor instead. Is it better? What is the difference between the shutdown and shutdownNow methods?
ProducersAndConsumers
Write a Java program that creates 10 producers of random numbers between 0 and 999 and 10 consumers. Use a LinkedBlockingQueue with a maximum queue size of 10000 to store the numbers being produced and being consumed. Make sure that the producers and consumers are stopped after 10 seconds.
Future Fibonacci
Write a Java program that slowly calculates the Fibonacci of various numbers concurrently. The program should pause for 5 seconds while the calculations are being done and display all completed results. Then the program should pause for enough time for the remaining calculations to be done and display the remaining results. The program should used Futures.
Leave a Reply