Archive for the 'java' Category

a regular expression String argument. The returned Pattern

Friday, November 3rd, 2006

COMMENTS (?x) Permits whitespace and comments in the pattern. When this mode is in effect, any whitespace in the pattern is ignored, and comments beginning with the # character are ignored to end-of-line. MULTILINE (?m) Turns on multiline mode. In multiline mode, the ^ and $ expressions match just after or just before (respectively) a line separator or the beginning or end of the character sequence. In normal mode, these expressions match only the beginning or end of the entire character sequence. DOTALL (?s) Dot (.) character matches any character, even line separators. By default, the dot expression does not match line separators. This option is equivalent to Perl’s single-line mode, hence the (?s) embedded flag name. CANON_EQ None Enables canonical equivalence. When this flag is specified, characters will be considered a match if and only if their canonical decompositions match. For example, the two-character sequence au030A (Unicode symbol “LATIN SMALL LETTER A” followed by symbol “COMBINING RING ABOVE”) will match the single character u00E5 (”LATIN SMALL LETTER A WITH RING”) when this flag is given. Canonical equivalence is not evaluated by default. See the character map definitions at http://www.unicode.org for canonical-equivalence details. This flag may incur a significant performance penalty. There is no embedded flag expression to enable canonical equivalence. Instances of the Pattern class are immutable; each is tied to a specific regular expression and cannot be modified. Pattern objects are also thread-safe and can be used concurrently by multiple threads. So, once you have a Pattern, what can you do with it? package java.util.regex; public final class Pattern implements java.io.Serializable{ // This is a partial API listing public String pattern() public int flags() public String[] split (CharSequence input, int limit) public String[] split (CharSequence input) 168
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

public String toString(); CharSequence subSequence (int start, int

Friday, November 3rd, 2006

// derived directly from a String printCharSequence (charSequence); // derived from a StringBuffer charSequence = stringBuffer; printCharSequence (charSequence); // Change StringBuffer stringBuffer.setLength (0); stringBuffer.append (”Goodbye cruel world”); // same “immutable” CharSequence yields different result printCharSequence (charSequence); // Derive CharSequence from CharBuffer charSequence = charBuffer; charBuffer.put (”xxxxxxxxxxxxxxxxxxxx”); charBuffer.clear(); charBuffer.put (”Hello World”); charBuffer.flip(); printCharSequence (charSequence); charBuffer.mark(); charBuffer.put (”Seeya”); charBuffer.reset(); printCharSequence (charSequence); charBuffer.clear(); printCharSequence (charSequence); // Changing underlying CharBuffer is reflected in the // read-only CharSequnce interface } private static void printCharSequence (CharSequence cs) { System.out.println (”length=” + cs.length() + “, content=’” + cs.toString() + “‘”); } } Here’s the result of executing CharSequence: length=11, content=’Hello World’length=11, content=’Hello World’length=19, content=’Goodbye cruel world’length=11, content=’Hello World’length=11, content=’Seeya World’length=20, content=’Seeya Worldxxxxxxxxx’ 5.2.2 The Pattern Class The Pattern class encapsulates a regular expression, which is a pattern you want to search for in a target character sequence. Matching regular expressions can be expensive because of the huge number of possible permutations, especially if the pattern will be 165
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

public String toString(); CharSequence subSequence (int start, int

Friday, November 3rd, 2006

applied repeatedly. Most regular expression processors (including Perl, under the covers) compile expressions first, then use this compiled representation to perform pattern detection in the input. The Java regular expression package is no different. Instances of the Pattern class encapsulate a single, compiled regular expression. Let’s take a look at the complete API of Pattern to see how it’s used. Remember, this is not a syntactically complete class file, just the method signatures with the class bodies left out. package java.util.regex; public final class Pattern implements java.io.Serializable { public static final int UNIX_LINES public static final int CASE_INSENSITIVE public static final int COMMENTS public static final int MULTILINE public static final int DOTALL public static final int UNICODE_CASE public static final int CANON_EQ public static boolean matches (String regex, CharSequence input) public static Pattern compile (String regex) public static Pattern compile (String regex, int flags) public String pattern() public int flags() public String[] split (CharSequence input, int limit) public String[] split (CharSequence input) public Matcher matcher (CharSequence input) } The first method listed above, matches(), is a convenience method that does a complete matching operation and returns a boolean indication of whether the regular expression matches the entire input sequence. This is handy because you don’t need to keep track of any objects; just call a simple static method and test the result. public boolean goodAnswer (String answer) { return (Pattern.matches (”[Yy]es|[Yy]|[Tt]rue”, answer)); } This is appropriate for cases in which default settings are acceptable and the test need to be done only once. If you will be checking for the same pattern repeatedly, if you want to find patterns that are subsequences of the input, or if you need to set nondefault options, you should create a Pattern object and make use of its API methods. Note that there are no public constructors for the Pattern class. New instances can be created only by invoking one of the static factory methods. Both forms of compile() take 166
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

public String toString(); CharSequence subSequence (int start, int

Friday, November 3rd, 2006

public String toString(); CharSequence subSequence (int start, int end); } Every character sequence described by CharSequence has a specific length returned by the length() method. Individual characters of the sequence can be fetched by calling charAt() with the index of the desired character position. Character positions start at zero and range to one less than the length, exactly like the familiar String.charAt(). The toString() method returns a String object containing the described sequence of characters. This may be useful, for example, to print the character sequence. As noted earlier, String now implements CharSequence. Both String and CharSequence are immutable, so if CharSequence describes a complete String, the toString() method of CharSequence returns the underlying String object, not a copy. If the backing object is a StringBuffer or a CharBuffer, a new String will be created to hold a copy of the character sequence. Finally, a new CharSequence describing a subrange can be created by calling the subSequence() method. The start and end values are specified in the same way as they are for String.substring(): start must be a valid index of the sequence, end must be greater than start and denotes the index of the last character plus one. In other words, start is the beginning index (inclusive), and end is the ending index (exclusive). The CharSequence interface appears to be immutable because it has no mutator methods, but the underlying implementing object may not be immutable. The CharSequence methods reflect the current state of the underlying object. If that state changes, the information returned by the CharSequence methods will also change (see Example 5-1). If you depend on a CharSequence remaining stable and are unsure of the underlying implementation, invoke the toString() method to make a truly immutable snapshot of the character sequence. Example 5-1. CharSequence interface examples package com.ronsoft.books.nio.regex; import java.nio.CharBuffer; /** * Demonstrate behavior of java.lang.CharSequence as implemented * by String, StringBuffer and CharBuffer. * * @author Ron Hitchens (ron@ronsoft.com) */ public class CharSeq{ public static void main (String [] argv) { StringBuffer stringBuffer = new StringBuffer (”Hello World”); CharBuffer charBuffer = CharBuffer.allocate (20); CharSequence charSequence = “Hello World”; 164
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

The popular Perl[1] scripting language incorporates regular expression

Friday, November 3rd, 2006

was donated to Apache and further enhanced. It has many features and is highly customizable. Jakarta-Regexp was also contributed to Apache but is smaller in scope. The GNU folks offer a regular expression package, gnu.regexp, with some Perl-like features. And IBM has a commercial package known as com.ibm.regex. It also provides many Perl-like features and good Unicode support. For all the details you can stand about the history of regular expressions, types of regex processors, available implementations, and everything you ever wanted to know about regular expression syntax and usage, consult Jeffrey E.F. Friedl’s book Mastering Regular Expressions (O’Reilly). 5.2 The Java Regular Expression API The java.util.regex package contains only two classes for implementing Java regular expression processing. These classes are named Pattern and Matcher. This is only natural when you recall that regular expression processing consists of pattern matching. There is also a new interface defined in java.lang that underpins these new classes. Before looking at Pattern and Matcher, we’ll take a quick look at the new CharSequence abstraction. Additionally, as a convenience, the String class provides some new methods as shortcuts to performing regular expression matching. These are discussed in Section 5.3. 5.2.1 The CharSequence Interface Regular expressions do pattern matching on sequences of characters. While String objects encapsulate character sequences, they are not the only objects capable of doing so. The JDK 1.4 release defines a new interface named CharSequence, which describes a specific, immutable sequence of characters. This new interface is an abstraction to separate the concept of a sequence of characters from specific implementations containing those characters. The venerable String and StringBuffer classes have been retrofitted in JDK 1.4 to implement the CharSequence interface. The new CharBuffer class (introduced in Chapter 2) also implements CharSequence. The CharSequence interface also comes into play in character set mapping (see Chapter 6). The API defined by CharSequence is very simple. It doesn’t take a lot to describe a sequence of characters, after all. package java.lang; public interface CharSequence { int length(); char charAt (int index); 163

Hint: If you are looking for very good and affordable webspace to host and run your j2ee hosting application check Virtualwebstudio j2ee web hosting services

The popular Perl[1] scripting language incorporates regular expression

Friday, November 3rd, 2006

What Is a Regular Expression? Regular expressions derive from a mathematical notation devised by Stephen Kleene in the 1950s for describing regular sets. Regular expressions remained in the realm of mathematics until 1968 when Ken Thompson, a Bell Labs researcher and Unix pioneer, developed a regular expression-based search algorithm eventually integrated into the Unix ed text editor. The g/Regular Expression/p (Global Regular Expression Print) command in ed was so useful, it spawned the standalone grep command. Other regex-based commands followed: sed, awk, lex, egrep, etc. As the uses of regular expressions proliferated and new features were added, the syntax of regular expressions used for text searches diverged from its mathematical origins. Over time, many cooks boiled many pots, and soon there were many flavors of regular expressions. The POSIX (Portable Operating System Interface) standard was first introduced in 1986 and attempts to standardize a broad range of operating-system characteristics. POSIX defines two classes of regular expressions: basic regular expressions (BREs) and extended regular expressions (EREs). Larry Wall released the first version of perl in 1987. Perl was useful because it brought together many powerful features in a single scripting language, not the least of which was regular expression processing woven into the fabric of the language syntax. The first version of Perl used regular expression code derived from James Gosling’s version of the emacs editor. Perl is now at Version 5, which has been universally deployed for about eight years now and has become the benchmark against which most regular expression processors are measured. Regular expression-matching engines fall into two categories: Deterministic Finite Automaton (DFA) and Nondeterministic Finite Automaton (NFA). Their differences have to do with how expressions are compiled and how they are matched against the target. DFA is usually faster because it does more work up front to build a matching tree from which unreachable branches are pruned as matching progresses. NFA can be slower because it performs a more exhaustive search and often needs to backtrack. Although DFA is faster, NFA is more full-featured. It can capture subexpressions, for example, while DFA processors cannot. The java.util.regex engine is NFA and similar in syntax to Perl 5. While regular expressions became an official part of the Java platform with JDK 1.4, by no means is java.util.regex the first regular expression package available for Java. The Apache organization has two open source, regular expression packages: Jakarta-ORO and Jakarta-Regexp, which have been around for quite a while. Jakarta-ORO is the successor to OROMatcher, which 162

Hint: If you are looking for very good and affordable webspace to host and run your j2ee hosting application check Virtualwebstudio j2ee web hosting services

The popular Perl[1] scripting language incorporates regular expression

Friday, November 3rd, 2006

The popular Perl[1] scripting language incorporates regular expression processing directly into its language syntax. As Perl has evolved and grown in popularity, it has added more sophisticated features and has extended the regular expression syntax. Because of its power and flexibility, Perl has become almost ubiquitous and has consequently established a de facto standard for regular expression processing. [1] Practical Extraction and Reporting Language (or Pathologically Eclectic Rubbish Lister, depending on how long you’ve been debugging). The regular expression capabilities provided by the java.util.regex classes track those provided by Perl 5. There are minor differences confined mostly to arcane areas that typical users will rarely encounter. The specifics are detailed in Section 5.4, in Table 5-7, and in the Javadoc API documentation for the java.util.regex.Pattern class. In a Perl script, regular expressions are used inline to match against variable values. This tight integration of regular expression evaluation into the language has made Perl popular for scripting applications in which text files are processed. Until now, Java has been at the other end of the spectrum. Processing text files with Java has been rather cumbersome because of the shortage of built-in tools to process nontrivial patterns in text files. While Java will never reach the level of regular expression integration that Perl enjoys, the new java.util.regex package brings the same level of expressive power to Java. The usage model is necessarily different between Perl (a procedural scripting language) and Java (a compiled, object-oriented[2] language), but the Java regular expression API is easy to use and should now allow Java to easily take on the text-processing tasks traditionally “outsourced” to Perl. [2] Some would argue that Perl is also object-oriented. Perl’s own documentation makes it clear that Perl “objects” are little more than a syntactic illusion. If you want to argue about it, frankly, you’re probably reading the wrong book. 161

Hint: If you are looking for very good and affordable webspace to host and run your j2ee hosting application check Virtualwebstudio j2ee web hosting services

// Resume interest in OP_READ key.interestOps (key.interestOps() |

Thursday, November 2nd, 2006

Chapter 5. Regular Expressions Hey, it’s a kind of magic. The Highlander In this chapter, we’ll discuss the API of the classes in the new java.util.regex package (see Figure 5-1). JSR 51, the Java Specification Request defining the new I/O capabilities, also specifies the addition of regular expression processing to the Java platform. While regular expressions, strictly speaking, are not I/O, they are most commonly used to scan text data read from files or streams. Figure 5-1. The regular expression classes You’ll learn how to use the new Java APIs to do the same powerful pattern matching that has been available to users of perl, egrep, and other text-processing tools. A detailed exploration of regular expression syntax is beyond the scope of This blog, but a working familiarity with regular expressions is assumed. If you’re new to regular expressions, want to improve your skills, or are baffled by this chapter, I recommend you pick up a good reference. O’Reilly publishes an authoritative regular expression book (it’s even cited in the JDK documentation): Mastering Regular Expressions, by Jeffrey E. F. Friedl (http://www.oreilly.com/catalog/regex/). 5.1 Regular Expression Basics A regular expression is a sequence of characters that describe, or express, a pattern of characters you are interested in matching within a target character sequence. Regular expressions have been widely available in the Unix world for many years by means of standard commands such as sed, grep, awk, etc. Because of its long history, the regular expression grammar used on the Unix platforms has been the basis for most regular expression processors. The Open Group, a Unix standards body, specifies regular expression syntax as a part of the Single Unix Specification (http://www.opengroup.org/onlinepubs/7908799/xbd/re.html). 160
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp hosting services

// Resume interest in OP_READ key.interestOps (key.interestOps() |

Thursday, November 2nd, 2006

// Resume interest in OP_READ key.interestOps (key.interestOps() | SelectionKey.OP_READ); // Cycle the selector so this key is active again key.selector().wakeup(); } } } Because the thread doing the selection will loop back and call select() again almost immediately, the interest set in the key is modified to remove interest in read-readiness. This prevents the selector from repeatedly invoking readDataFromSocket() (because the channel will remain ready to read until the worker thread can drain the data from it). When a worker thread has finished servicing the channel, it will again update the key’s interest set to reassert an interest in read-readiness. It also does an explicit wakeup() on the selector. If the main thread is blocked in select(), this causes it to resume. The selection loop will then cycle (possibly doing nothing) and reenter select() with the updated key. 4.6 Summary In this chapter, we covered the most powerful aspect of NIO. Readiness selection is essential to large-scale, high-volume server-side applications. The addition of this capability to the Java platform means that enterprise-class Java applications can now slug it out toe-to-toe with comparable applications written in any language. The key concepts covered in this chapter were: Selector classes The Selector, SelectableChannel, and SelectionKey classes form the triumvirate that makes readiness selection possible on the Java platform. In Section 4.1, we saw how these classes relate to each other and what they represent. Selection keys In Section 4.2, we learned more about selection keys and how they are used. The SelectionKey class encapsulates the relationship between a SelectableChannel object and a Selector with which it’s registered. Selectors Selection requests that the operating system determine which channels registered with a given selector are ready for I/O operation(s) of interest. We learned about the selection process in Section 4.3 and how to manage the key set returned from a call to select(). We also discussed some of the concurrency issues relating to selection. 158
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp hosting services

// Resume interest in OP_READ key.interestOps (key.interestOps() |

Thursday, November 2nd, 2006

Asynchronous closability Issues relating to closing selectors and channels asynchronously were touched on in Section 4.1. Multithreading In Section 4.5, we discussed how multiple threads can be put to work to service selectable channels without resorting to multiple Selector objects. Selectors hold great promise for Java server applications. As this powerful new capability is integrated into commercial application servers, server-side applications will gain even greater scalability, reliability, and responsiveness. OK, we’ve completed the main tour of java.nio and its subpackages. But don’t put your camera away. We have a couple of bonus highlights thrown in at no extra charge. Watch your step reboarding the bus. Next stop is the enchanted land of regular expressions. 159
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp hosting services

*/ private class ThreadPool { List idle =

Thursday, November 2nd, 2006

* thread returns itself to its parent pool. */ private class WorkerThread extends Thread { private ByteBuffer buffer = ByteBuffer.allocate (1024); private ThreadPool pool; private SelectionKey key; WorkerThread (ThreadPool pool) { this.pool = pool; } // Loop forever waiting for work to do public synchronized void run() { System.out.println (this.getName() + ” is ready”); while (true) { try { // Sleep and release object lock this.wait(); } catch (InterruptedException e) { e.printStackTrace(); // Clear interrupt status this.interrupted(); } if (key == null) { continue; // just in case } System.out.println (this.getName() + ” has been awakened”); try { drainChannel (key); } catch (Exception e) { System.out.println (”Caught ‘” + e + “‘ closing channel”); // Close channel and nudge selector try { key.channel().close(); } catch (IOException ex) { ex.printStackTrace(); } key.selector().wakeup(); } key = null; // Done. Ready for more. Return to pool this.pool.returnWorker (this); } } 156
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

*/ private class ThreadPool { List idle =

Thursday, November 2nd, 2006

/** * Called to initiate a unit of work by this worker thread * on the provided SelectionKey object. This method is * synchronized, as is the run() method, so only one key * can be serviced at a given time. * Before waking the worker thread, and before returning * to the main selection loop, this key’s interest set is * updated to remove OP_READ. This will cause the selector * to ignore read-readiness for this channel while the * worker thread is servicing it. */ synchronized void serviceChannel (SelectionKey key) { this.key = key; key.interestOps (key.interestOps() & (~SelectionKey.OP_READ)); this.notify(); // Awaken the thread } /** * The actual code which drains the channel associated with * the given key. This method assumes the key has been * modified prior to invocation to turn off selection * interest in OP_READ. When this method completes it * re-enables OP_READ and calls wakeup() on the selector * so the selector will resume watching this channel. */ void drainChannel (SelectionKey key) throws Exception { SocketChannel channel = (SocketChannel) key.channel(); int count; buffer.clear(); // Empty buffer // Loop while data is available; channel is nonblocking while ((count = channel.read (buffer)) > 0) { buffer.flip(); // make buffer readable // Send the data; may not go all at once while (buffer.hasRemaining()) { channel.write (buffer); } // WARNING: the above loop is evil. // See comments in superclass. buffer.clear(); // Empty buffer } if (count < 0) { // Close channel on EOF; invalidates the key channel.close(); return; } 157
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

*/ private class ThreadPool { List idle =

Thursday, November 2nd, 2006

*/ private class ThreadPool { List idle = new LinkedList(); ThreadPool (int poolSize) { // Fill up the pool with worker threads for (int i = 0; i < poolSize; i++) { WorkerThread thread = new WorkerThread (this); // Set thread name for debugging. Start it. thread.setName ("Worker" + (i + 1)); thread.start(); idle.add (thread); } } /** * Find an idle worker thread, if any. Could return null. */ WorkerThread getWorker() { WorkerThread worker = null; synchronized (idle) { if (idle.size() > 0) { worker = (WorkerThread) idle.remove (0); } } return (worker); } /** * Called by the worker thread to return itself to the * idle pool. */ void returnWorker (WorkerThread worker) { synchronized (idle) { idle.add (worker); } } } /** * A worker thread class which can drain channels and echo-back * the input. Each instance is constructed with a reference to * the owning thread pool object. When started, the thread loops * forever waiting to be awakened to service the channel associated * with a SelectionKey object. * The worker is tasked by calling its serviceChannel() method * with a SelectionKey object. The serviceChannel() method stores * the key reference in the thread object then calls notify() * to wake it up. When the channel has been drained, the worker 155
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services

not request the same locks in the same

Thursday, November 2nd, 2006

* Specialization of the SelectSockets class which uses a thread pool * to service channels. The thread pool is an ad-hoc implementation * quicky lashed togther in a few hours for demonstration purposes. * It’s definitely not production quality. * * @author Ron Hitchens (ron@ronsoft.com) */ public class SelectSocketsThreadPool extends SelectSockets{ private static final int MAX_THREADS = 5; private ThreadPool pool = new ThreadPool (MAX_THREADS); // ————————————————————- public static void main (String [] argv) throws Exception { new SelectSocketsThreadPool().go (argv); } // ————————————————————- /** * Sample data handler method for a channel with data ready to read. * This method is invoked from the go() method in the parent class. * This handler delegates to a worker thread in a thread pool to * service the channel, then returns immediately. * @param key A SelectionKey object representing a channel * determined by the selector to be ready for reading. If the * channel returns an EOF condition, it is closed here, which * automatically invalidates the associated key. The selector * will then de-register the channel on the next select call. */ protected void readDataFromSocket (SelectionKey key) throws Exception { WorkerThread worker = pool.getWorker(); if (worker == null) { // No threads available. Do nothing. The selection // loop will keep calling this method until a // thread becomes available. This design could // be improved. return; } // Invoking this wakes up the worker thread, then returns worker.serviceChannel (key); } // ————————————————————— /** * A very simple thread pool class. The pool size is set at * construction time and remains fixed. Threads are cycled * through a FIFO idle queue. 154
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

not request the same locks in the same

Thursday, November 2nd, 2006

On a system with n CPUs, n-1 could be idling while the single thread trundles along servicing each channel sequentially. Or what about the case in which different channels require different classes of service? Suppose an application logs information from a large number of distributed sensors. Any given sensor could wait several seconds while the servicing thread iterates through each ready channel. This is OK if response time is not critical. But higher-priority connections (such as operator commands) would have to wait in the queue as well if only one thread services all channels. Every application’s requirements are different. The solutions you apply are affected by what you’re trying to accomplish. For the first scenario, in which you want to bring more threads into play to service channels, resist the urge to use multiple selectors. Performing readiness selection on large numbers of channels is not expensive; most of the work is done by the underlying operating system. Maintaining multiple selectors and randomly assigning channels to one of them is not a satisfactory solution to this problem. It simply makes smaller versions of the same scenario. A better approach is to use one selector for all selectable channels and delegate the servicing of ready channels to other threads. You have a single point to monitor channel readiness and a decoupled pool of worker threads to handle the incoming data. The thread pool size can be tuned (or tune itself, dynamically) according to deployment conditions. Management of selectable channels remains simple, and simple is good. The second scenario, in which some channels demand greater responsiveness than others, can be addressed by using two selectors: one for the command connections and another for the normal connections. But this scenario can be easily addressed in much the same way as the first. Rather than dispatching all ready channels to the same thread pool, channels can be handed off to different classes of worker threads according to function. There may be a logging thread pool, a command/control pool, a status request pool, etc. The code in Example 4-2 is an extension of the generic selection loop code in Example 4-1. It overrides the readDataFromSocket() method and uses a thread pool to service channels with data to read. Rather than reading the data synchronously in the main thread, this version passes the SelectionKey object to a worker thread for servicing. Example 4-2. Servicing channels with a thread pool package com.ronsoft.books.nio.channels; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.channels.SelectionKey; import java.util.List; import java.util.LinkedList; import java.io.IOException; /** 153
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

not request the same locks in the same

Thursday, November 2nd, 2006

not request the same locks in the same order, there is a potential for deadlock. If you are certain that no other threads will be accessing the selector at the same time, then synchronization is not necessary. The close() method of Selector synchronizes in the same way as select(), so there is a potential for blocking there. A thread calling close() will block until an in-progress selection is complete or the thread doing the selection goes to sleep. In the latter case, the selecting thread will awaken as soon as the closing thread acquires the locks and closes the selector (see Section 4.3.2). 4.4 Asynchronous Closability It’s possible to close a channel or cancel a selection key at any time. Unless you take steps to synchronize, the states of the keys and associated channels could change unexpectedly. The presence of a key in a particular key set does not guarantee that the key is still valid or that its associated channel is still open. Closing channels should not be a time-consuming operation. The designers of NIO specifically wanted to prevent the possibility of a thread closing a channel being blocked in an indefinite wait if the channel is involved in a select operation. When a channel is closed, its associated keys are cancelled. This does not directly affect an in-process select(), but it does mean that a selection key that was valid when you called select() could be invalid upon return. You should always use the selected key set returned by the selector’s selectedKeys() method; do not maintain your own set of keys. Understanding the selection process as outlined in Section 4.3.1 is important to avoid running into trouble. Refer to Section 4.3.2 for the details of how a thread can be awakened when blocked in select(). If you attempt to use a key that’s been invalidated, a CancelledKeyException will be thrown by most methods. You can, however, safely retrieve the channel handle from a cancelled key. If the channel has also been closed, attempting to use it will yield a ClosedChannelException in most cases. 4.5 Selection Scaling I’ve mentioned several times that selectors make it easy for a single thread to multiplex large numbers of selectable channels. Using one thread to service all the channels reduces complexity and can potentially boost performance by eliminating the overhead of managing many threads. But is it a good idea to use just one thread to service all selectable channels? As always, it depends. It could be argued that on a single CPU system it’s a good idea because only one thread can be running at a time anyway. By eliminating the overhead of context switching between threads, total throughput could be higher. But what about a multi-CPU system? 152
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

(ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel (selector,

Thursday, November 2nd, 2006

do this because only ServerSocketChannel objects support the OP_ACCEPT operation. We also know our code registers only a single ServerSocketChannel object with interest in OP_ACCEPT. With a reference to the server socket channel, we invoke accept() on it to obtain a handle to the incoming socket. The object returned is of type SocketChannel, which is also a selectable type of channel. At this point, rather than spawning a new thread to read data from the new connection, we simply register the socket channel with the selector. We tell the selector we’re interested in knowing when the new socket channel is ready for reading by passing in the OP_READ flag. If the key did not indicate that the channel was ready for accept, we check to see if it’s ready for read. Any socket channels indicating so will be one of the SocketChannel objects previously created by the ServerSocketChannel and registered for interest in reading. For each socket channel with data to read, we invoke a common routine to read and process the data socket. Note that this routine should be prepared to deal with incomplete data on the socket, which is in nonblocking mode. It should return promptly so that other channels with pending input can be serviced in a timely manner. Example 4-1 simply echoes the data back down the socket to the sender. At the bottom of the loop, we remove the key from the selected key set by calling remove() on the Iterator object. Keys can be removed directly from the Set returned by selectedKeys(), but when examining the set with an Iterator, you should use the iterator’s remove() method to avoid corrupting the iterator’s internal state. 4.3.4 Concurrency Selector objects are thread-safe, but the key sets they contain are not. The key sets returned by the keys() and selectedKeys() methods are direct references to private Set objects inside the Selector object. These sets can change at any time. The registered key set is read-only. If you attempt to modify it, your reward will be a java.lang.UnsupportedOperationException, but you can still run into trouble if it’s changed while you’re looking at it. Iterator objects are fail-fast: they will throw java.util.ConcurrentModificationException if the underlying Set is modified, so be prepared for this if you expect to share selectors and/or key sets among threads. You’re allowed to modify the selection key set directly, but be aware that you could clobber some other thread’s Iterator by doing so. If there is any question of multiple threads accessing the key sets of a selector concurrently, you must take steps to properly synchronize access. When performing a selection operation, selectors synchronize on the Selector object, the registered key set, and the selected key set objects, in that order. They also synchronize on the cancelled key set during Steps 1 and 3 of the selection process (when it deregisters channels associated with cancelled keys). In a multithread scenario, if you need to make changes to any of the key sets, either directly or as a side effect of another operation, you should first synchronize on the same objects, in the same order. The locking order is vitally important. If competing threads do 151
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

(ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel (selector,

Thursday, November 2nd, 2006

(ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel (selector, channel, SelectionKey.OP_READ); sayHello (channel); } // Is there data to read on this channel? if (key.isReadable()) { readDataFromSocket (key); } // Remove key from selected set; it’s been handled it.remove(); } } } // ———————————————————- /** * Register the given channel with the given selector for * the given operations of interest */ protected void registerChannel (Selector selector, SelectableChannel channel, int ops) throws Exception { if (channel == null) { return; // could happen } // Set the new channel nonblocking channel.configureBlocking (false); // Register it with the selector channel.register (selector, ops); } // ———————————————————- // Use the same byte buffer for all channels. A single thread is // servicing all the channels, so no danger of concurrent acccess. private ByteBuffer buffer = ByteBuffer.allocateDirect (1024); /** * Sample data handler method for a channel with data ready to read. * @param key A SelectionKey object associated with a channel * determined by the selector to be ready for reading. If the * channel returns an EOF condition, it is closed here, which * automatically invalidates the associated key. The selector * will then de-register the channel on the next select call. */ protected void readDataFromSocket (SelectionKey key) throws Exception 149
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

(ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel (selector,

Thursday, November 2nd, 2006

{ SocketChannel socketChannel = (SocketChannel) key.channel(); int count; buffer.clear(); // Empty buffer // Loop while data is available; channel is nonblockingwhile ((count = socketChannel.read (buffer)) > 0) { buffer.flip(); // Make buffer readable // Send the data; don’t assume it goes all at once while (buffer.hasRemaining()) { socketChannel.write (buffer); } // WARNING: the above loop is evil. Because // it’s writing back to the same nonblocking // channel it read the data from, this code can // potentially spin in a busy loop. In real life // you’d do something more useful than this. buffer.clear(); // Empty buffer } if (count < 0) { // Close channel on EOF, invalidates the key socketChannel.close(); } } // ---------------------------------------------------------- /** * Spew a greeting to the incoming client connection. * @param channel The newly connected SocketChannel to say hello to. */ private void sayHello (SocketChannel channel) throws Exception { buffer.clear(); buffer.put ("Hi there!rn".getBytes()); buffer.flip(); channel.write (buffer); } } Example 4-1 implements a simple server. It creates ServerSocketChannel and Selector objects and registers the channel with the selector. We don't bother saving a reference to the registration key for the server socket because it will never be deregistered. The infinite loop calls select() at the top, which may block indefinitely. When selection is complete, the selected key set is iterated to check for ready channels. If a key indicates that its channel is ready to do an accept(), we obtain the channel associated with the key and cast it to a ServerSocketChannel object. We know it's safe to 150
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

immediately. Subsequent selection operations will behave normally. Invoking

Thursday, November 2nd, 2006

*/ public class SelectSockets{ public static int PORT_NUMBER = 1234; public static void main (String [] argv) throws Exception { new SelectSockets().go (argv); } public void go (String [] argv) throws Exception { int port = PORT_NUMBER; if (argv.length > 0) { // Override default listen port port = Integer.parseInt (argv [0]); } System.out.println (”Listening on port ” + port); // Allocate an unbound server socket channel ServerSocketChannel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // Create a new Selector for use below Selector selector = Selector.open(); // Set the port the server channel will listen to serverSocket.bind (new InetSocketAddress (port)); // Set nonblocking mode for the listening socket serverChannel.configureBlocking (false); // Register the ServerSocketChannel with the Selector serverChannel.register (selector, SelectionKey.OP_ACCEPT); while (true) { // This may block for a long time. Upon returning, the // selected set contains keys of the ready channels. int n = selector.select(); if (n == 0) { continue; // nothing to do } // Get an iterator over the set of selected keys Iterator it = selector.selectedKeys().iterator(); // Look at each key in the selected set while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = 148
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check Actions tomcat hosting services