NetBeans Tips


Use Eclipse Shortcuts
Tools -> Options -> Keymap -> select Eclipse profile
Create code template
Tools -> Options -> Editor -> "Code Templates"
Press tab to activate define code template.
Reset the layout of windows
Windows -> Reset windows
Float/Dock views
Export/Import Settings
Open Options Dialog: Tools > Options
Click Export/Import button

In NetBeans, we can run a project, run a file, or run a test file.
Select project -> Properties -> Choose Run node -> Type command line arguments in the Arguments text box.
Remote debug
Settings in Netbeans:
Debug -> Attach Debugger
In the "Attach" dialog:
Debugger:  JPDA
Connector: Socket Attach
Transport: dt_socket
Enter host and port
Settings in server:
set JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n
-Xdebug
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n
Update Sites

Additional Development Plugins
Latest Development Build
Static Development UC
Dynamic Development UC
nbpluginportal
Netbeans logs
Windows XP: C:\Documents and Settings\joe\.netbeans\6.7\var\log\message.log
Linux: /home/joe/.netbeans/6.7/var/log/messages.log
Mac OS X: /Users/joe/.netbeans/6.7/var/log/messages.log

JBoss Tips


Commands
shutdown.sh -S
run.sh -b 0.0.0.0 -c default
run.bat –Djboss.server.log.dir=d:/log
Change ports
In jboss 5, in $JBoss\server\default\conf\bindingservice.beans\META-INF\bindings-jboss-beans.xml, change the port offset of PortsDefaultBindings.
<bean name="PortsDefaultBindings"  class="org.jboss.services.binding.impl.ServiceBindingSet">
  <constructor>
     <!-- The port offset -->
     <parameter>1000</parameter>
     <!-- Set of bindings to which the "offset by X" approach can't be applied -->
     <parameter><null/></parameter>
  </constructor>
</bean>
To use the port assignments defined by the Ports01Bindings bean, set the jboss.service.binding.set system property to ports-01 when starting the application server.
run -c myconfig2 -Djboss.service.binding.set=ports-01
Configuring logging

The log4j configuration file is located at server/xxx/conf/jboss-log4j.xml.
Defining a rolling log appender
<appender name="FILE">
    <param name="Append" value="true"/>
    <param name="MaxFileSize" value="10MB"/>
    <param name="MaxBackupIndex" value="20"/>
    <param name="Threshold" value="ERROR"/>
</appender>
Defining logging for your application
You can log your application by adding category entries to the jboss-log4j.xml file.
<appender name="JBIA" ...>
    <param name="File" value="${jboss.server.log.dir}/jbia.log"/>
</appender>
<category name="org.jbia">
    <priority value="DEBUG"/>
    <appender-ref ref="JBIA" />
</category>

Edit the server.xml file. For the default server in the default location, it is ${jboss.home}\server\default\deploy\jbossweb.sar\server.xml.
Uncomment the "Access logger" section. The log file will show up in server/default/log/localhost_access_log.{todays_date}.log

<Valve className="org.apache.catalina.valves.AccessLogValve"
                prefix="localhost_access_log." suffix=".log"
                pattern="common" directory="${jboss.server.log.dir}" 
                resolveHosts="false" />


Configuring startup parameters
Rename run.bat for example to run-old.bat.
Create another run.bat file and put this line to it:
set JAVA_OPTS=%JAVA_OPTS% -Xms512m -Xmx1024m -XX:MaxPermSize=512m
run-old.bat -b 0.0.0.0 -c default
Dump SOAP Messages
For the case that is not easy to model as a simple DFS request, it is useful to enable the SOAP dump.
For client side, set "com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true";
For server side, set "com.sun.xml.ws.transport.http.HttpAdapter.dump=true";
In Jboass, put the following line in newly created run.bat:
set JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true
Enable remote debug
In newly created run.bat:
rem set JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n
Configure apache httpd.conf:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
<Proxy balancer://mycluster>
Order deny,allow
Allow from all
BalancerMember http://node1.mycluster.lan:8080/ route=node1 timeout=15
BalancerMember http://node2.mycluster.lan:8080/ route=node2 timeout=15
ProxySet stickysession=JSESSIONID|jsessionid
# other values: bybusyness|byrequests|bytraffic
ProxySet lbmethod=bytraffic 
</Proxy>
ProxyPass /jmx-console balancer://mycluster/jmx-console 
ProxyPassReverse /jmx-console  http://localhost:9080/jmx-console stickysession=JSESSIONID|jsessionid



Configure JBoss
In jboss, modify {jboss.home}\server\default\deploy\jbossweb.sar\server.xml to configure the jvmRoute for sticky sessions:
<Engine name="jboss.web" defaultHost="localhost" jvmRoute="node1">

Modify {jboss.home}\server\default\deployers\jbossweb.deployer\META-INF\war-deployers-jboss-beans.xml:
<bean name="WebAppClusteringDefaultsDeploye" class="org.jboss.web.tomcat.service.deployers.ClusteringDefaultsDeployer">
  <property name="useJK">true</property>
</bean>

Resources:

Useful Notepad++ Tips


 
Three years ago, after used Notepad++ after some time, I write one article  about NotePad++. Three years later, it's time to give it some update.
Common Settings
Open "Settings" -> "Preferences...".
In "Tab bar" section of General tab, select "Double click to close document" and "Multi-line".
In "Backup/Auto-Completion" tab, enable auto-completion option, and choose "Word completion".
Enable spell-checker
Install Aspell, afterwards enable spell-checker :)
Use "Ctrl+Tab"
Use "Ctrl+Tab" to switch between to you last viewed file, and quickly jump to the file you want.

Useful Plugins:

How to install plugins:
Go to "Plugins" -> "Plugin Manager" -> "Show Plugin Manager", this will bring up the "Plugin Manager" dialog where you can find many available plugins.
File switcher
Usually I opened many files in Notepad++, 20 - 30+, some files I need edit often, or some files I just forget to close. So sometimes, it would be hard to find files I want to edit in Notepad++.
File switcher is just the plugin that we need- It presents a sortable list, and we can type text to filter and find the file we want.

Compare Plugin - show the difference between 2 files.
XML Tools - XML Checker. Can auto-close tags and provides other useful features.
To Format XML:
Go to "Plugins" -> "XML Tools" -> "Pretty print (XML only -with line breaks) - Ctrl+Alt+Shift+B"
Explorer Plugin – a file browser
Speech Plugin
There are many other useful plugins that may meet your needs, please explore them.

Resources:

Link With Editor in Eclipse


I remembered that in the old versions of eclipse(maybe 3.1), in the package and project explorer, it will show the current java class that is opened in the editor. When I change to another java class, it the explorer will automatically scroll to display the new class.

It seems this feature is gone in later release.
But the fact is that it is hidden - by default disabled, to enable it, you just need toggle the"Link with Editor" button in Package/Project/ or Navigator toolbar.



















Resources:

Use Working Set to group projects in Eclipse



Use Working Set to organize and group related projects visually in Eclipse

Usually, we develop or maintain different projects at same time, each project
has multiple modules, or related projects, such as test or demo projects.

We want to organize related projects visually, so in eclipse, it would look like:
projecta
---projecta-module1
---projecta-module2
---projecta-module3
---projecta-other-modules
projectb
---projectb--related-modules

To achieve this in Eclipse:
Create one working set, add related projects into it, and then (important step here), in project(or package) explorer, click the top down button -> "Top level elements" -> choose "Working Sets".

Resources:

Fail to start JBoss5 - Common unexpected


Unable to start JBoss 5 - \Common was unexpected at this time

--Don't use quotes in path variable

Today, I download JBoss 5 in my Windows 7 - 64 bit machine, and try to use run.bat to start the server, but it fails, and reports error:
\Common was unexpected at this time.

Google searched, but found nothing useful.
So I tried to take a look at the run.bat, first I comment the first row "@echo off", so I will now where it stops with the error above. I located the source of the errors:
if not "x%JBOSS_NATIVE_HOME%" == "x" (
  set "PATH=%JBOSS_NATIVE_HOME%;%PATH%;%JBOSS_HOME%\bin"
  set JAVA_OPTS=%JAVA_OPTS% "-Djava.library.path=%JBOSS_NATIVE_HOME%;%PATH%;%JBOSS_HOME%\bin"
)

Then I check the PATH environment:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;"C:\Program Files (x86)\Common Files\EMC";C:\Program Files\Perforce;%JAVA_HOME%\bin;%ANT_HOME%\bin;%MVN_HOME%\bin

Yeah, find out the culprit: the quotes around the path to EMC common files - "C:\Program Files (x86)\Common Files\EMC"
After removed the quotes, start a new command line, JBoss can be started with no problem.

Lesson learned: don't put quotes in your environment variables, such as PATH, JAVA_HOME etc, this may make scripts broken. This also applies when installation program update these variables.

Learning JDK Code – concurrent


Learning JDK Code – concurrent

CopyOnWriteArrayList
 package java.util.concurrent;  
 public class CopyOnWriteArrayList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {  
   /** The lock protecting all mutators */  
   transient final ReentrantLock lock = new ReentrantLock();  
   private volatile transient Object[] array;  
    * <p>The returned iterator provides a snapshot of the state of the list  
    * when the iterator was constructed. No synchronization is needed while  
    * traversing the iterator. The iterator does <em>NOT</em> support the  
    * <tt>remove method.  
   public Iterator<E> iterator() {  
     return new COWIterator<E>(getArray(), 0);  
   }    
   public E set(int index, E element) {  
      final ReentrantLock lock = this.lock;  
      lock.lock();  
      try {  
        Object[] elements = getArray();  
        Object oldValue = elements[index];  
        if (oldValue != element) {  
           int len = elements.length;  
     // create a new array  
           Object[] newElements = Arrays.copyOf(elements, len);  
           newElements[index] = element;  
           setArray(newElements);  
        } else {  
           // Not quite a no-op; ensures volatile write semantics  
           setArray(elements);  
        }  
        return (E)oldValue;  
      } finally {  
        lock.unlock();  
      }  
   }    
   public boolean add(E e) {  
      final ReentrantLock lock = this.lock;  
      lock.lock();  
      try {  
        Object[] elements = getArray();  
        int len = elements.length;  
        Object[] newElements = Arrays.copyOf(elements, len + 1);  
        newElements[len] = e;  
        setArray(newElements);  
        return true;  
      } finally {  
        lock.unlock();  
      }  
   }    
   public boolean remove(Object o) {  
      final ReentrantLock lock = this.lock;  
      lock.lock();  
      try {  
        Object[] elements = getArray();  
        int len = elements.length;  
        if (len != 0) {  
           // Copy while searching for element to remove  
           // This wins in the normal case of element being present  
           int newlen = len - 1;  
           Object[] newElements = new Object[newlen];  
           for (int i = 0; i < newlen; ++i) {  
             if (eq(o, elements[i])) {  
                // found one; copy remaining and exit  
                for (int k = i + 1; k < len; ++k)  
                  newElements[k-1] = elements[k];  
                setArray(newElements);  
                return true;  
             } else  
                newElements[i] = elements[i];  
           }  
           // special handling for last cell  
           if (eq(o, elements[newlen])) {  
             setArray(newElements);  
             return true;  
           }  
        }  
        return false;  
      } finally {  
        lock.unlock();  
      }  
   }  
   public E remove(int index) {  
      final ReentrantLock lock = this.lock;  
      lock.lock();  
      try {  
        Object[] elements = getArray();  
        int len = elements.length;  
        Object oldValue = elements[index];  
        int numMoved = len - index - 1;  
        if (numMoved == 0)  
           setArray(Arrays.copyOf(elements, len - 1));  
        else {  
           Object[] newElements = new Object[len - 1];  
           System.arraycopy(elements, 0, newElements, 0, index);  
           System.arraycopy(elements, index + 1, newElements, index,  
                      numMoved);  
           setArray(newElements);  
        }  
        return (E)oldValue;  
      } finally {  
        lock.unlock();  
      }  
   }    
   private static class COWIterator<E> implements ListIterator<E> {  
     /** Snapshot of the array **/  
     private final Object[] snapshot;  
     /** Index of element to be returned by subsequent call to next. */  
     private int cursor;  
     private COWIterator(Object[] elements, int initialCursor) {  
       cursor = initialCursor;  
       snapshot = elements;  
     }  
     public boolean hasNext() {  
       return cursor < snapshot.length;  
     }  
     public boolean hasPrevious() {  
       return cursor > 0;  
     }  
     public E next() {  
        if (! hasNext())  
         throw new NoSuchElementException();  
        return (E) snapshot[cursor++];  
     }  
     public E previous() {  
        if (! hasPrevious())  
         throw new NoSuchElementException();  
        return (E) snapshot[--cursor];  
     }  
     public int nextIndex() {  
       return cursor;  
     }  
     public int previousIndex() {  
       return cursor-1;  
     }  
     public void remove()|set(E e)|add(E e) {  
       throw new UnsupportedOperationException();  
     }  
   }  
 }    
ArrayBlockingQueue
 public class ArrayBlockingQueue<E> extends AbstractQueue<E>  
   implements BlockingQueue<E>, java.io.Serializable {  
 {  
   private final E[] items;  
   private int takeIndex;  
   private int putIndex;      
   /** Main lock guarding all access */  
   private final ReentrantLock lock;  
   /** Condition for waiting takes */  
   private final Condition notEmpty;  
   /** Condition for waiting puts */  
   private final Condition notFull;  
   // Blocked operations  
    * Inserts the specified element at the tail of this queue, waiting  
    * for space to become available if the queue is full.  
   public void put(E e) throws InterruptedException {  
     if (e == null) throw new NullPointerException();  
     final E[] items = this.items;  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       try {  
         while (count == items.length)  
           notFull.await();  
       } catch (InterruptedException ie) {  
         notFull.signal(); // propagate to non-interrupted thread  
         throw ie;  
       }  
       insert(e);  
     } finally {  
       lock.unlock();  
     }  
   }    
    * Inserts the specified element at the tail of this queue, waiting  
    * for space to become available if the queue is full.    
   public E take() throws InterruptedException {  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       try {  
         while (count == 0)  
           notEmpty.await();  
       } catch (InterruptedException ie) {  
         notEmpty.signal(); // propagate to non-interrupted thread  
         throw ie;  
       }  
       E x = extract();  
       return x;  
     } finally {  
       lock.unlock();  
     }  
   }  
   public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
      long nanos = unit.toNanos(timeout);  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       for (;;) {  
         if (count != 0) {  
           E x = extract();  
           return x;  
         }  
         if (nanos <= 0)  
           return null;  
         try {  
           nanos = notEmpty.awaitNanos(nanos);  
         } catch (InterruptedException ie) {  
           notEmpty.signal(); // propagate to non-interrupted thread  
           throw ie;  
         }  
       }  
     } finally {  
       lock.unlock();  
     }  
   }    
   public boolean offer(E e, long timeout, TimeUnit unit)  
     throws InterruptedException {  
     if (e == null) throw new NullPointerException();  
      long nanos = unit.toNanos(timeout);  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       for (;;) {  
         if (count != items.length) {  
           insert(e);  
           return true;  
         }  
         if (nanos <= 0)  
           return false;  
         try {  
           nanos = notFull.awaitNanos(nanos);  
         } catch (InterruptedException ie) {  
           notFull.signal(); // propagate to non-interrupted thread  
           throw ie;  
         }  
       }  
     } finally {  
       lock.unlock();  
     }  
   }  
   public boolean contains(Object o) {  
     if (o == null) return false;  
     final E[] items = this.items;  
     final ReentrantLock lock = this.lock;  
     lock.lock();  
     try {  
       int i = takeIndex;  
       int k = 0;  
       while (k++ < count) {  
         if (o.equals(items[i]))  
           return true;  
         i = inc(i);  
       }  
       return false;  
     } finally {  
       lock.unlock();  
     }  
   }    
    * Inserts element at current put position, advances, and signals.  
    * Call only when holding lock.  
   private void insert(E x) {  
     items[putIndex] = x;  
     putIndex = inc(putIndex);  
     ++count;  
     notEmpty.signal();  
   }  
    * Extracts element at current take position, advances, and signals.  
    * Call only when holding lock.  
   private E extract() {  
     final E[] items = this.items;  
     E x = items[takeIndex];  
     items[takeIndex] = null;  
     takeIndex = inc(takeIndex);  
     --count;  
     notFull.signal();  
     return x;  
   }    
   final int inc(int i) {  
     return (++i == items.length)? 0 : i;  
 }  
   /**  
    * Returns an iterator over the elements in this queue in proper sequence.  
    * The returned Iterator is a "weakly consistent" iterator that  
    * will never throw {@link ConcurrentModificationException},  
    * and guarantees to traverse elements as they existed upon  
    * construction of the iterator, and may (but is not guaranteed to)  
    * reflect any modifications subsequent to construction.  
   public Iterator<E> iterator() {  
     final ReentrantLock lock = this.lock;  
     lock.lock();  
     try {  
       return new Itr();  
     } finally {  
       lock.unlock();  
     }  
 }  
   private class Itr implements Iterator<E> {  
      * Index of element to be returned by next,  
      * or a negative number if no such.  
     private int nextIndex;  
      * nextItem holds on to item fields because once we claim  
      * that an element exists in hasNext(), we must return it in  
      * the following next() call even if it was in the process of  
      * being removed when hasNext() was called.  
     private E nextItem;  
      * Index of element returned by most recent call to next.  
      * Reset to -1 if this element is deleted by a call to remove.  
     private int lastRet;  
     Itr() {  
       lastRet = -1;  
       if (count == 0)  
         nextIndex = -1;  
       else {  
         nextIndex = takeIndex;  
         nextItem = items[takeIndex];  
       }  
     }  
     public boolean hasNext() {  
        * No sync. We can return true by mistake here  
        * only if this iterator passed across threads,  
        * which we don't support anyway.  
       return nextIndex >= 0;  
     }  
      * Checks whether nextIndex is valid; if so setting nextItem.  
      * Stops iterator when either hits putIndex or sees null item.  
     private void checkNext() {  
       if (nextIndex == putIndex) {  
         nextIndex = -1;  
         nextItem = null;  
       } else {  
         nextItem = items[nextIndex];  
         if (nextItem == null)  
           nextIndex = -1;  
       }  
     }  
     public E next() {  
       final ReentrantLock lock = ArrayBlockingQueue.this.lock;  
       lock.lock();  
       try {  
         if (nextIndex < 0)  
           throw new NoSuchElementException();  
         lastRet = nextIndex;  
         E x = nextItem;  
         nextIndex = inc(nextIndex);  
         checkNext();  
         return x;  
       } finally {  
         lock.unlock();  
       }  
     }  
     public void remove() {  
       final ReentrantLock lock = ArrayBlockingQueue.this.lock;  
       lock.lock();  
       try {  
         int i = lastRet;  
         if (i == -1)  
           throw new IllegalStateException();  
         lastRet = -1;  
         int ti = takeIndex;  
         removeAt(i);  
         // back up cursor (reset to front if was first element)  
         nextIndex = (i == ti) ? takeIndex : i;  
         checkNext();  
       } finally {  
         lock.unlock();  
       }  
     }  
   }  
 }  
LinkedBlockingQueue
 public class LinkedBlockingQueue<E> extends AbstractQueue<E>  
     implements BlockingQueue<E>, java.io.Serializable {  
   static class Node<E> {  
     E item;  
      * One of:  
      * - the real successor Node  
      * - this Node, meaning the successor is head.next  
      * - null, meaning there is no successor (this is the last node)  
     Node<E> next;  
     Node(E x) { item = x; }  
   }  
   /** Current number of elements */  
   private final AtomicInteger count = new AtomicInteger(0);  
   private transient Node<E> head;  
   private transient Node<E> last;  
   /** Lock held by take, poll, etc */  
   private final ReentrantLock takeLock = new ReentrantLock();  
   /** Wait queue for waiting takes */  
   private final Condition notEmpty = takeLock.newCondition();  
   /** Lock held by put, offer, etc */  
   private final ReentrantLock putLock = new ReentrantLock();  
   /** Wait queue for waiting puts */  
   private final Condition notFull = putLock.newCondition();   
   public LinkedBlockingQueue(int capacity) {  
     if (capacity <= 0) throw new IllegalArgumentException();  
     this.capacity = capacity;  
     last = head = new Node<E>(null);  
   }    
   public LinkedBlockingQueue(Collection<? extends E> c) {  
     this(Integer.MAX_VALUE);  
     final ReentrantLock putLock = this.putLock;  
     putLock.lock(); // Never contended, but necessary for visibility  
     try {  
       int n = 0;  
       for (E e : c) {  
         if (e == null)  
           throw new NullPointerException();  
         if (n == capacity)  
           throw new IllegalStateException("Queue full");  
         enqueue(e);  
         ++n;  
       }  
       count.set(n);  
     } finally {  
       putLock.unlock();  
     }  
   }    
   public E take() throws InterruptedException {  
     E x;  
     int c = -1;  
     final AtomicInteger count = this.count;  
     final ReentrantLock takeLock = this.takeLock;  
     takeLock.lockInterruptibly();  
     try {  
         while (count.get() == 0) {  
           notEmpty.await();  
         }  
       x = dequeue();  
       c = count.getAndDecrement();  
       if (c > 1)  
         notEmpty.signal();  
     } finally {  
       takeLock.unlock();  
     }  
     if (c == capacity)  
       signalNotFull();  
     return x;  
   }  
    * Inserts the specified element at the tail of this queue, waiting if  
    * necessary for space to become available.    
   public void put(E e) throws InterruptedException {  
     if (e == null) throw new NullPointerException();  
     // Note: convention in all put/take/etc is to preset local var  
     // holding count negative to indicate failure unless set.  
     int c = -1;  
     final ReentrantLock putLock = this.putLock;  
     final AtomicInteger count = this.count;  
     putLock.lockInterruptibly();  
     try {  
       /*  
        * Note that count is used in wait guard even though it is  
        * not protected by lock. This works because count can  
        * only decrease at this point (all other puts are shut  
        * out by lock), and we (or some other waiting put) are  
        * signalled if it ever changes from  
        * capacity. Similarly for all other uses of count in  
        * other wait guards.  
        */  
       while (count.get() == capacity) {   
           notFull.await();  
       }  
       enqueue(e);  
       c = count.getAndIncrement();  
       if (c + 1 < capacity)  
         notFull.signal();  
     } finally {  
       putLock.unlock();  
     }  
     if (c == 0)  
       signalNotEmpty();  
   }  
   public boolean offer(E e, long timeout, TimeUnit unit)  
     throws InterruptedException {  
     if (e == null) throw new NullPointerException();  
     long nanos = unit.toNanos(timeout);  
     int c = -1;  
     final ReentrantLock putLock = this.putLock;  
     final AtomicInteger count = this.count;  
     putLock.lockInterruptibly();  
     try {  
       while (count.get() == capacity) {  
         if (nanos <= 0)  
           return false;  
         nanos = notFull.awaitNanos(nanos);  
       }  
       enqueue(e);  
       c = count.getAndIncrement();  
       if (c + 1 < capacity)  
         notFull.signal();  
     } finally {  
       putLock.unlock();  
     }  
     if (c == 0)  
       signalNotEmpty();  
     return true;  
   }  
   public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
     E x = null;  
     int c = -1;  
     long nanos = unit.toNanos(timeout);  
     final AtomicInteger count = this.count;  
     final ReentrantLock takeLock = this.takeLock;  
     takeLock.lockInterruptibly();  
     try {  
         while (count.get() == 0) {   
          if (nanos <= 0)  
           return null;  
          nanos = notEmpty.awaitNanos(nanos);  
         }  
         x = dequeue();  
         c = count.getAndDecrement();  
         if (c > 1)  
           notEmpty.signal();  
     } finally {  
       takeLock.unlock();  
     }  
     if (c == capacity)  
       signalNotFull();  
     return x;  
   }  
   private void enqueue(E x) {  
     // assert putLock.isHeldByCurrentThread();  
     last = last.next = new Node<E>(x);  
   }  
   private E dequeue() {  
     // assert takeLock.isHeldByCurrentThread();  
     Node<E> h = head;  
     Node<E> first = h.next;  
     h.next = h; // help GC  
     head = first;  
     E x = first.item;  
     first.item = null;  
     return x;  
   }    
   public Iterator<E> iterator() {  
    return new Itr();  
   }  
   private class Itr implements Iterator<E> {  
     /*  
      * Basic weakly-consistent iterator. At all times hold the next  
      * item to hand out so that if hasNext() reports true, we will  
      * still have it to return even if lost race with a take etc.  
      */  
     private Node<E> current;  
     private Node<E> lastRet;  
     private E currentElement;  
     Itr() {  
       fullyLock();  
       try {  
         current = head.next;  
         if (current != null)  
           currentElement = current.item;  
       } finally {  
         fullyUnlock();  
       }  
     }  
     public boolean hasNext() {  
       return current != null;  
     }  
     public E next() {  
       fullyLock();  
       try {  
         if (current == null)  
           throw new NoSuchElementException();  
         E x = currentElement;  
         lastRet = current;  
         current = nextNode(current);  
         currentElement = (current == null) ? null : current.item;  
         return x;  
       } finally {  
         fullyUnlock();  
       }  
     }  
     public void remove() {  
       if (lastRet == null)  
         throw new IllegalStateException();  
       fullyLock();  
       try {  
         Node<E> node = lastRet;  
         lastRet = null;  
         for (Node<E> trail = head, p = trail.next;  
            p != null;  
            trail = p, p = p.next) {  
            if (p == node) {  
              unlink(p, trail);  
              break;  
            }  
         }  
       } finally {  
         fullyUnlock();  
       }  
     }  
   }  
   public boolean remove(Object o) {  
     if (o == null) return false;  
     fullyLock();  
     try {  
       for (Node<E> trail = head, p = trail.next;  
          p != null;  
          trail = p, p = p.next) {  
         if (o.equals(p.item)) {  
           unlink(p, trail);  
           return true;  
         }  
       }  
       return false;  
     } finally {  
       fullyUnlock();  
     }  
 }  
   public void clear() {  
     fullyLock();  
     try {  
       for (Node<E> p, h = head; (p = h.next) != null; h = p) {  
         h.next = h;  
         p.item = null;  
       }  
       head = last;  
       // assert head.item == null && head.next == null;  
       if (count.getAndSet(0) == capacity)  
         notFull.signal();  
     } finally {  
       fullyUnlock();  
     }  
   }  
   boolean isFullyLocked() {  
     return (putLock.isHeldByCurrentThread() &&  
         takeLock.isHeldByCurrentThread());  
   }  
 }  
PriorityQueue
Point – build min heap, and heapify, siftDown, use bitwise operators to improve performance.
 public class PriorityQueue<E> extends AbstractQueue<E>  
 implements java.io.Serializable {  
    * Priority queue represented as a balanced binary heap: the two  
    * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The  
    * priority queue is ordered by comparator, or by the elements'  
    * natural ordering, if comparator is null: For each node n in the  
    * heap and each descendant d of n, n <= d. The element with the  
    * lowest value is in queue[0], assuming the queue is nonempty.  
 private transient Object[] queue;  
    * The number of elements in the priority queue.  
   private int size = 0;  
    * The comparator, or null if priority queue uses elements'  
    * natural ordering.  
   private final Comparator<? super E> comparator;  
    * The number of times this priority queue has been  
    * <i>structurally modified</i>. See AbstractList for gory details.  
  private transient int modCount = 0;  
 private void initFromCollection(Collection<? extends E> c) {  
     Object[] a = c.toArray();  
     // If c.toArray incorrectly doesn't return Object[], copy it.  
     if (a.getClass() != Object[].class)  
       a = Arrays.copyOf(a, a.length, Object[].class);  
     queue = a;  
     size = a.length;  
 }  
 // provide a better api to client  
   public PriorityQueue(PriorityQueue<? extends E> c) {  
     comparator = (Comparator<? super E>)c.comparator();  
     initFromCollection(c);  
   }  
   public PriorityQueue(Collection<? extends E> c) {  
     initFromCollection(c);  
     if (c instanceof SortedSet)  
       comparator = (Comparator<? super E>)  
         ((SortedSet<? extends E>)c).comparator();  
     else if (c instanceof PriorityQueue)  
       comparator = (Comparator<? super E>)  
         ((PriorityQueue<? extends E>)c).comparator();  
     else {  
       comparator = null;  
       heapify();  
     }  
 }  
   private void heapify() {  
     for (int i = (size >>> 1) - 1; i >= 0; i--)  
       siftDown(i, (E) queue[i]);  
   }  
    * Inserts item x at position k, maintaining heap invariant by  
    * demoting x down the tree repeatedly until it is less than or  
    * equal to its children or is a leaf.  
   private void siftDown(int k, E x) {  
     if (comparator != null)  
       siftDownUsingComparator(k, x);  
     else  
       siftDownComparable(k, x);  
   }  
   private void siftDownComparable(int k, E x) {  
     Comparable<? super E> key = (Comparable<? super E>)x;  
     int half = size >>> 1;    // loop while a non-leaf  
     while (k < half) {  
       int child = (k << 1) + 1; // assume left child is least  
       Object c = queue[child];  
       int right = child + 1;  
       if (right < size &&  
         ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)  
         c = queue[child = right];  
       if (key.compareTo((E) c) <= 0)  
         break;  
       queue[k] = c;  
       k = child;  
     }  
     queue[k] = key;  
   }  
   private void siftDownUsingComparator(int k, E x) {  
     int half = size >>> 1;  
     while (k < half) {  
       int child = (k << 1) + 1;  
       Object c = queue[child];  
       int right = child + 1;  
       if (right < size &&  
         comparator.compare((E) c, (E) queue[right]) > 0)  
         c = queue[child = right];  
       if (comparator.compare(x, (E) c) <= 0)  
         break;  
       queue[k] = c;  
       k = child;  
     }  
     queue[k] = x;  
 }  
 // be careful to check overflow when do four arithmetic operations.  
   private void grow(int minCapacity) {  
     if (minCapacity < 0) // overflow  
       throw new OutOfMemoryError();  
      int oldCapacity = queue.length;  
     // Double size if small; else grow by 50%  
     int newCapacity = ((oldCapacity < 64)?  
               ((oldCapacity + 1) * 2):  
               ((oldCapacity / 2) * 3));  
     if (newCapacity < 0) // overflow  
       newCapacity = Integer.MAX_VALUE;  
     if (newCapacity < minCapacity)  
       newCapacity = minCapacity;  
     queue = Arrays.copyOf(queue, newCapacity);  
 }  
 // throws NullPointerException explicitly, and document the NPE.  
    * Inserts the specified element into this priority queue.  
    * @throws ClassCastException if the specified element cannot be  
    *     compared with elements currently in this priority queue  
    *     according to the priority queue's ordering  
    * @throws NullPointerException if the specified element is null  
    */  
   public boolean offer(E e) {  
     if (e == null)  
       throw new NullPointerException();  
     modCount++;  
     int i = size;  
     if (i >= queue.length)  
       grow(i + 1);  
     size = i + 1;  
     if (i == 0)  
       queue[0] = e;  
     else  
       siftUp(i, e);  
     return true;  
   }  
    * To simplify and speed up coercions and comparisons. the  
    * Comparable and Comparator versions are separated into different  
    * methods that are otherwise identical. (Similarly for siftDown.)  
   private void siftUp(int k, E x) {  
     if (comparator != null)  
       siftUpUsingComparator(k, x);  
     else  
       siftUpComparable(k, x);  
   }  
   private void siftUpComparable(int k, E x) {  
     Comparable<? super E> key = (Comparable<? super E>) x;  
     while (k > 0) {  
       int parent = (k - 1) >>> 1;  
       Object e = queue[parent];  
       if (key.compareTo((E) e) >= 0)  
         break;  
       queue[k] = e;  
       k = parent;  
     }  
     queue[k] = key;  
   }  
   private void siftUpUsingComparator(int k, E x) {  
     while (k > 0) {  
       int parent = (k - 1) >>> 1;  
       Object e = queue[parent];  
       if (comparator.compare(x, (E) e) >= 0)  
         break;  
       queue[k] = e;  
       k = parent;  
     }  
     queue[k] = x;  
 }  
   public E poll() {  
     if (size == 0)  
       return null;  
     int s = --size;  
     modCount++;  
     E result = (E) queue[0];  
     E x = (E) queue[s];  
     queue[s] = null;  
     if (s != 0)  
       siftDown(0, x);  
     return result;  
   }  
   public boolean remove(Object o) {  
      int i = indexOf(o);  
      if (i == -1)  
        return false;  
      else {  
        removeAt(i);  
        return true;  
      }  
 }  
    * Normally this method leaves the elements at up to i-1,  
    * inclusive, untouched. Under these circumstances, it returns  
    * null. Occasionally, in order to maintain the heap invariant,  
    * it must swap a later element of the list with one earlier than  
    * i. Under these circumstances, this method returns the element  
    * that was previously at the end of the list and is now at some  
    * position before i. This fact is used by iterator.remove so as to  
    * avoid missing traversing elements.  
   private E removeAt(int i) {  
     assert i >= 0 && i < size;  
     modCount++;  
     int s = --size;  
     if (s == i) // removed last element  
       queue[i] = null;  
     else {  
       E moved = (E) queue[s];  
       queue[s] = null;  
       siftDown(i, moved);  
       if (queue[i] == moved) {  
         siftUp(i, moved);  
         if (queue[i] != moved)  
           return moved;  
       }  
     }  
     return null;  
   }  
 *   String[] y = x.toArray(new String[0]);  
 * @throws NullPointerException if the specified array is null  
   public <T> T[] toArray(T[] a) {  
     if (a.length < size)  
       // Make a new array of a's runtime type, but my contents:  
       return (T[]) Arrays.copyOf(queue, size, a.getClass());  
      System.arraycopy(queue, 0, a, 0, size);  
     if (a.length > size)  
       a[size] = null;  
     return a;  
   }  
   public Iterator<E> iterator() {  
     return new Itr();  
   }  
   private final class Itr implements Iterator<E> {  
      * Index (into queue array) of element to be returned by  
      * subsequent call to next.  
     private int cursor = 0;  
      * Index of element returned by most recent call to next,  
      * unless that element came from the forgetMeNot list.  
      * Set to -1 if element is deleted by a call to remove.  
     private int lastRet = -1;  
      * A queue of elements that were moved from the unvisited portion of  
      * the heap into the visited portion as a result of "unlucky" element  
      * removals during the iteration. (Unlucky element removals are those  
      * that require a siftup instead of a siftdown.) We must visit all of  
      * the elements in this list to complete the iteration. We do this  
      * after we've completed the "normal" iteration.  
      *  
      * We expect that most iterations, even those involving removals,  
      * will not need to store elements in this field.  
     private ArrayDeque<E> forgetMeNot = null;  
      * Element returned by the most recent call to next iff that  
      * element was drawn from the forgetMeNot list.  
     private E lastRetElt = null;  
      * The modCount value that the iterator believes that the backing  
      * Queue should have. If this expectation is violated, the iterator  
      * has detected concurrent modification.  
     private int expectedModCount = modCount;  
     public boolean hasNext() {  
       return cursor < size ||  
         (forgetMeNot != null && !forgetMeNot.isEmpty());  
     }  
     public E next() {  
       if (expectedModCount != modCount)  
         throw new ConcurrentModificationException();  
       if (cursor < size)  
         return (E) queue[lastRet = cursor++];  
       if (forgetMeNot != null) {  
         lastRet = -1;  
         lastRetElt = forgetMeNot.poll();  
         if (lastRetElt != null)  
           return lastRetElt;  
       }  
       throw new NoSuchElementException();  
     }  
     public void remove() {  
       if (expectedModCount != modCount)  
         throw new ConcurrentModificationException();  
       if (lastRet != -1) {  
         E moved = PriorityQueue.this.removeAt(lastRet);  
         lastRet = -1;  
         if (moved == null)  
           cursor--;  
         else {  
           if (forgetMeNot == null)  
             forgetMeNot = new ArrayDeque<E>();  
           forgetMeNot.add(moved);  
         }  
       } else if (lastRetElt != null) {  
         PriorityQueue.this.removeEq(lastRetElt);  
         lastRetElt = null;  
       } else {  
         throw new IllegalStateException();  
        }  
       expectedModCount = modCount;  
     }  
 }  
   private void writeObject(java.io.ObjectOutputStream s)  
     throws java.io.IOException{  
     // Write out element count, and any hidden stuff  
     s.defaultWriteObject();  
     // Write out array length, for compatibility with 1.5 version  
     s.writeInt(Math.max(2, size + 1));  
     // Write out all elements in the "proper order".  
     for (int i = 0; i < size; i++)  
       s.writeObject(queue[i]);  
 }  
   private void readObject(java.io.ObjectInputStream s)  
     throws java.io.IOException, ClassNotFoundException {  
     // Read in size, and any hidden stuff  
     s.defaultReadObject();  
     // Read in (and discard) array length  
     s.readInt();  
      queue = new Object[size];  
     // Read in all elements.  
     for (int i = 0; i < size; i++)  
       queue[i] = s.readObject();  
      // Elements are guaranteed to be in "proper order", but the  
      // spec has never explained what that might be.  
      heapify();  
 }  
 }  
DelayQueue
It uses PriorityQueue underlying.
 package java.util.concurrent;  
 * An unbounded {@linkplain BlockingQueue blocking queue} of  
  * <tt>Delayed</tt> elements, in which an element can only be taken  
  * when its delay has expired. The <em>head</em> of the queue is that  
  * <tt>Delayed</tt> element whose delay expired furthest in the  
  * past. If no delay has expired there is no head and <tt>poll</tt>  
  * will return <tt>null</tt>. Expiration occurs when an element's  
  * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less  
  * than or equal to zero. Even though unexpired elements cannot be  
  * removed using <tt>take</tt> or <tt>poll</tt>, they are otherwise  
  * treated as normal elements. For example, the <tt>size</tt> method  
  * returns the count of both expired and unexpired elements.  
  * This queue does not permit null elements.   
 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>  
   implements BlockingQueue<E> {  
   private transient final ReentrantLock lock = new ReentrantLock();  
   private transient final Condition available = lock.newCondition();  
   private final PriorityQueue<E> q = new PriorityQueue<E>();  
   public boolean offer(E e) {  
     final ReentrantLock lock = this.lock;  
     lock.lock();  
     try {  
       E first = q.peek();  
       q.offer(e);  
       if (first == null || e.compareTo(first) < 0)  
         available.signalAll();  
       return true;  
     } finally {  
       lock.unlock();  
     }  
 }  
    * Retrieves and removes the head of this queue, or returns <tt>null</tt>  
    * if this queue has no elements with an expired delay.  
    * @return the head of this queue, or <tt>null</tt> if this  
    *     queue has no elements with an expired delay  
   public E poll() {  
     final ReentrantLock lock = this.lock;  
     lock.lock();  
     try {  
       E first = q.peek();  
       if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)  
         return null;  
       else {  
         E x = q.poll();  
         assert x != null;  
         if (q.size() != 0)  
           available.signalAll();  
         return x;  
       }  
     } finally {  
       lock.unlock();  
     }  
   }  
    * Retrieves and removes the head of this queue, waiting if necessary  
    * until an element with an expired delay is available on this queue,  
    * or the specified wait time expires.  
   public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
     long nanos = unit.toNanos(timeout);  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       for (;;) {  
         E first = q.peek();  
         if (first == null) {  
           if (nanos <= 0)  
             return null;  
           else  
             nanos = available.awaitNanos(nanos);  
         } else {  
           long delay = first.getDelay(TimeUnit.NANOSECONDS);  
           if (delay > 0) {  
             if (nanos <= 0)  
               return null;  
             if (delay > nanos)  
               delay = nanos;  
             long timeLeft = available.awaitNanos(delay);  
             nanos -= delay - timeLeft;  
           } else {  
             E x = q.poll();  
             assert x != null;  
             if (q.size() != 0)  
               available.signalAll();  
             return x;  
           }  
         }  
       }  
     } finally {  
       lock.unlock();  
     }  
   }  
    * Retrieves and removes the head of this queue, waiting if necessary  
    * until an element with an expired delay is available on this queue.  
   public E take() throws InterruptedException {  
     final ReentrantLock lock = this.lock;  
     lock.lockInterruptibly();  
     try {  
       for (;;) {  
         E first = q.peek();  
         if (first == null) {  
           available.await();  
         } else {  
           long delay = first.getDelay(TimeUnit.NANOSECONDS);  
           if (delay > 0) {  
             long tl = available.awaitNanos(delay);  
           } else {  
             E x = q.poll();  
             assert x != null;  
             if (q.size() != 0)  
               available.signalAll(); // wake up other takers  
             return x;  
           }  
         }  
       }  
     } finally {  
       lock.unlock();  
     }  
   }  
    * Returns an iterator over all the elements (both expired and  
    * unexpired) in this queue. The iterator does not return the  
    * elements in any particular order. The returned  
    * <tt>Iterator</tt> is a "weakly consistent" iterator that will  
    * never throw {@link ConcurrentModificationException}, and  
    * guarantees to traverse elements as they existed upon  
    * construction of the iterator, and may (but is not guaranteed  
    * to) reflect any modifications subsequent to construction.  
   public Iterator<E> iterator() {  
     return new Itr(toArray());  
   }  
    * Snapshot iterator that works off copy of underlying q array.  
   private class Itr implements Iterator<E> {  
     final Object[] array; // Array of all elements  
      int cursor;      // index of next element to return;  
      int lastRet;     // index of last element, or -1 if no such  
     Itr(Object[] array) {  
       lastRet = -1;  
       this.array = array;  
     }  
     public boolean hasNext() {  
       return cursor < array.length;  
     }  
     public E next() {  
       if (cursor >= array.length)  
         throw new NoSuchElementException();  
       lastRet = cursor;  
       return (E)array[cursor++];  
     }  
     public void remove() {  
       if (lastRet < 0)  
           throw new IllegalStateException();  
       Object x = array[lastRet];  
       lastRet = -1;  
       // Traverse underlying queue to find == element,  
       // not just a .equals element.  
       lock.lock();  
       try {  
         for (Iterator it = q.iterator(); it.hasNext(); ) {  
           if (it.next() == x) {  
             it.remove();  
             return;  
           }  
         }  
       } finally {  
         lock.unlock();  
       }  
     }  
 }  
 }  
 * A mix-in style interface for marking objects that should be  
  * acted upon after a given delay.  
 * <p>An implementation of this interface must define a  
  * <tt>compareTo</tt> method that provides an ordering consistent with  
  * its <tt>getDelay</tt> method.  
 public interface Delayed extends Comparable<Delayed> {  
   long getDelay(TimeUnit unit);  
 }  
ExecutorCompletionService
 package java.util.concurrent;  
 public class ExecutorCompletionService<V> implements CompletionService<V> {  
   private final Executor executor;  
   private final AbstractExecutorService aes;  
 private final BlockingQueue<Future<V>> completionQueue;  
   public ExecutorCompletionService(Executor executor,  
                    BlockingQueue<Future<V>> completionQueue) {  
     if (executor == null || completionQueue == null)  
       throw new NullPointerException();  
     this.executor = executor;  
     this.aes = (executor instanceof AbstractExecutorService) ?  
       (AbstractExecutorService) executor : null;  
     this.completionQueue = completionQueue;  
   }  
   public Future<V> submit(Callable<V> task) {  
     if (task == null) throw new NullPointerException();  
     RunnableFuture<V> f = newTaskFor(task);  
     executor.execute(new QueueingFuture(f));  
     return f;  
   }  
   public Future<V> submit(Runnable task, V result) {  
     if (task == null) throw new NullPointerException();  
     RunnableFuture<V> f = newTaskFor(task, result);  
     executor.execute(new QueueingFuture(f));  
     return f;  
   }  
   public Future<V> take() throws InterruptedException {  
     return completionQueue.take();  
   }  
   public Future<V> poll() {  
     return completionQueue.poll();  
   }  
   public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException {  
     return completionQueue.poll(timeout, unit);  
   }  
   private class QueueingFuture extends FutureTask<Void> {  
     QueueingFuture(RunnableFuture<V> task) {  
       super(task, null);  
       this.task = task;  
     }  
     protected void done() { completionQueue.add(task); }  
     private final Future<V> task;  
   }  
   private RunnableFuture<V> newTaskFor(Callable<V> task) {  
     if (aes == null)  
       return new FutureTask<V>(task);  
     else  
       return aes.newTaskFor(task);  
   }  
   private RunnableFuture<V> newTaskFor(Runnable task, V result) {  
     if (aes == null)  
       return new FutureTask<V>(task, result);  
     else  
       return aes.newTaskFor(task, result);  
 }  
 }  
ExecutorService
 public interface ExecutorService extends Executor {  
   <T> Future<T> submit(Callable<T> task);  
   <T> Future<T> submit(Runnable task, T result);  
   Future<?> submit(Runnable task);  
   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)  
     throws InterruptedException;  
   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)  
     throws InterruptedException;  
    * Executes the given tasks, returning the result  
    * of one that has completed successfully (i.e., without throwing  
    * an exception), if any do. Upon normal or exceptional return,  
    * tasks that have not completed are cancelled.  
    * The results of this method are undefined if the given  
    * collection is modified while this operation is in progress.  
   <T> T invokeAny(Collection<? extends Callable<T>> tasks)  
     throws InterruptedException, ExecutionException;  
   <T> T invokeAny(Collection<? extends Callable<T>> tasks,  
           long timeout, TimeUnit unit)  
     throws InterruptedException, ExecutionException, TimeoutException;  
   boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;  
   void shutdown();  
   List<Runnable> shutdownNow();  
   boolean isShutdown();  
   boolean isTerminated();  
 }  
Future task
 public interface Future<V> {  
   boolean cancel(boolean mayInterruptIfRunning);  
   boolean isCancelled();  
   boolean isDone();  
   V get() throws InterruptedException, ExecutionException;  
   V get(long timeout, TimeUnit unit)  
     throws InterruptedException, ExecutionException, TimeoutException;  
 }  
 public interface RunnableFuture<V> extends Runnable, Future<V> {  
   void run();  
 }  
 public class FutureTask<V> implements RunnableFuture<V> {}  

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)