Looking for performance boost to java.nio.charset.encode(String) method

hi ,
i have run jprofiler on my application and so that this method takes 4% of the overall CPU time (!) .
is there any other , faster way to do this encoding ?
thanks!

yjavaman wrote:
i susspect that in my application (multi threaded ) , it is actually a larger bottle neck than i think right now.
i ask about maybe the caching of the encoder , decoder , maybe i can save this time by doing other stuff .Not sure if you are already buffereing, but from javadoc:
java.io.OutputStreamWriter
Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.
For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:
Writer out = new BufferedWriter(new OutputStreamWriter(System.out));
Just something simple to use.

Similar Messages

  • Thread blocking on java.nio.charset.CoderResult

    Hello all,
    I have a multi-threaded app which does some fairly intestive string operations (basically extracts text from documents for indexing a search system).
    I am seeing a massive bottleneck around the java.nio.charset.CoderResult class. When profiling, I see a whole stack of threads blocking on (waiting for) a monitor on this java.nio.charset.CoderResult class. Seems to be a result of string encoding/decoding (I am often encoding strings as UTF-8).
    Anyone know why the JVM would want my threads to sync on this class? It's creating a huge performance issue for my app. Approximately 15% of ALL the processing time is spent waiting for this class.
    Help!

    I would guess that you're using some of the static methods in the CoderResult class. The static methods CoderResult.unmappableCache(), CoderResult.malformedForLength() and CoderResult.malformedCache all use a static inner class called Cache. Its get() method is synchronized on Cache.class. Since the Cache inner-class is static, any part of your multi-threaded application that goes through the Cache.get() method is going to be waiting for the lock on Cache.class.
    Could you create a CoderResult instance for each thread? That would mean that there would be a different static Cache class for each thread, reducing the number of threads competing for the Cache.class lock.
    I'd have to see some of your code to give a better answer.
    Brian

  • Look for general blog on Java technologies

    Hello,
    I am greatly interesting in Java and look for active blog on Java technologies. I found 1000 of blogs posted in this forum but many are very specific or not active anymore. Could you please advise me good java blog with regular posting and interesting articles on different part of Java?
    thanks
    sebastien

    To write JNI code for integrating of an activeX is not a simple task. You will face with a number of problems related to COM:
    - when and where to call CoInitialize and CoUninitialize,
    - how to clean up COM references on Java Application exit,
    - when to do Thread Marshal and when it is not needed for COM interfaces;
    - how to Marshal and Unmarshal COM parameters in Java methods calls to COM Interface methods, etc.
    The best decision is to use some Java-COM Bridge.
    My company has developed tools like
    - Java-COM Bridge
    - Object-Oriented JNI SDKs for C++ and .NET (v1.1,v.2.0) languages (do not mix with JNI wrapper generators). These are an object-oriented maps of the regular JNI SDK,
    - Add-Ins for MS Visual Studio v.6.0 and v.7.1 that generate Java wrappers in C++, C#, J#, MCpp, VB for Object-Oriented JNI SDK.
    So we know problems you have.
    See our site
    http://www.javain.com

  • Re: LOOKING FOR H264 CODEC in JAVA!!

    I am still looking for it!! Now is 2007, will it come this year??
    Looking forward to it!!

    Here are examples of a streaming video applet embedded inside a Java FX application.
    http://vxweb1.vx30.com/images/myVideoPlayer1.png
    http://vxweb1.vx30.com/images/myVideoPlayer2.png
    http://vxweb1.vx30.com/images/myVideoPlayer3.png
    Much better quality, performance compared to the previous example.

  • It it possible to look for a page that does not contain a string?

    Is it possible in the search feature in Dreamweaver CS3 to find all pages that do NOT contain a specific string?

    I don't think so, at least not directly. I could be wrong, Regular Expressions can be pretty powerful, I'm not sure how well they're implemented in CS3 though: http://www.adobe.com/devnet/dreamweaver/articles/regular_expressions_pt1.edu.html
    Maybe you could do a find/replace of that specific string, with itself.
    All of the files that have it would be updated without actually changing the code.
    The Date Modified for the file would change though.
    The files without the string of info you are looking for would have the old modification date.

  • Looking for Performance Comparisons Between JRockit 6 and Sun Java SE 6

    Hello,
    Can someone point me to some performance comparisons (benchmarks, etc.) between the JRockit and Sun JVMs?
    Thanks in advance.

    Hi Ben.
    Before I send to to the SPEC sites (which can be a tad hard to parse) I must ask - What application or type of application are you interested in? The answer will vary a bit depending on what you need.

  • Looking for training on Sun Java(tm) System Messaging Server 6

    Hi All,
    I looking to take training on Sun Java(tm) System Messaging Server 6 i checked SUN Training Site but i didn't find
    Can ant one tell me if its available or not.
    regards,
    Mariam

    MariamS wrote:
    I see that you know so much about Sun Java System Messaging staff. I've been using Messaging Server for over 8 years in various roles so I have a good head-start.
    from where you learned all these i like to expert in this area but i dont know from where i have to start.The Messaging Server admin guide is the best place to start:
    http://docs.sun.com/app/docs/doc/819-4428
    Regards,
    Shane.

  • Looking for More Info on Java Web Service

    Hi Everyone,
    Where can i find More info on Java web Service in BPEL? Is there any link or documentation for this? I looked at the tutorial and the only info available is:
    B.2.7 Java Web Service
    This service enables you to publish a Web service from a Java class. A wizard creates the WSDL document and deployment files needed to publish your code as a Web service. After you select the class and methods you want to publish, the wizard generates deployment descriptors, a JAX-RPC mapping file, and a WSDL document that can be deployed to an application server.
    Thank You,

    Sure,
    one way would be to upload the files to XE using the WebDav feature of the XML DB. You find more information here: http://daust.blogspot.com/2006/03/where-are-images-of-application.html
    Another option would be to configure a standalone Apache as a proxy server to XE. This way you can configure the Apache any way you like.
    HTTPS with Oracle XE ?
    Re: Existing http server
    For correctly logging the remote IP you will need the following workaround:
    Re: How to get X-Forwarded-For value?
    Regards,
    ~Dietmar.

  • Looking for some help on Java IO Streams

    Need to find a example or how to on:
    Java IO Streams
    using a scanner to find files with
    FileInputSeteam ...("c:\\data.in")
    did that make sense
    sandyR

    What about the API page for Scanner: http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    And the IO tutorial: http://java.sun.com/docs/books/tutorial/essential/io/index.html (which also discusses Scanner).

  • I'm in class right now and am looking for answers to all java questions

    post all answers to every question i will have in the future here now.

    sorry, people's i was in my csc class and feeling a
    little bored. i do have a legitimate question.
    what is the difference between a static variable and
    an instance variable?i'll tell you the answer LATER. c'mon, a little guessing so i don't have to use any effort

  • I look for a "java client IRC applet"

    Hello every body and good hollydays!
    For long time, I looked for a open source java "client irc" applet.
    I have found one, but it does' n run! (it needs to be signed and unfortunatly
    I don't doing it !).
    Briefly i need links about all this subject.
    A great thanks.
    elias

    Search in google by "java client IRC applet" found many different links :-)

  • The java.nio circus - what a headache

    Hi All
    I've been working now with the java.nio classes for a bit and trying to get a non-blocking client HTTP socket going. The requirement: no 3rd-party code and must either read fully from the socket OR timeout quickly (say 10sec).
    Unfortunately, I haven't been able to find ANY nio code that actually does this. There was one example by a John Z. that came really close, but it hung after a full reading of an HTTP stream because it could not determine if it was done reading or not!
    Anyway, here's my full code. It's very hacky and piecemeal, but i'm just looking for a prototype.
    Here's the main processing loop, cobbled together from a mix of examples on the web, plus my own little flourishes... :)
    public static void createSelector(URL url) throws IOException
    // Create a selector and register two socket channels
    Selector selector = null;
    // Create the selector
    selector = Selector.open();
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    int port = url.getPort();
    if (port == -1) { port = 80; }
    sChannel.connect(new InetSocketAddress(url.getHost(), port));
    // Before the socket is usable, the connection must be completed
    // by calling finishConnect(), which is non-blocking
    int iTime = 0;
    while (!sChannel.finishConnect())
         if (iTime > 10)
              System.out.println("Timeout!");
              throw new IOException("Connection timed out!");
         iTime++;
    System.out.println("Waiting for connection...");
    try { Thread.sleep(1000); } catch (InterruptedException interex) {}
    // Register the channel with selector, listening for all events
    //sChannel.register(selector, sChannel.validOps());
    sChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
    boolean allDone = false;
    while (selector.select(5000) > 0)
    // Get list of selection keys with pending events
    Iterator it = selector.selectedKeys().iterator();
    // Process each key at a time
    while (it.hasNext())
    // Get the selection key
    SelectionKey selKey = (SelectionKey)it.next();
    // Remove it from the list to indicate that it is being processed
    it.remove();
    allDone = processSelectionKey(selKey, url);
    if (allDone) { break; }
    } // while(true)
    if (allDone)
    System.out.println("All done!");
    else
         System.out.println("Timeout!");
    Now, the processSelectionKey method returns a true only if we get a -1 on our read. It looks like this:
    public static boolean processSelectionKey(SelectionKey selKey, URL url) throws IOException
    // Since the ready operations are cumulative,
    // need to check readiness for each operation
    if (selKey.isValid() && selKey.isConnectable())
    // Get channel with connection request
    SocketChannel sChannel = (SocketChannel)selKey.channel();
    //System.out.println("Sending request for "+url.getPath()+" using Connectable stream");
    String request = "GET "+url.getPath()+" \r\n\r\n";
    //System.out.println("Writing request "+request);
    sChannel.write(NonblockSocket.encoder.encode(CharBuffer.wrap(request)));
    //sentRequest = true;
    if (selKey.isValid() && selKey.isReadable())
         System.out.println("Readable key!");
    // Get channel with bytes to read
    SocketChannel sChannel = (SocketChannel)selKey.channel();
    int bytesRead = sChannel.read(buf);
    if (bytesRead == -1)
         return true;
    else
         System.out.println("Read "+bytesRead+" bytes...");
    buf.flip();
    System.out.println(decode(buf));
    buf.clear();
    cbuf.clear();
    OK, now this code does not work. There are a couple of problems with it. First of all, the "GET "+urlpath+" \r\n\r\n" is called a WHOLE BUNCH of times, not the usual once-per-request, as you would expect. But, if I programmatically enforce only one GET, it hangs. Still, it's strange.
    Secondly (and this is the real sticky point), it almost never reads in a full HTTP stream from the server before I get the following UNSETTLING exception during a read from the Channel:
    java.io.IOException: An existing connection was forcibly closed by the remote host
    I usually get either one or two successful reads from a readable channel and then the server disconnects me! NEVER saw this one coming. All in all, has ANYONE been able to use nio for client-side stuff to ANY degree at all? Maybe I'm doing something wrong? Any help would be excellent. BTW I'm running Win2K with JDK1.4.1.
    If I can't get this one to work, maybe I'll check out the new additions to the "old-school" java.net Socket.

    Actually,
    I just wrote a if..then to ignore the null accept.
    Even without using non-blocking connect i got two accepts.
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.nio.charset.*;
    import java.io.*;
    import java.util.*;
    * @author Aashish
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class NonBlockingServerSocket
         public static void main(String[] args)
              try
                        ServerSocketChannel serv = ServerSocketChannel.open();
                        serv.configureBlocking(false);
                        serv.socket().bind(new InetSocketAddress(33333));
                        System.out.println("bind complete");
                        Selector selector = Selector.open();
                        serv.register(selector,SelectionKey.OP_ACCEPT);
                        while(selector.select() > 0)
                             Iterator iter = selector.selectedKeys().iterator();
                             while(iter.hasNext())
                                  SelectionKey key = (SelectionKey)iter.next();
                                  if(key.isAcceptable())
                                       ServerSocketChannel servChan = (ServerSocketChannel)key.channel();
                                       SocketChannel sockChan = servChan.accept();
                                       if(sockChan == null)
                                            System.out.println("Just got a null channel in accept");
                                       else
                                            System.out.println("just accepted a sockChan");
                                            sockChan.configureBlocking(false);
                                           sockChan.register(selector,SelectionKey.OP_READ);
                                           if(sockChan.isConnected())
                                                 System.out.println("Channel is connected");
                                  if(key.isReadable())
                                                        //something here
              catch (Exception ex)
                   ex.printStackTrace();

  • New Charset Encoder/Decoder for Microsoft telnet

    Hello,
    I have a problem for writing a server which is accessible by microsoft windows telnet.
    I have managed to find out these relationships:
              switch ((int) c) {
                   case -27: c = '�'; break;
                   case -28: c = '�'; break;
                   case -102: c = '�'; break;
                   case -103: c = '�'; break;
                   case -108: c = '�'; break;
                   case -114: c = '�'; break;
                   case -124: c = '�'; break;
                   case -127: c = '�'; break;
    So how could i write an encoder/decoder which could map these charcters specially and others as norma ISO-8859-1.
    I switched them after encoding/decoding but then i got problem, that
    i got two characters(in telnet window). First was some wierd symbol and second the right character.
    Any help lplease?

    Okay, got working the charset include and everything is okay.
    Now i need to look after charcodes below 0. I though that it would be useful to create new charset for this purpose which adds little extra functionality to IBM850. When running this code it says that IBM850 charset not found when initilizating X-MICRO charset. But it is accessible in main program. Any ideas what is wrong?... Please help me, this damn internationallization has driven me mad.
    package ee.feelfree.charset;
    import java.nio.charset.Charset;
    import java.nio.charset.spi.CharsetProvider;
    import java.util.HashSet;
    import java.util.Iterator;
    public class MicrosoftCharsetProvider extends CharsetProvider {
         private static final String CHARSET_NAME = "X-MICRO";
         private Charset micro = null;
         public MicrosoftCharsetProvider()
         this.micro = new MicrosoftCharset (CHARSET_NAME, new String [0]);
         public Iterator charsets() {
              HashSet set = new HashSet (1);
              set.add (micro);
              return (set.iterator());
         public Charset charsetForName (String charsetName) {
              if (charsetName.equalsIgnoreCase (CHARSET_NAME)) {
                   return (micro);
                   return (null);
    package ee.feelfree.charset;
    import java.nio.CharBuffer;
    import java.nio.charset.*;
    import java.nio.ByteBuffer;
    public class MicrosoftCharset extends Charset {
         private static final String BASE_CHARSET_NAME = "IBM850";
         Charset baseCharset;
         protected MicrosoftCharset(String canonical,String [] aliases) {
              super (canonical, aliases);
              baseCharset = Charset.forName(BASE_CHARSET_NAME);
         public CharsetEncoder newEncoder() {
              return new MicrosoftEncoder(this,baseCharset.newEncoder());
         public CharsetDecoder newDecoder() {
              return new MicrosoftDecoder(this,baseCharset.newDecoder());
         public boolean contains (Charset cs) {
              return false;
         private class MicrosoftEncoder extends CharsetEncoder {
              private CharsetEncoder baseEncoder;
              MicrosoftEncoder(Charset cs,CharsetEncoder baseEncoder) {
                   super(cs, baseEncoder.averageBytesPerChar(),
                             baseEncoder.maxBytesPerChar());
                   this.baseEncoder = baseEncoder;
              protected CoderResult encodeLoop (CharBuffer cb, ByteBuffer bb)
                   CharBuffer tmpcb = CharBuffer.allocate (cb.remaining());
                   while (cb.hasRemaining()) {
                   tmpcb.put (cb.get());
                   tmpcb.rewind();
                   baseEncoder.reset();
                   CoderResult cr = baseEncoder.encode (tmpcb, bb, true);
                   cb.position (cb.position() - tmpcb.remaining());
                   return (cr);
         private class MicrosoftDecoder extends CharsetDecoder
         private CharsetDecoder baseDecoder;
         private boolean microClient = false;
              MicrosoftDecoder (Charset cs, CharsetDecoder baseDecoder)
                   super (cs, baseDecoder.averageCharsPerByte(),
                   baseDecoder.maxCharsPerByte());
                   this.baseDecoder = baseDecoder;
              protected CoderResult decodeLoop (ByteBuffer bb, CharBuffer cb)
                   baseDecoder.reset();
                   CoderResult result = baseDecoder.decode (bb, cb, true);
                   myDecode (cb);
                   return (result);
              public boolean getClient() {
                   return microClient;
              private void myDecode(CharBuffer cb) {
                   microClient = false;
                   for (int pos = cb.position(); pos < cb.limit(); pos++) {
                        int c = (int) cb.get (pos);
                        if (c<0) microClient=true;
    }

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • Javac compiler throws java.nio.BufferOverflowException!!Why?

    An exception has occurred in the compiler (1.4.1). Please file a bug at the Java Developer Connection (http://java.sun.com/cgi-bin/bugreport.cgi) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.
    java.nio.BufferOverflowException
    at java.nio.charset.CoderResult.throwException(CoderResult.java:259)
    at java.lang.StringCoding$CharsetSD.decode(StringCoding.java:186)
    at java.lang.StringCoding.decode(StringCoding.java:222)
    at java.lang.StringCoding.decode(StringCoding.java:228)
    at java.lang.String.<init>(String.java:383)
    at java.lang.String.<init>(String.java:404)
    at java.io.UnixFileSystem.list(Native Method)
    at java.io.File.list(File.java:914)
    at com.sun.tools.javac.v8.code.ClassReader.list(ClassReader.java:1224)
    at com.sun.tools.javac.v8.code.ClassReader.listAll(ClassReader.java:1320)
    at com.sun.tools.javac.v8.code.ClassReader.fillIn(ClassReader.java:1340)
    at com.sun.tools.javac.v8.code.ClassReader.complete(ClassReader.java:1049)
    at com.sun.tools.javac.v8.code.Symbol.complete(Symbol.java:332)
    at com.sun.tools.javac.v8.comp.Enter.visitTopLevel(Enter.java:467)
    at com.sun.tools.javac.v8.tree.Tree$TopLevel.accept(Tree.java:390)
    at com.sun.tools.javac.v8.comp.Enter.classEnter(Enter.java:442)
    at com.sun.tools.javac.v8.comp.Enter.classEnter(Enter.java:456)
    at com.sun.tools.javac.v8.comp.Enter.complete(Enter.java:588)
    at com.sun.tools.javac.v8.comp.Enter.main(Enter.java:574)
    at com.sun.tools.javac.v8.JavaCompiler.compile(JavaCompiler.java:334)
    at com.sun.tools.javac.v8.Main.compile(Main.java:520)
    at com.sun.tools.javac.Main.compile(Main.java:36)
    at com.sun.tools.javac.Main.main(Main.java:27)

    See this bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4949631

Maybe you are looking for

  • Problem with logging in

    So, I powered up my computer, entered the login password and got an error message that I could not login right now. I tried all sorts of things, safe boot, restarting, etc. A friend, helping me out (??), decided we should reinstall the OS SW, which w

  • Firefox slows or freezes on Google Blogger Editor

    When writing or editing a post on Google's Blogger, right at the start, Firefox freezes for sometime when opening a new blank editor page. After it works OK. This initial freeze when opening the editor has been happening for over one year now. Since

  • TS1292 I tried to put in a $15 iTunes card and put the code in correctly but it said the card was not properly activated.

    It said the code was not properly activated what do I do?

  • 500 Pre-Order Bonus Points Missing

    I have several games I've pre-ordered and picked up this year but I can't seem to find the bonus points and I can't look back more than 90 days.  The most recent is COD: MW but there have been others.  I have GCU and have followed the rules.  Can som

  • Setting WEP key in DOS

    I am trying to find a way to store the WEP key in DOS on a machine. I have the CSCODI drivers loading just fine. However to get into our network login screen in dos here. we have to have the wep key stored. I am using the Aeornet 350 PCI card, and wh