To understand the simple Java Socket Thread sever, we need to know the Networking and Thread. This post presents a simple sockets-based program to introduce the concepts of sockets and multi-threaded programming.

First, you need to know What are Sockets and know how client and server communicates. Second, if you only have single thread of sever, your client is waiting in queue. So a multi-threaded program performs multiple tasks at one time such as fielding simultaneous requests from many client programs.

The Socket Communications can give you a whole picture.

But only Threads server is not enough. So we can add Thread Pool to recycle our threads. You can create your own thread pool, like this or use Java 1.5 Thread Pool.

Reference:
1. Server Thread Code for Java

2. Sockets programming in Java

3. Advanced Socket Programming

4. A process-driven approach to avoid thread death

5. Programming Java threads in the real world, Part 8

6. Sockets programming in Java

7. Write your own threaded discussion forum: The communications and server components, part 2

When the main thread in a single-threaded application throws an uncaught exception, you are likely to notice because the stack trace is printed on the console (and because the program stops). But in a multithreaded application, especially one that runs as a server and is not attached to a console, thread death may be a less noticeable event, resulting in partial system failures that can cause confusing application behavior.

If we found a thread is dying due to an uncaught exception, the answer is simple: catch the exception at an appropriate place so that you can keep going. For example,

class SaferPoolWorker extends Thread {
    public void run() {
        IncomingResponse ir;

        while (true) {
            ir = (IncomingResponse) queue.getNext();
            PlugIn plugIn = findPlugIn(ir.getResponseId());
            if (plugIn != null) {
                try {
                    plugIn.handleMessage(ir.getResponse());
                }
                catch (RuntimeException e) {
                    // log the exception and move on
                }
            }
            else
                log("Unknown plug-in for response " + ir.getResponseId());
        }
    }
}

OK, the thread dies, and your object is gone? No! You said.
The robust multiple thread should Objects do not depend upon particular threads. If a thread should fail, the thread is recreated, and the object continues to run.”
Well, you know Thread can’t be restarted, so we need to recreate a Thread to load current object on it. Here is the example, The taming of the thread.

Reference
1. Hey, where’d my thread go?
2. Thread pools and work queues
3. Java while loop and Threads!
4. How to restart thread in java?
5. Java: How to stop a thread?

The Collections framework introduced iterators for traversing a list or other collection, which optimizes the process of iterating through the elements in a collection. However, the iterators implemented in the java.util Collections classes are fail-fast, which means that if one thread changes a collection while another thread is traversing it through an Iterator, the next Iterator.hasNext() or Iterator.next() call will throw ConcurrentModificationException.

Look at this,
[Only good for single thread]

   List list = new ArrayList();
   Iterator iterator = list.iterator();
   while(iterator.hasNext()) {
     Item item = iterator.next();
     if(isOld(item)) {
   	 iterator.remove();
     }
   }

if this is single-threaded code and need to modify a collection while iterating through it. That’s fine.
But you run in multiple-threaded, how to avoid ConcurrentModificationException?
First you may want to use synchronizedList like this,
[Scalability problems]

  List originalList = new ArrayList();
  List list = Collections.synchronizedList(originalList);
  synchronized(list) {
    Iterator iterator = list.iterator(); // Must be in synchronized block
    while (iterator.hasNext()) {
       Item item = iterator.next();
       if(isOld(item)) {
          iterator.remove();
       }
    }
  }

The bigger problem with the synchronized Collections wrappers(synchronizedList, synchronizedMap), and the earlier Hashtable and Vector classes, is that they synchronize on a single lock. This means that only one thread may access the collection at once, and if one thread is in the process of reading from a Map, all other threads that want to either read from it or write to it must wait.
So what’s perfect way to do?
[Concurrent Collections]

List originalList = new ArrayList();
List list = new CopyOnWriteArrayList(originalList);
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
     Item item = iterator.next();
     if(isOld(item)) {
       iterator.remove();
     }
}

The same story for Map, you should use ConcurrentHashMap instead synchronizedMap.

Reference:
1. Concurrent collections classes
2. Building a better HashMap
3. Java Concurrency Bugs #4: ConcurrentModificationException
4. Taming Tiger: Concurrent collections
5. Introduction to nonblocking algorithms
6. Concurrency: Blocking Queues and You

Sometimes we frustrate for the business logic inside code. So we try to use many different design patterns to solve the problem. But we still experience like, Scattered Business Logic and mixed up with everything else, Business Logic hidden in Code, frameworks for everything else except business knowledge. I have spent some time to use JBoss jBPM to solve those problem, and it’s not perfect but it is better than before.

The basic Advantages to use jBPM is
1. Declarative Programming or Domain Specific Language (DSL)
2. Logic and Data Separation
3. Speed and Scalability
4. Centralization of Knowledge
5. Adopt JBoss Drool then you can set rule with your BPM.

Reference:
JBoss jBPM
JBoss jBPM articles
JBPM Tutorial-Hands On Guide
jBPM Tools Reference Guide
Top 10 Java Workflow Engine

Also my previous post discussed the web flow at front-end. Some projects consider the web flow pattern to combine with jBPM and make web page and business logic together such as Spring Web Flow and Seam Page Flow.
jBPM and Spring
Integrating jBPM3 With Spring
Seam and JBoss jBPM

At the end, you may be interested how to work with ESB…
JBoss jBPM meets ESB
ESB Service Orchestration with JBPM

You can use assertions to detect errors that may otherwise go unnoticed. Assertions contain Boolean expressions that define the correct state of your program at specific points in the program source code.
Reduce to use try/catch/finally to throw an exception instead of assertions.

Basic assertion helps you
1. Presents an overview of design by contract
2. Presents an overview of assertions
3. Shows how to roll your own assertion capabilities
4. Describes the new assertion facility
5. Shows how to use the new assertion facility
6. Offers guidelines for using assertions
7. Presents examples of how to use assertions

But you should watch the pitfall, too.

Reference:
Using Assertions in Java Technology
Programming With Assertions
Develop code using assertions

The world of dynamic web applications offers various ways for a client and server to interact. Two approaches are particularly well suited for situations when information on the server changes frequently. These approaches are: HTTP Streaming, and Client Polling (JavaScript Polling).

In HTTP streaming, the client/server connection is left open for an extended period of time so that data is streamed from the server to the client. This approach is also known as server-side push, reverse Ajax, or comet. As information changes on the server, updates are pushed to the client.

With Client Polling, the browser periodically issues an XMLHttpRequest call to obtain new information from the server. For example, a client can send an XMLHttpRequest to the server every five seconds to get new information. This approach is also known as periodic refresh.

Look at this, Using a Javascript-Centric View Tier. Demo: here.

Or you want to try the reusable component, Poller – YUI3 Component

Reference:
JavaScript Timing Events

Last time I posted Using server push in general. This post I focus on Java server-side implementation.

First We talk about AJAX Push. Ajax Push enables real-time collaborative features, because everyone can be instantly aware of each others actions. The underlying mechanism for Ajax Push is HTTP protocol inversion (also known as long polling). This technique involves holding a connection open from the browser client to the server with a blocking request, and then fulfilling that request when some state change in the application triggers an update to the presentation. For more, see here.

How do we use it at Java web server? basically the server needs to implement so called Asynchronous Request Processing. What happens in synchronous HTTP where the server is blocking on incoming and outgoing I/O is that you end up having a thread consumed per client connection. This eats up memory and valuable thread resources. Therefore, each server has their way to handle those problem.

1. Apache Tomcat 6 Comet Processor and JBoss 4.2.3
Asynchronous HTTP Request Processing

2. Sun Glassfish Grizzly Plugin
Grizzly part III: Asynchronous Request Processing (ARP)

Reference:
Asynchronous Ajax for Revolutionary Web Applications

Update: 2009-06-02
Developing with Comet and Java

My friend said “Look, the HTTP response from Goolge is strange!”.

Google’s Web site responds:

HTTP/1.1 200 OK
Server: GWS/2.0
Date: Tue, 21 May 2002 12:34:56 GMT
Transfer-Encoding: chunked
Content-Encoding: gzip
Content-Type: text/html
Cache-control: private
Set-Cookie: PREF=ID=58c005a7065c0996:TM=1021283456:LM=1021283456:S=OLJcXi3RhSE;
domain=.google.com; path=/; expires=Sun, 17-Jan-2038 19:14:07 GMT

(Web content compressed with gzip)

I told him “Have you experience the web page slow? then try to use HTTP compression”.
Of interest in this response is that the Web content is of a format that cannot be printed, binary. Because my browser specified in its request that it accepts gzip (GNU zip) encoding, Google chose to encode the response with gzip. This is a popular compression algorithm that allows for a quicker transfer due to the smaller size of the HTTP response. Again this is very common skill but it’s useful.

Reference:
1. Using HTTP Compression

2. HTTP Compression Speeds up the Web

3. Compress data streams in Java with GZIP and Zip

4. Compressing web content with GZip and Filter

5. Speed up your Web pages

1. JFreeChar

2. Open Flash Chart

3. AmCharts – flash view

4. Ejschart – Pure Javascript chart tool

5. JS Charts – Free Javascript Chart Generator

update: 04-14-2009
You can choose between web generators, flash, javascript libraries, Silverlight or PHP classes.
25 great free resources for making charts

Before Rich Internet Application (RIA) comes to web application, we have to deal with the HTTP rule to handle flow within pages. My friend doesn’t know the problem why page control is so difficult. I think it is great to review those scenarios.

1. HTTP is stateless and synchronous. When user is adding stuff into shopping cart, you need to do session tracking. Because page and page needs to share user’s state.

Beginning HTTPSession from novice to professional.

2. When user submits the shopping form, and send to server, you need to know how to do with success, fail, or redirect from server. The user experience doesn’t have nervous to your response. Here is some useful tips.

Redirect After Post
GET after POST
How to redirect a web page, the smart way
Use standard redirects: don’t break the back button!
Redirect in response to POST transaction

3. When your pages have to keep server-side navigation history of visited Web pages and visited named sequences of Web pages, also known as Web flows. Web flows is more complicate, so I usually recommend to adapt framework.

Enable backwards navigation through Web applications
Spring Web Flow 2: A boon to JSF developers
Spring Web Flow for better workflow management in JSF
Spring Web Flow Examined

You may ask “Why should I know this?”, because those are the basic HTTP concept, and if you are interested, you can think more how they work in AJAX and RESTFul service. Enjoy!