Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of good multithreaded Java code? [closed]

I want to study some good multi-threaded Java code. Could anyone please suggest some examples ? Is Apache web server a good pick ?

Thanks, Abhinav.

like image 972
abhinav Avatar asked Jan 29 '10 08:01

abhinav


2 Answers

I'd recommend you to have a look at this book. It covers almost everything about java and concurrency/multithreading, including coding principles and many examples.

like image 83
b_erb Avatar answered Sep 22 '22 01:09

b_erb


I would strongly recommend you read - at least twice - (I am on my 4th reading now) the superb The secrets of Concurrency that Dr. Heinz M. Kabutz has generously made public on his website.

Topics include:

The Law of the Sabotaged Doorbell
The Law of the Distracted Spearfisherman
The Law of the Overstocked Haberdashery
The Law of the Blind Spot
The Law of the Leaked Memo
The Law of the Corrupt Politician
The Law of the Micromanager
The Law of Cretan Driving
The Law of Sudden Riches
The Law of the Uneaten Lutefisk
The Law of the Xerox Copier

All are both entertaining and extremely informative.

Where else but in the Overstocked Haberdashery will you find code like:

public class ThreadCreationTest {
  public static void main(String[] args) throws InterruptedException {
    final AtomicInteger threads_created = new AtomicInteger(0);
    while (true) {
      final CountDownLatch latch = new CountDownLatch(1);
      new Thread() {
        { start(); }
        public void run() {
          latch.countDown();
          synchronized (this) {
            System.out.println("threads created: " +
                threads_created.incrementAndGet());
            try {
              wait();
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
        }
      };
      latch.await();
    }
  }
}

where he not only uses a CountDownLatch and an AtomicInteger and synchronized(this) and handles an InterruptedException apropriately, he even uses a double brace initialiser to start the thread!! Now if that is not epic java what is?

like image 33
OldCurmudgeon Avatar answered Sep 19 '22 01:09

OldCurmudgeon