code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.regex; import sun.security.action.GetPropertyAction; /** {@collect.stats} * {@description.open} * Unchecked exception thrown to indicate a syntax error in a * regular-expression pattern. * {@description.close} * * @author unascribed * @since 1.4 * @spec JSR-51 */ public class PatternSyntaxException extends IllegalArgumentException { private final String desc; private final String pattern; private final int index; /** {@collect.stats} * {@description.open} * Constructs a new instance of this class. * {@description.close} * * @param desc * A description of the error * * @param regex * The erroneous pattern * * @param index * The approximate index in the pattern of the error, * or <tt>-1</tt> if the index is not known */ public PatternSyntaxException(String desc, String regex, int index) { this.desc = desc; this.pattern = regex; this.index = index; } /** {@collect.stats} * {@description.open} * Retrieves the error index. * {@description.close} * * @return The approximate index in the pattern of the error, * or <tt>-1</tt> if the index is not known */ public int getIndex() { return index; } /** {@collect.stats} * {@description.open} * Retrieves the description of the error. * {@description.close} * * @return The description of the error */ public String getDescription() { return desc; } /** {@collect.stats} * {@description.open} * Retrieves the erroneous regular-expression pattern. * {@description.close} * * @return The erroneous pattern */ public String getPattern() { return pattern; } private static final String nl = java.security.AccessController .doPrivileged(new GetPropertyAction("line.separator")); /** {@collect.stats} * {@description.open} * Returns a multi-line string containing the description of the syntax * error and its index, the erroneous regular-expression pattern, and a * visual indication of the error index within the pattern. * {@description.close} * * @return The full detail message */ public String getMessage() { StringBuffer sb = new StringBuffer(); sb.append(desc); if (index >= 0) { sb.append(" near index "); sb.append(index); } sb.append(nl); sb.append(pattern); if (index >= 0) { sb.append(nl); for (int i = 0; i < index; i++) sb.append(' '); sb.append('^'); } return sb.toString(); } }
Java
/* * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.regex; /** {@collect.stats} * {@description.open} * Utility class that implements the standard C ctype functionality. * {@description.close} * * @author Hong Zhang */ final class ASCII { static final int UPPER = 0x00000100; static final int LOWER = 0x00000200; static final int DIGIT = 0x00000400; static final int SPACE = 0x00000800; static final int PUNCT = 0x00001000; static final int CNTRL = 0x00002000; static final int BLANK = 0x00004000; static final int HEX = 0x00008000; static final int UNDER = 0x00010000; static final int ASCII = 0x0000FF00; static final int ALPHA = (UPPER|LOWER); static final int ALNUM = (UPPER|LOWER|DIGIT); static final int GRAPH = (PUNCT|UPPER|LOWER|DIGIT); static final int WORD = (UPPER|LOWER|UNDER|DIGIT); static final int XDIGIT = (HEX); private static final int[] ctype = new int[] { CNTRL, /* 00 (NUL) */ CNTRL, /* 01 (SOH) */ CNTRL, /* 02 (STX) */ CNTRL, /* 03 (ETX) */ CNTRL, /* 04 (EOT) */ CNTRL, /* 05 (ENQ) */ CNTRL, /* 06 (ACK) */ CNTRL, /* 07 (BEL) */ CNTRL, /* 08 (BS) */ SPACE+CNTRL+BLANK, /* 09 (HT) */ SPACE+CNTRL, /* 0A (LF) */ SPACE+CNTRL, /* 0B (VT) */ SPACE+CNTRL, /* 0C (FF) */ SPACE+CNTRL, /* 0D (CR) */ CNTRL, /* 0E (SI) */ CNTRL, /* 0F (SO) */ CNTRL, /* 10 (DLE) */ CNTRL, /* 11 (DC1) */ CNTRL, /* 12 (DC2) */ CNTRL, /* 13 (DC3) */ CNTRL, /* 14 (DC4) */ CNTRL, /* 15 (NAK) */ CNTRL, /* 16 (SYN) */ CNTRL, /* 17 (ETB) */ CNTRL, /* 18 (CAN) */ CNTRL, /* 19 (EM) */ CNTRL, /* 1A (SUB) */ CNTRL, /* 1B (ESC) */ CNTRL, /* 1C (FS) */ CNTRL, /* 1D (GS) */ CNTRL, /* 1E (RS) */ CNTRL, /* 1F (US) */ SPACE+BLANK, /* 20 SPACE */ PUNCT, /* 21 ! */ PUNCT, /* 22 " */ PUNCT, /* 23 # */ PUNCT, /* 24 $ */ PUNCT, /* 25 % */ PUNCT, /* 26 & */ PUNCT, /* 27 ' */ PUNCT, /* 28 ( */ PUNCT, /* 29 ) */ PUNCT, /* 2A * */ PUNCT, /* 2B + */ PUNCT, /* 2C , */ PUNCT, /* 2D - */ PUNCT, /* 2E . */ PUNCT, /* 2F / */ DIGIT+HEX+0, /* 30 0 */ DIGIT+HEX+1, /* 31 1 */ DIGIT+HEX+2, /* 32 2 */ DIGIT+HEX+3, /* 33 3 */ DIGIT+HEX+4, /* 34 4 */ DIGIT+HEX+5, /* 35 5 */ DIGIT+HEX+6, /* 36 6 */ DIGIT+HEX+7, /* 37 7 */ DIGIT+HEX+8, /* 38 8 */ DIGIT+HEX+9, /* 39 9 */ PUNCT, /* 3A : */ PUNCT, /* 3B ; */ PUNCT, /* 3C < */ PUNCT, /* 3D = */ PUNCT, /* 3E > */ PUNCT, /* 3F ? */ PUNCT, /* 40 @ */ UPPER+HEX+10, /* 41 A */ UPPER+HEX+11, /* 42 B */ UPPER+HEX+12, /* 43 C */ UPPER+HEX+13, /* 44 D */ UPPER+HEX+14, /* 45 E */ UPPER+HEX+15, /* 46 F */ UPPER+16, /* 47 G */ UPPER+17, /* 48 H */ UPPER+18, /* 49 I */ UPPER+19, /* 4A J */ UPPER+20, /* 4B K */ UPPER+21, /* 4C L */ UPPER+22, /* 4D M */ UPPER+23, /* 4E N */ UPPER+24, /* 4F O */ UPPER+25, /* 50 P */ UPPER+26, /* 51 Q */ UPPER+27, /* 52 R */ UPPER+28, /* 53 S */ UPPER+29, /* 54 T */ UPPER+30, /* 55 U */ UPPER+31, /* 56 V */ UPPER+32, /* 57 W */ UPPER+33, /* 58 X */ UPPER+34, /* 59 Y */ UPPER+35, /* 5A Z */ PUNCT, /* 5B [ */ PUNCT, /* 5C \ */ PUNCT, /* 5D ] */ PUNCT, /* 5E ^ */ PUNCT|UNDER, /* 5F _ */ PUNCT, /* 60 ` */ LOWER+HEX+10, /* 61 a */ LOWER+HEX+11, /* 62 b */ LOWER+HEX+12, /* 63 c */ LOWER+HEX+13, /* 64 d */ LOWER+HEX+14, /* 65 e */ LOWER+HEX+15, /* 66 f */ LOWER+16, /* 67 g */ LOWER+17, /* 68 h */ LOWER+18, /* 69 i */ LOWER+19, /* 6A j */ LOWER+20, /* 6B k */ LOWER+21, /* 6C l */ LOWER+22, /* 6D m */ LOWER+23, /* 6E n */ LOWER+24, /* 6F o */ LOWER+25, /* 70 p */ LOWER+26, /* 71 q */ LOWER+27, /* 72 r */ LOWER+28, /* 73 s */ LOWER+29, /* 74 t */ LOWER+30, /* 75 u */ LOWER+31, /* 76 v */ LOWER+32, /* 77 w */ LOWER+33, /* 78 x */ LOWER+34, /* 79 y */ LOWER+35, /* 7A z */ PUNCT, /* 7B { */ PUNCT, /* 7C | */ PUNCT, /* 7D } */ PUNCT, /* 7E ~ */ CNTRL, /* 7F (DEL) */ }; static int getType(int ch) { return ((ch & 0xFFFFFF80) == 0 ? ctype[ch] : 0); } static boolean isType(int ch, int type) { return (getType(ch) & type) != 0; } static boolean isAscii(int ch) { return ((ch & 0xFFFFFF80) == 0); } static boolean isAlpha(int ch) { return isType(ch, ALPHA); } static boolean isDigit(int ch) { return ((ch-'0')|('9'-ch)) >= 0; } static boolean isAlnum(int ch) { return isType(ch, ALNUM); } static boolean isGraph(int ch) { return isType(ch, GRAPH); } static boolean isPrint(int ch) { return ((ch-0x20)|(0x7E-ch)) >= 0; } static boolean isPunct(int ch) { return isType(ch, PUNCT); } static boolean isSpace(int ch) { return isType(ch, SPACE); } static boolean isHexDigit(int ch) { return isType(ch, HEX); } static boolean isOctDigit(int ch) { return ((ch-'0')|('7'-ch)) >= 0; } static boolean isCntrl(int ch) { return isType(ch, CNTRL); } static boolean isLower(int ch) { return ((ch-'a')|('z'-ch)) >= 0; } static boolean isUpper(int ch) { return ((ch-'A')|('Z'-ch)) >= 0; } static boolean isWord(int ch) { return isType(ch, WORD); } static int toDigit(int ch) { return (ctype[ch & 0x7F] & 0x3F); } static int toLower(int ch) { return isUpper(ch) ? (ch + 0x20) : ch; } static int toUpper(int ch) { return isLower(ch) ? (ch - 0x20) : ch; } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.regex; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.CharacterIterator; import java.text.Normalizer; import java.util.ArrayList; import java.util.HashMap; import java.util.Arrays; /** {@collect.stats} * {@description.open} * A compiled representation of a regular expression. * * <p> A regular expression, specified as a string, must first be compiled into * an instance of this class. The resulting pattern can then be used to create * a {@link Matcher} object that can match arbitrary {@link * java.lang.CharSequence </code>character sequences<code>} against the regular * expression. All of the state involved in performing a match resides in the * matcher, so many matchers can share the same pattern. * * <p> A typical invocation sequence is thus * * <blockquote><pre> * Pattern p = Pattern.{@link #compile compile}("a*b"); * Matcher m = p.{@link #matcher matcher}("aaaaab"); * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote> * * <p> A {@link #matches matches} method is defined by this class as a * convenience for when a regular expression is used just once. This method * compiles an expression and matches an input sequence against it in a single * invocation. The statement * * <blockquote><pre> * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote> * * is equivalent to the three statements above, though for repeated matches it * is less efficient since it does not allow the compiled pattern to be reused. * * <p> Instances of this class are immutable and are safe for use by multiple * concurrent threads. Instances of the {@link Matcher} class are not safe for * such use. * * * <a name="sum"> * <h4> Summary of regular-expression constructs </h4> * * <table border="0" cellpadding="1" cellspacing="0" * summary="Regular expression constructs, and what they match"> * * <tr align="left"> * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th> * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th> * </tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="characters">Characters</th></tr> * * <tr><td valign="top" headers="construct characters"><i>x</i></td> * <td headers="matches">The character <i>x</i></td></tr> * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td> * <td headers="matches">The backslash character</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td> * <td headers="matches">The character with octal value <tt>0</tt><i>n</i> * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td> * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i> * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td> * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i> * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>m</i>&nbsp;<tt>&lt;=</tt>&nbsp;3, * 0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td> * <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hh</i></td></tr> * <tr><td valign="top" headers="construct characters"><tt>&#92;u</tt><i>hhhh</i></td> * <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hhhh</i></td></tr> * <tr><td valign="top" headers="matches"><tt>\t</tt></td> * <td headers="matches">The tab character (<tt>'&#92;u0009'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td> * <td headers="matches">The newline (line feed) character (<tt>'&#92;u000A'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td> * <td headers="matches">The carriage-return character (<tt>'&#92;u000D'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td> * <td headers="matches">The form-feed character (<tt>'&#92;u000C'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td> * <td headers="matches">The alert (bell) character (<tt>'&#92;u0007'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td> * <td headers="matches">The escape character (<tt>'&#92;u001B'</tt>)</td></tr> * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td> * <td headers="matches">The control character corresponding to <i>x</i></td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr> * * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td> * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr> * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td> * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr> * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td> * <td headers="matches"><tt>a</tt> through <tt>z</tt> * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr> * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td> * <td headers="matches"><tt>a</tt> through <tt>d</tt>, * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr> * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td> * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr> * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td> * <td headers="matches"><tt>a</tt> through <tt>z</tt>, * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr> * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td> * <td headers="matches"><tt>a</tt> through <tt>z</tt>, * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr> * <tr><th>&nbsp;</th></tr> * * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr> * * <tr><td valign="top" headers="construct predef"><tt>.</tt></td> * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr> * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td> * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr> * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td> * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr> * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td> * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr> * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td> * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr> * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td> * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr> * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td> * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr> * * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td> * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td> * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td> * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td> * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td> * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td> * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td> * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr> * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt> * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> --> * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td> * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td> * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td> * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td> * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td> * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr> * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td> * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr> * * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td> * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr> * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td> * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr> * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td> * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr> * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td> * <td>Equivalent to java.lang.Character.isMirrored()</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode blocks and categories</th></tr> * * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td> * <td headers="matches">A character in the Greek&nbsp;block (simple <a href="#ubc">block</a>)</td></tr> * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td> * <td headers="matches">An uppercase letter (simple <a href="#ubc">category</a>)</td></tr> * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td> * <td headers="matches">A currency symbol</td></tr> * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td> * <td headers="matches">Any character except one in the Greek block (negation)</td></tr> * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]]&nbsp;</tt></td> * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr> * * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td> * <td headers="matches">The beginning of a line</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td> * <td headers="matches">The end of a line</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td> * <td headers="matches">A word boundary</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td> * <td headers="matches">A non-word boundary</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td> * <td headers="matches">The beginning of the input</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td> * <td headers="matches">The end of the previous match</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td> * <td headers="matches">The end of the input but for the final * <a href="#lt">terminator</a>, if&nbsp;any</td></tr> * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td> * <td headers="matches">The end of the input</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr> * * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td> * <td headers="matches"><i>X</i>, once or not at all</td></tr> * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td> * <td headers="matches"><i>X</i>, zero or more times</td></tr> * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td> * <td headers="matches"><i>X</i>, one or more times</td></tr> * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td> * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr> * * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td> * <td headers="matches"><i>X</i>, once or not at all</td></tr> * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td> * <td headers="matches"><i>X</i>, zero or more times</td></tr> * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td> * <td headers="matches"><i>X</i>, one or more times</td></tr> * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td> * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr> * * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td> * <td headers="matches"><i>X</i>, once or not at all</td></tr> * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td> * <td headers="matches"><i>X</i>, zero or more times</td></tr> * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td> * <td headers="matches"><i>X</i>, one or more times</td></tr> * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td> * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr> * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td> * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr> * * <tr><td valign="top" headers="construct logical"><i>XY</i></td> * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr> * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td> * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr> * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td> * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="backref">Back references</th></tr> * * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td> * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup> * <a href="#cg">capturing group</a> matched</td></tr> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr> * * <tr><td valign="top" headers="construct quot"><tt>\</tt></td> * <td headers="matches">Nothing, but quotes the following character</td></tr> * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td> * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr> * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td> * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr> * <!-- Metachars: !$()*+.<>?[\]^{|} --> * * <tr><th>&nbsp;</th></tr> * <tr align="left"><th colspan="2" id="special">Special constructs (non-capturing)</th></tr> * * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux)&nbsp;</tt></td> * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a> * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> on - off</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt>&nbsp;&nbsp;</td> * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a> * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a > * <a href="#COMMENTS">x</a> on - off</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?&lt;=</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?&lt;!</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr> * <tr><td valign="top" headers="construct special"><tt>(?&gt;</tt><i>X</i><tt>)</tt></td> * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr> * * </table> * * <hr> * * * <a name="bs"> * <h4> Backslashes, escapes, and quoting </h4> * * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped * constructs, as defined in the table above, as well as to quote characters * that otherwise would be interpreted as unescaped constructs. Thus the * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a * left brace. * * <p> It is an error to use a backslash prior to any alphabetic character that * does not denote an escaped construct; these are reserved for future * extensions to the regular-expression language. A backslash may be used * prior to a non-alphabetic character regardless of whether that character is * part of an unescaped construct. * * <p> Backslashes within string literals in Java source code are interpreted * as required by the <a * href="http://java.sun.com/docs/books/jls">Java Language * Specification</a> as either <a * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#100850">Unicode * escapes</a> or other <a * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">character * escapes</a>. It is therefore necessary to double backslashes in string * literals that represent regular expressions to protect them from * interpretation by the Java bytecode compiler. The string literal * <tt>"&#92;b"</tt>, for example, matches a single backspace character when * interpreted as a regular expression, while <tt>"&#92;&#92;b"</tt> matches a * word boundary. The string literal <tt>"&#92;(hello&#92;)"</tt> is illegal * and leads to a compile-time error; in order to match the string * <tt>(hello)</tt> the string literal <tt>"&#92;&#92;(hello&#92;&#92;)"</tt> * must be used. * * <a name="cc"> * <h4> Character Classes </h4> * * <p> Character classes may appear within other character classes, and * may be composed by the union operator (implicit) and the intersection * operator (<tt>&amp;&amp;</tt>). * The union operator denotes a class that contains every character that is * in at least one of its operand classes. The intersection operator * denotes a class that contains every character that is in both of its * operand classes. * * <p> The precedence of character-class operators is as follows, from * highest to lowest: * * <blockquote><table border="0" cellpadding="1" cellspacing="0" * summary="Precedence of character class operators."> * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td> * <td><tt>\x</tt></td></tr> * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td>Grouping</td> * <td><tt>[...]</tt></td></tr> * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td>Range</td> * <td><tt>a-z</tt></td></tr> * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td>Union</td> * <td><tt>[a-e][i-u]</tt></td></tr> * <tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td>Intersection</td> * <td><tt>[a-z&&[aeiou]]</tt></td></tr> * </table></blockquote> * * <p> Note that a different set of metacharacters are in effect inside * a character class than outside a character class. For instance, the * regular expression <tt>.</tt> loses its special meaning inside a * character class, while the expression <tt>-</tt> becomes a range * forming metacharacter. * * <a name="lt"> * <h4> Line terminators </h4> * * <p> A <i>line terminator</i> is a one- or two-character sequence that marks * the end of a line of the input character sequence. The following are * recognized as line terminators: * * <ul> * * <li> A newline (line feed) character&nbsp;(<tt>'\n'</tt>), * * <li> A carriage-return character followed immediately by a newline * character&nbsp;(<tt>"\r\n"</tt>), * * <li> A standalone carriage-return character&nbsp;(<tt>'\r'</tt>), * * <li> A next-line character&nbsp;(<tt>'&#92;u0085'</tt>), * * <li> A line-separator character&nbsp;(<tt>'&#92;u2028'</tt>), or * * <li> A paragraph-separator character&nbsp;(<tt>'&#92;u2029</tt>). * * </ul> * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators * recognized are newline characters. * * <p> The regular expression <tt>.</tt> matches any character except a line * terminator unless the {@link #DOTALL} flag is specified. * * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore * line terminators and only match at the beginning and the end, respectively, * of the entire input sequence. If {@link #MULTILINE} mode is activated then * <tt>^</tt> matches at the beginning of input and after any line terminator * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt> * matches just before a line terminator or the end of the input sequence. * * <a name="cg"> * <h4> Groups and capturing </h4> * * <p> Capturing groups are numbered by counting their opening parentheses from * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there * are four such groups: </p> * * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings"> * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td><tt>((A)(B(C)))</tt></td></tr> * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td><tt>(A)</tt></td></tr> * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td><tt>(B(C))</tt></td></tr> * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th> * <td><tt>(C)</tt></td></tr> * </table></blockquote> * * <p> Group zero always stands for the entire expression. * * <p> Capturing groups are so named because, during a match, each subsequence * of the input sequence that matches such a group is saved. The captured * subsequence may be used later in the expression, via a back reference, and * may also be retrieved from the matcher once the match operation is complete. * * <p> The captured input associated with a group is always the subsequence * that the group most recently matched. If a group is evaluated a second time * because of quantification then its previously-captured value, if any, will * be retained if the second evaluation fails. Matching the string * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves * group two set to <tt>"b"</tt>. All captured input is discarded at the * beginning of each match. * * <p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups * that do not capture text and do not count towards the group total. * * * <h4> Unicode support </h4> * * <p> This class is in conformance with Level 1 of <a * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical * Standard #18: Unicode Regular Expression Guidelines</i></a>, plus RL2.1 * Canonical Equivalents. * * <p> Unicode escape sequences such as <tt>&#92;u2014</tt> in Java source code * are processed as described in <a * href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#100850">\u00A73.3</a> * of the Java Language Specification. Such escape sequences are also * implemented directly by the regular-expression parser so that Unicode * escapes can be used in expressions that are read from files or from the * keyboard. Thus the strings <tt>"&#92;u2014"</tt> and <tt>"\\u2014"</tt>, * while not equal, compile into the same pattern, which matches the character * with hexadecimal value <tt>0x2014</tt>. * * <a name="ubc"> <p>Unicode blocks and categories are written with the * <tt>\p</tt> and <tt>\P</tt> constructs as in * Perl. <tt>\p{</tt><i>prop</i><tt>}</tt> matches if the input has the * property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt> does not match if * the input has that property. Blocks are specified with the prefix * <tt>In</tt>, as in <tt>InMongolian</tt>. Categories may be specified with * the optional prefix <tt>Is</tt>: Both <tt>\p{L}</tt> and <tt>\p{IsL}</tt> * denote the category of Unicode letters. Blocks and categories can be used * both inside and outside of a character class. * * <p> The supported categories are those of * <a href="http://www.unicode.org/unicode/standard/standard.html"> * <i>The Unicode Standard</i></a> in the version specified by the * {@link java.lang.Character Character} class. The category names are those * defined in the Standard, both normative and informative. * The block names supported by <code>Pattern</code> are the valid block names * accepted and defined by * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}. * * <a name="jcc"> <p>Categories that behave like the java.lang.Character * boolean is<i>methodname</i> methods (except for the deprecated ones) are * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where * the specified property has the name <tt>java<i>methodname</i></tt>. * * <h4> Comparison to Perl 5 </h4> * * <p>The <code>Pattern</code> engine performs traditional NFA-based matching * with ordered alternation as occurs in Perl 5. * * <p> Perl constructs not supported by this class: </p> * * <ul> * * <li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>, * </p></li> * * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt> * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li> * * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li> * * <li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>, * <tt>\L</tt>, and <tt>\U</tt>. </p></li> * * </ul> * * <p> Constructs supported by this class but not by Perl: </p> * * <ul> * * <li><p> Possessive quantifiers, which greedily match as much as they can * and do not back off, even when doing so would allow the overall match to * succeed. </p></li> * * <li><p> Character-class union and intersection as described * <a href="#cc">above</a>.</p></li> * * </ul> * * <p> Notable differences from Perl: </p> * * <ul> * * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted * as back references; a backslash-escaped number greater than <tt>9</tt> is * treated as a back reference if at least that many subexpressions exist, * otherwise it is interpreted, if possible, as an octal escape. In this * class octal escapes must always begin with a zero. In this class, * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back * references, and a larger number is accepted as a back reference if at * least that many subexpressions exist at that point in the regular * expression, otherwise the parser will drop digits until the number is * smaller or equal to the existing number of groups or it is one digit. * </p></li> * * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes * where the last match left off. This functionality is provided implicitly * by the {@link Matcher} class: Repeated invocations of the {@link * Matcher#find find} method will resume where the last match left off, * unless the matcher is reset. </p></li> * * <li><p> In Perl, embedded flags at the top level of an expression affect * the whole expression. In this class, embedded flags always take effect * at the point at which they appear, whether they are at the top level or * within a group; in the latter case, flags are restored at the end of the * group just as in Perl. </p></li> * * <li><p> Perl is forgiving about malformed matching constructs, as in the * expression <tt>*a</tt>, as well as dangling brackets, as in the * expression <tt>abc]</tt>, and treats them as literals. This * class also accepts dangling brackets but is strict about dangling * metacharacters like +, ? and *, and will throw a * {@link PatternSyntaxException} if it encounters them. </p></li> * * </ul> * * * <p> For a more precise description of the behavior of regular expression * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/"> * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl, * O'Reilly and Associates, 2006.</a> * </p> * {@description.close} * * @see java.lang.String#split(String, int) * @see java.lang.String#split(String) * * @author Mike McCloskey * @author Mark Reinhold * @author JSR-51 Expert Group * @since 1.4 * @spec JSR-51 */ public final class Pattern implements java.io.Serializable { /** {@collect.stats} * {@description.open} * Regular expression modifier values. Instead of being passed as * arguments, they can also be passed as inline modifiers. * For example, the following statements have the same effect. * <pre> * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M); * RegExp r2 = RegExp.compile("(?im)abc", 0); * </pre> * * The flags are duplicated so that the familiar Perl match flag * names are available. * {@description.close} */ /** {@collect.stats} * {@description.open} * Enables Unix lines mode. * * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>. * * <p> Unix lines mode can also be enabled via the embedded flag * expression&nbsp;<tt>(?d)</tt>. * {@description.close} */ public static final int UNIX_LINES = 0x01; /** {@collect.stats} * {@description.open} * Enables case-insensitive matching. * * <p> By default, case-insensitive matching assumes that only characters * in the US-ASCII charset are being matched. Unicode-aware * case-insensitive matching can be enabled by specifying the {@link * #UNICODE_CASE} flag in conjunction with this flag. * * <p> Case-insensitive matching can also be enabled via the embedded flag * expression&nbsp;<tt>(?i)</tt>. * * <p> Specifying this flag may impose a slight performance penalty. </p> * {@description.close} */ public static final int CASE_INSENSITIVE = 0x02; /** {@collect.stats} * {@description.open} * Permits whitespace and comments in pattern. * * <p> In this mode, whitespace is ignored, and embedded comments starting * with <tt>#</tt> are ignored until the end of a line. * * <p> Comments mode can also be enabled via the embedded flag * expression&nbsp;<tt>(?x)</tt>. * {@description.close} */ public static final int COMMENTS = 0x04; /** {@collect.stats} * {@description.open} * Enables multiline mode. * * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match * just after or just before, respectively, a line terminator or the end of * the input sequence. By default these expressions only match at the * beginning and the end of the entire input sequence. * * <p> Multiline mode can also be enabled via the embedded flag * expression&nbsp;<tt>(?m)</tt>. </p> * {@description.close} */ public static final int MULTILINE = 0x08; /** {@collect.stats} * {@description.open} * Enables literal parsing of the pattern. * * <p> When this flag is specified then the input string that specifies * the pattern is treated as a sequence of literal characters. * Metacharacters or escape sequences in the input sequence will be * given no special meaning. * * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on * matching when used in conjunction with this flag. The other flags * become superfluous. * * <p> There is no embedded flag character for enabling literal parsing. * {@description.close} * @since 1.5 */ public static final int LITERAL = 0x10; /** {@collect.stats} * {@description.open} * Enables dotall mode. * * <p> In dotall mode, the expression <tt>.</tt> matches any character, * including a line terminator. By default this expression does not match * line terminators. * * <p> Dotall mode can also be enabled via the embedded flag * expression&nbsp;<tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for * "single-line" mode, which is what this is called in Perl.) </p> * {@description.close} */ public static final int DOTALL = 0x20; /** {@collect.stats} * {@description.open} * Enables Unicode-aware case folding. * * <p> When this flag is specified then case-insensitive matching, when * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner * consistent with the Unicode Standard. By default, case-insensitive * matching assumes that only characters in the US-ASCII charset are being * matched. * * <p> Unicode-aware case folding can also be enabled via the embedded flag * expression&nbsp;<tt>(?u)</tt>. * * <p> Specifying this flag may impose a performance penalty. </p> * {@description.close} */ public static final int UNICODE_CASE = 0x40; /** {@collect.stats} * {@description.open} * Enables canonical equivalence. * * <p> When this flag is specified then two characters will be considered * to match if, and only if, their full canonical decompositions match. * The expression <tt>"a&#92;u030A"</tt>, for example, will match the * string <tt>"&#92;u00E5"</tt> when this flag is specified. By default, * matching does not take canonical equivalence into account. * * <p> There is no embedded flag character for enabling canonical * equivalence. * * <p> Specifying this flag may impose a performance penalty. </p> * {@description.close} */ public static final int CANON_EQ = 0x80; /* Pattern has only two serialized components: The pattern string * and the flags, which are all that is needed to recompile the pattern * when it is deserialized. */ /** {@collect.stats} * {@description.open} * use serialVersionUID from Merlin b59 for interoperability * {@description.close} */ private static final long serialVersionUID = 5073258162644648461L; /** {@collect.stats} * {@description.open} * The original regular-expression pattern string. * {@description.close} * * @serial */ private String pattern; /** {@collect.stats} * {@description.open} * The original pattern flags. * {@description.close} * * @serial */ private int flags; /** {@collect.stats} * {@description.open} * Boolean indicating this Pattern is compiled; this is necessary in order * to lazily compile deserialized Patterns. * {@description.close} */ private transient volatile boolean compiled = false; /** {@collect.stats} * {@description.open} * The normalized pattern string. * {@description.close} */ private transient String normalizedPattern; /** {@collect.stats} * {@description.open} * The starting point of state machine for the find operation. This allows * a match to start anywhere in the input. * {@description.close} */ transient Node root; /** {@collect.stats} * {@description.open} * The root of object tree for a match operation. The pattern is matched * at the beginning. This may include a find that uses BnM or a First * node. * {@description.close} */ transient Node matchRoot; /** {@collect.stats} * {@description.open} * Temporary storage used by parsing pattern slice. * {@description.close} */ transient int[] buffer; /** {@collect.stats} * {@description.open} * Temporary storage used while parsing group references. * {@description.close} */ transient GroupHead[] groupNodes; /** {@collect.stats} * {@description.open} * Temporary null terminated code point array used by pattern compiling. * {@description.close} */ private transient int[] temp; /** {@collect.stats} * {@description.open} * The number of capturing groups in this Pattern. Used by matchers to * allocate storage needed to perform a match. * {@description.close} */ transient int capturingGroupCount; /** {@collect.stats} * {@description.open} * The local variable count used by parsing tree. Used by matchers to * allocate storage needed to perform a match. * {@description.close} */ transient int localCount; /** {@collect.stats} * {@description.open} * Index into the pattern string that keeps track of how much has been * parsed. * {@description.close} */ private transient int cursor; /** {@collect.stats} * {@description.open} * Holds the length of the pattern string. * {@description.close} */ private transient int patternLength; /** {@collect.stats} * {@description.open} * Compiles the given regular expression into a pattern. </p> * {@description.close} * * @param regex * The expression to be compiled * * @throws PatternSyntaxException * If the expression's syntax is invalid */ public static Pattern compile(String regex) { return new Pattern(regex, 0); } /** {@collect.stats} * {@description.open} * Compiles the given regular expression into a pattern with the given * flags. </p> * {@description.close} * * @param regex * The expression to be compiled * * @param flags * Match flags, a bit mask that may include * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL}, * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES}, * {@link #LITERAL} and {@link #COMMENTS} * * @throws IllegalArgumentException * If bit values other than those corresponding to the defined * match flags are set in <tt>flags</tt> * * @throws PatternSyntaxException * If the expression's syntax is invalid */ public static Pattern compile(String regex, int flags) { return new Pattern(regex, flags); } /** {@collect.stats} * {@description.open} * Returns the regular expression from which this pattern was compiled. * </p> * {@description.close} * * @return The source of this pattern */ public String pattern() { return pattern; } /** {@collect.stats} * {@description.open} * <p>Returns the string representation of this pattern. This * is the regular expression from which this pattern was * compiled.</p> * {@description.close} * * @return The string representation of this pattern * @since 1.5 */ public String toString() { return pattern; } /** {@collect.stats} * {@description.open} * Creates a matcher that will match the given input against this pattern. * </p> * {@description.close} * * @param input * The character sequence to be matched * * @return A new matcher for this pattern */ public Matcher matcher(CharSequence input) { if (!compiled) { synchronized(this) { if (!compiled) compile(); } } Matcher m = new Matcher(this, input); return m; } /** {@collect.stats} * {@description.open} * Returns this pattern's match flags. </p> * {@description.close} * * @return The match flags specified when this pattern was compiled */ public int flags() { return flags; } /** {@collect.stats} * {@description.open} * Compiles the given regular expression and attempts to match the given * input against it. * * <p> An invocation of this convenience method of the form * * <blockquote><pre> * Pattern.matches(regex, input);</pre></blockquote> * * behaves in exactly the same way as the expression * * <blockquote><pre> * Pattern.compile(regex).matcher(input).matches()</pre></blockquote> * * <p> If a pattern is to be used multiple times, compiling it once and reusing * it will be more efficient than invoking this method each time. </p> * {@description.close} * * @param regex * The expression to be compiled * * @param input * The character sequence to be matched * * @throws PatternSyntaxException * If the expression's syntax is invalid */ public static boolean matches(String regex, CharSequence input) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); return m.matches(); } /** {@collect.stats} * {@description.open} * Splits the given input sequence around matches of this pattern. * * <p> The array returned by this method contains each substring of the * input sequence that is terminated by another subsequence that matches * this pattern or is terminated by the end of the input sequence. The * substrings in the array are in the order in which they occur in the * input. If this pattern does not match any subsequence of the input then * the resulting array has just one element, namely the input sequence in * string form. * * <p> The <tt>limit</tt> parameter controls the number of times the * pattern is applied and therefore affects the length of the resulting * array. If the limit <i>n</i> is greater than zero then the pattern * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's * length will be no greater than <i>n</i>, and the array's last entry * will contain all input beyond the last matched delimiter. If <i>n</i> * is non-positive then the pattern will be applied as many times as * possible and the array can have any length. If <i>n</i> is zero then * the pattern will be applied as many times as possible, the array can * have any length, and trailing empty strings will be discarded. * * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following * results with these parameters: * * <blockquote><table cellpadding=1 cellspacing=0 * summary="Split examples showing regex, limit, and result"> * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th> * <th><P align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th> * <th><P align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr> * <tr><td align=center>:</td> * <td align=center>2</td> * <td><tt>{ "boo", "and:foo" }</tt></td></tr> * <tr><td align=center>:</td> * <td align=center>5</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>:</td> * <td align=center>-2</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>5</td> * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>-2</td> * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr> * <tr><td align=center>o</td> * <td align=center>0</td> * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> * </table></blockquote> * * {@description.close} * * @param input * The character sequence to be split * * @param limit * The result threshold, as described above * * @return The array of strings computed by splitting the input * around matches of this pattern */ public String[] split(CharSequence input, int limit) { int index = 0; boolean matchLimited = limit > 0; ArrayList<String> matchList = new ArrayList<String>(); Matcher m = matcher(input); // Add segments before each match found while(m.find()) { if (!matchLimited || matchList.size() < limit - 1) { String match = input.subSequence(index, m.start()).toString(); matchList.add(match); index = m.end(); } else if (matchList.size() == limit - 1) { // last one String match = input.subSequence(index, input.length()).toString(); matchList.add(match); index = m.end(); } } // If no match was found, return this if (index == 0) return new String[] {input.toString()}; // Add remaining segment if (!matchLimited || matchList.size() < limit) matchList.add(input.subSequence(index, input.length()).toString()); // Construct result int resultSize = matchList.size(); if (limit == 0) while (resultSize > 0 && matchList.get(resultSize-1).equals("")) resultSize--; String[] result = new String[resultSize]; return matchList.subList(0, resultSize).toArray(result); } /** {@collect.stats} * {@description.open} * Splits the given input sequence around matches of this pattern. * * <p> This method works as if by invoking the two-argument {@link * #split(java.lang.CharSequence, int) split} method with the given input * sequence and a limit argument of zero. Trailing empty strings are * therefore not included in the resulting array. </p> * * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following * results with these expressions: * * <blockquote><table cellpadding=1 cellspacing=0 * summary="Split examples showing regex and result"> * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th> * <th><P align="left"><i>Result</i></th></tr> * <tr><td align=center>:</td> * <td><tt>{ "boo", "and", "foo" }</tt></td></tr> * <tr><td align=center>o</td> * <td><tt>{ "b", "", ":and:f" }</tt></td></tr> * </table></blockquote> * * {@description.close} * * @param input * The character sequence to be split * * @return The array of strings computed by splitting the input * around matches of this pattern */ public String[] split(CharSequence input) { return split(input, 0); } /** {@collect.stats} * {@description.open} * Returns a literal pattern <code>String</code> for the specified * <code>String</code>. * * <p>This method produces a <code>String</code> that can be used to * create a <code>Pattern</code> that would match the string * <code>s</code> as if it were a literal pattern.</p> Metacharacters * or escape sequences in the input sequence will be given no special * meaning. * {@description.close} * * @param s The string to be literalized * @return A literal string replacement * @since 1.5 */ public static String quote(String s) { int slashEIndex = s.indexOf("\\E"); if (slashEIndex == -1) return "\\Q" + s + "\\E"; StringBuilder sb = new StringBuilder(s.length() * 2); sb.append("\\Q"); slashEIndex = 0; int current = 0; while ((slashEIndex = s.indexOf("\\E", current)) != -1) { sb.append(s.substring(current, slashEIndex)); current = slashEIndex + 2; sb.append("\\E\\\\E\\Q"); } sb.append(s.substring(current, s.length())); sb.append("\\E"); return sb.toString(); } /** {@collect.stats} * {@description.open} * Recompile the Pattern instance from a stream. The original pattern * string is read in and the object tree is recompiled from it. * {@description.close} */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in all fields s.defaultReadObject(); // Initialize counts capturingGroupCount = 1; localCount = 0; // if length > 0, the Pattern is lazily compiled compiled = false; if (pattern.length() == 0) { root = new Start(lastAccept); matchRoot = lastAccept; compiled = true; } } /** {@collect.stats} * {@description.open} * This private constructor is used to create all Patterns. The pattern * string and match flags are all that is needed to completely describe * a Pattern. An empty pattern string results in an object tree with * only a Start node and a LastNode node. * {@description.close} */ private Pattern(String p, int f) { pattern = p; flags = f; // Reset group index count capturingGroupCount = 1; localCount = 0; if (pattern.length() > 0) { compile(); } else { root = new Start(lastAccept); matchRoot = lastAccept; } } /** {@collect.stats} * {@description.open} * The pattern is converted to normalizedD form and then a pure group * is constructed to match canonical equivalences of the characters. * {@description.close} */ private void normalize() { boolean inCharClass = false; int lastCodePoint = -1; // Convert pattern into normalizedD form normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD); patternLength = normalizedPattern.length(); // Modify pattern to match canonical equivalences StringBuilder newPattern = new StringBuilder(patternLength); for(int i=0; i<patternLength; ) { int c = normalizedPattern.codePointAt(i); StringBuilder sequenceBuffer; if ((Character.getType(c) == Character.NON_SPACING_MARK) && (lastCodePoint != -1)) { sequenceBuffer = new StringBuilder(); sequenceBuffer.appendCodePoint(lastCodePoint); sequenceBuffer.appendCodePoint(c); while(Character.getType(c) == Character.NON_SPACING_MARK) { i += Character.charCount(c); if (i >= patternLength) break; c = normalizedPattern.codePointAt(i); sequenceBuffer.appendCodePoint(c); } String ea = produceEquivalentAlternation( sequenceBuffer.toString()); newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint)); newPattern.append("(?:").append(ea).append(")"); } else if (c == '[' && lastCodePoint != '\\') { i = normalizeCharClass(newPattern, i); } else { newPattern.appendCodePoint(c); } lastCodePoint = c; i += Character.charCount(c); } normalizedPattern = newPattern.toString(); } /** {@collect.stats} * {@description.open} * Complete the character class being parsed and add a set * of alternations to it that will match the canonical equivalences * of the characters within the class. * {@description.close} */ private int normalizeCharClass(StringBuilder newPattern, int i) { StringBuilder charClass = new StringBuilder(); StringBuilder eq = null; int lastCodePoint = -1; String result; i++; charClass.append("["); while(true) { int c = normalizedPattern.codePointAt(i); StringBuilder sequenceBuffer; if (c == ']' && lastCodePoint != '\\') { charClass.append((char)c); break; } else if (Character.getType(c) == Character.NON_SPACING_MARK) { sequenceBuffer = new StringBuilder(); sequenceBuffer.appendCodePoint(lastCodePoint); while(Character.getType(c) == Character.NON_SPACING_MARK) { sequenceBuffer.appendCodePoint(c); i += Character.charCount(c); if (i >= normalizedPattern.length()) break; c = normalizedPattern.codePointAt(i); } String ea = produceEquivalentAlternation( sequenceBuffer.toString()); charClass.setLength(charClass.length()-Character.charCount(lastCodePoint)); if (eq == null) eq = new StringBuilder(); eq.append('|'); eq.append(ea); } else { charClass.appendCodePoint(c); i++; } if (i == normalizedPattern.length()) throw error("Unclosed character class"); lastCodePoint = c; } if (eq != null) { result = "(?:"+charClass.toString()+eq.toString()+")"; } else { result = charClass.toString(); } newPattern.append(result); return i; } /** {@collect.stats} * {@description.open} * Given a specific sequence composed of a regular character and * combining marks that follow it, produce the alternation that will * match all canonical equivalences of that sequence. * {@description.close} */ private String produceEquivalentAlternation(String source) { int len = countChars(source, 0, 1); if (source.length() == len) // source has one character. return source; String base = source.substring(0,len); String combiningMarks = source.substring(len); String[] perms = producePermutations(combiningMarks); StringBuilder result = new StringBuilder(source); // Add combined permutations for(int x=0; x<perms.length; x++) { String next = base + perms[x]; if (x>0) result.append("|"+next); next = composeOneStep(next); if (next != null) result.append("|"+produceEquivalentAlternation(next)); } return result.toString(); } /** {@collect.stats} * {@description.open} * Returns an array of strings that have all the possible * permutations of the characters in the input string. * This is used to get a list of all possible orderings * of a set of combining marks. Note that some of the permutations * are invalid because of combining class collisions, and these * possibilities must be removed because they are not canonically * equivalent. * {@description.close} */ private String[] producePermutations(String input) { if (input.length() == countChars(input, 0, 1)) return new String[] {input}; if (input.length() == countChars(input, 0, 2)) { int c0 = Character.codePointAt(input, 0); int c1 = Character.codePointAt(input, Character.charCount(c0)); if (getClass(c1) == getClass(c0)) { return new String[] {input}; } String[] result = new String[2]; result[0] = input; StringBuilder sb = new StringBuilder(2); sb.appendCodePoint(c1); sb.appendCodePoint(c0); result[1] = sb.toString(); return result; } int length = 1; int nCodePoints = countCodePoints(input); for(int x=1; x<nCodePoints; x++) length = length * (x+1); String[] temp = new String[length]; int combClass[] = new int[nCodePoints]; for(int x=0, i=0; x<nCodePoints; x++) { int c = Character.codePointAt(input, i); combClass[x] = getClass(c); i += Character.charCount(c); } // For each char, take it out and add the permutations // of the remaining chars int index = 0; int len; // offset maintains the index in code units. loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) { len = countChars(input, offset, 1); boolean skip = false; for(int y=x-1; y>=0; y--) { if (combClass[y] == combClass[x]) { continue loop; } } StringBuilder sb = new StringBuilder(input); String otherChars = sb.delete(offset, offset+len).toString(); String[] subResult = producePermutations(otherChars); String prefix = input.substring(offset, offset+len); for(int y=0; y<subResult.length; y++) temp[index++] = prefix + subResult[y]; } String[] result = new String[index]; for (int x=0; x<index; x++) result[x] = temp[x]; return result; } private int getClass(int c) { return sun.text.Normalizer.getCombiningClass(c); } /** {@collect.stats} * {@description.open} * Attempts to compose input by combining the first character * with the first combining mark following it. Returns a String * that is the composition of the leading character with its first * combining mark followed by the remaining combining marks. Returns * null if the first two characters cannot be further composed. * {@description.close} */ private String composeOneStep(String input) { int len = countChars(input, 0, 2); String firstTwoCharacters = input.substring(0, len); String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC); if (result.equals(firstTwoCharacters)) return null; else { String remainder = input.substring(len); return result + remainder; } } /** {@collect.stats} * {@description.open} * Preprocess any \Q...\E sequences in `temp', meta-quoting them. * See the description of `quotemeta' in perlfunc(1). * {@description.close} */ private void RemoveQEQuoting() { final int pLen = patternLength; int i = 0; while (i < pLen-1) { if (temp[i] != '\\') i += 1; else if (temp[i + 1] != 'Q') i += 2; else break; } if (i >= pLen - 1) // No \Q sequence found return; int j = i; i += 2; int[] newtemp = new int[j + 2*(pLen-i) + 2]; System.arraycopy(temp, 0, newtemp, 0, j); boolean inQuote = true; while (i < pLen) { int c = temp[i++]; if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) { newtemp[j++] = c; } else if (c != '\\') { if (inQuote) newtemp[j++] = '\\'; newtemp[j++] = c; } else if (inQuote) { if (temp[i] == 'E') { i++; inQuote = false; } else { newtemp[j++] = '\\'; newtemp[j++] = '\\'; } } else { if (temp[i] == 'Q') { i++; inQuote = true; } else { newtemp[j++] = c; if (i != pLen) newtemp[j++] = temp[i++]; } } } patternLength = j; temp = Arrays.copyOf(newtemp, j + 2); // double zero termination } /** {@collect.stats} * {@description.open} * Copies regular expression to an int array and invokes the parsing * of the expression which will create the object tree. * {@description.close} */ private void compile() { // Handle canonical equivalences if (has(CANON_EQ) && !has(LITERAL)) { normalize(); } else { normalizedPattern = pattern; } patternLength = normalizedPattern.length(); // Copy pattern to int array for convenience // Use double zero to terminate pattern temp = new int[patternLength + 2]; boolean hasSupplementary = false; int c, count = 0; // Convert all chars into code points for (int x = 0; x < patternLength; x += Character.charCount(c)) { c = normalizedPattern.codePointAt(x); if (isSupplementary(c)) { hasSupplementary = true; } temp[count++] = c; } patternLength = count; // patternLength now in code points if (! has(LITERAL)) RemoveQEQuoting(); // Allocate all temporary objects here. buffer = new int[32]; groupNodes = new GroupHead[10]; if (has(LITERAL)) { // Literal pattern handling matchRoot = newSlice(temp, patternLength, hasSupplementary); matchRoot.next = lastAccept; } else { // Start recursive descent parsing matchRoot = expr(lastAccept); // Check extra pattern characters if (patternLength != cursor) { if (peek() == ')') { throw error("Unmatched closing ')'"); } else { throw error("Unexpected internal error"); } } } // Peephole optimization if (matchRoot instanceof Slice) { root = BnM.optimize(matchRoot); if (root == matchRoot) { root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot); } } else if (matchRoot instanceof Begin || matchRoot instanceof First) { root = matchRoot; } else { root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot); } // Release temporary storage temp = null; buffer = null; groupNodes = null; patternLength = 0; compiled = true; } /** {@collect.stats} * {@description.open} * Used to print out a subtree of the Pattern to help with debugging. * {@description.close} */ private static void printObjectTree(Node node) { while(node != null) { if (node instanceof Prolog) { System.out.println(node); printObjectTree(((Prolog)node).loop); System.out.println("**** end contents prolog loop"); } else if (node instanceof Loop) { System.out.println(node); printObjectTree(((Loop)node).body); System.out.println("**** end contents Loop body"); } else if (node instanceof Curly) { System.out.println(node); printObjectTree(((Curly)node).atom); System.out.println("**** end contents Curly body"); } else if (node instanceof GroupCurly) { System.out.println(node); printObjectTree(((GroupCurly)node).atom); System.out.println("**** end contents GroupCurly body"); } else if (node instanceof GroupTail) { System.out.println(node); System.out.println("Tail next is "+node.next); return; } else { System.out.println(node); } node = node.next; if (node != null) System.out.println("->next:"); if (node == Pattern.accept) { System.out.println("Accept Node"); node = null; } } } /** {@collect.stats} * {@description.open} * Used to accumulate information about a subtree of the object graph * so that optimizations can be applied to the subtree. * {@description.close} */ static final class TreeInfo { int minLength; int maxLength; boolean maxValid; boolean deterministic; TreeInfo() { reset(); } void reset() { minLength = 0; maxLength = 0; maxValid = true; deterministic = true; } } /* * The following private methods are mainly used to improve the * readability of the code. In order to let the Java compiler easily * inline them, we should not put many assertions or error checks in them. */ /** {@collect.stats} * {@description.open} * Indicates whether a particular flag is set or not. * {@description.close} */ private boolean has(int f) { return (flags & f) != 0; } /** {@collect.stats} * {@description.open} * Match next character, signal error if failed. * {@description.close} */ private void accept(int ch, String s) { int testChar = temp[cursor++]; if (has(COMMENTS)) testChar = parsePastWhitespace(testChar); if (ch != testChar) { throw error(s); } } /** {@collect.stats} * {@description.open} * Mark the end of pattern with a specific character. * {@description.close} */ private void mark(int c) { temp[patternLength] = c; } /** {@collect.stats} * {@description.open} * Peek the next character, and do not advance the cursor. * {@description.close} */ private int peek() { int ch = temp[cursor]; if (has(COMMENTS)) ch = peekPastWhitespace(ch); return ch; } /** {@collect.stats} * {@description.open} * Read the next character, and advance the cursor by one. * {@description.close} */ private int read() { int ch = temp[cursor++]; if (has(COMMENTS)) ch = parsePastWhitespace(ch); return ch; } /** {@collect.stats} * {@description.open} * Read the next character, and advance the cursor by one, * ignoring the COMMENTS setting * {@description.close} */ private int readEscaped() { int ch = temp[cursor++]; return ch; } /** {@collect.stats} * {@description.open} * Advance the cursor by one, and peek the next character. * {@description.close} */ private int next() { int ch = temp[++cursor]; if (has(COMMENTS)) ch = peekPastWhitespace(ch); return ch; } /** {@collect.stats} * {@description.open} * Advance the cursor by one, and peek the next character, * ignoring the COMMENTS setting * {@description.close} */ private int nextEscaped() { int ch = temp[++cursor]; return ch; } /** {@collect.stats} * {@description.open} * If in xmode peek past whitespace and comments. * {@description.close} */ private int peekPastWhitespace(int ch) { while (ASCII.isSpace(ch) || ch == '#') { while (ASCII.isSpace(ch)) ch = temp[++cursor]; if (ch == '#') { ch = peekPastLine(); } } return ch; } /** {@collect.stats} * {@description.open} * If in xmode parse past whitespace and comments. * {@description.close} */ private int parsePastWhitespace(int ch) { while (ASCII.isSpace(ch) || ch == '#') { while (ASCII.isSpace(ch)) ch = temp[cursor++]; if (ch == '#') ch = parsePastLine(); } return ch; } /** {@collect.stats} * {@description.open} * xmode parse past comment to end of line. * {@description.close} */ private int parsePastLine() { int ch = temp[cursor++]; while (ch != 0 && !isLineSeparator(ch)) ch = temp[cursor++]; return ch; } /** {@collect.stats} * {@description.open} * xmode peek past comment to end of line. * {@description.close} */ private int peekPastLine() { int ch = temp[++cursor]; while (ch != 0 && !isLineSeparator(ch)) ch = temp[++cursor]; return ch; } /** {@collect.stats} * {@description.open} * Determines if character is a line separator in the current mode * {@description.close} */ private boolean isLineSeparator(int ch) { if (has(UNIX_LINES)) { return ch == '\n'; } else { return (ch == '\n' || ch == '\r' || (ch|1) == '\u2029' || ch == '\u0085'); } } /** {@collect.stats} * {@description.open} * Read the character after the next one, and advance the cursor by two. * {@description.close} */ private int skip() { int i = cursor; int ch = temp[i+1]; cursor = i + 2; return ch; } /** {@collect.stats} * {@description.open} * Unread one next character, and retreat cursor by one. * {@description.close} */ private void unread() { cursor--; } /** {@collect.stats} * {@description.open} * Internal method used for handling all syntax errors. The pattern is * displayed with a pointer to aid in locating the syntax error. * {@description.close} */ private PatternSyntaxException error(String s) { return new PatternSyntaxException(s, normalizedPattern, cursor - 1); } /** {@collect.stats} * {@description.open} * Determines if there is any supplementary character or unpaired * surrogate in the specified range. * {@description.close} */ private boolean findSupplementary(int start, int end) { for (int i = start; i < end; i++) { if (isSupplementary(temp[i])) return true; } return false; } /** {@collect.stats} * {@description.open} * Determines if the specified code point is a supplementary * character or unpaired surrogate. * {@description.close} */ private static final boolean isSupplementary(int ch) { return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT || isSurrogate(ch); } /** {@collect.stats} * {@description.open} * The following methods handle the main parsing. They are sorted * according to their precedence order, the lowest one first. * {@description.close} */ /** {@collect.stats} * {@description.open} * The expression is parsed with branch nodes added for alternations. * This may be called recursively to parse sub expressions that may * contain alternations. * {@description.close} */ private Node expr(Node end) { Node prev = null; Node firstTail = null; Node branchConn = null; for (;;) { Node node = sequence(end); Node nodeTail = root; //double return if (prev == null) { prev = node; firstTail = nodeTail; } else { // Branch if (branchConn == null) { branchConn = new BranchConn(); branchConn.next = end; } if (node == end) { // if the node returned from sequence() is "end" // we have an empty expr, set a null atom into // the branch to indicate to go "next" directly. node = null; } else { // the "tail.next" of each atom goes to branchConn nodeTail.next = branchConn; } if (prev instanceof Branch) { ((Branch)prev).add(node); } else { if (prev == end) { prev = null; } else { // replace the "end" with "branchConn" at its tail.next // when put the "prev" into the branch as the first atom. firstTail.next = branchConn; } prev = new Branch(prev, node, branchConn); } } if (peek() != '|') { return prev; } next(); } } /** {@collect.stats} * {@description.open} * Parsing of sequences between alternations. * {@description.close} */ private Node sequence(Node end) { Node head = null; Node tail = null; Node node = null; LOOP: for (;;) { int ch = peek(); switch (ch) { case '(': // Because group handles its own closure, // we need to treat it differently node = group0(); // Check for comment or flag group if (node == null) continue; if (head == null) head = node; else tail.next = node; // Double return: Tail was returned in root tail = root; continue; case '[': node = clazz(true); break; case '\\': ch = nextEscaped(); if (ch == 'p' || ch == 'P') { boolean oneLetter = true; boolean comp = (ch == 'P'); ch = next(); // Consume { if present if (ch != '{') { unread(); } else { oneLetter = false; } node = family(oneLetter).maybeComplement(comp); } else { unread(); node = atom(); } break; case '^': next(); if (has(MULTILINE)) { if (has(UNIX_LINES)) node = new UnixCaret(); else node = new Caret(); } else { node = new Begin(); } break; case '$': next(); if (has(UNIX_LINES)) node = new UnixDollar(has(MULTILINE)); else node = new Dollar(has(MULTILINE)); break; case '.': next(); if (has(DOTALL)) { node = new All(); } else { if (has(UNIX_LINES)) node = new UnixDot(); else { node = new Dot(); } } break; case '|': case ')': break LOOP; case ']': // Now interpreting dangling ] and } as literals case '}': node = atom(); break; case '?': case '*': case '+': next(); throw error("Dangling meta character '" + ((char)ch) + "'"); case 0: if (cursor >= patternLength) { break LOOP; } // Fall through default: node = atom(); break; } node = closure(node); if (head == null) { head = tail = node; } else { tail.next = node; tail = node; } } if (head == null) { return end; } tail.next = end; root = tail; //double return return head; } /** {@collect.stats} * {@description.open} * Parse and add a new Single or Slice. * {@description.close} */ private Node atom() { int first = 0; int prev = -1; boolean hasSupplementary = false; int ch = peek(); for (;;) { switch (ch) { case '*': case '+': case '?': case '{': if (first > 1) { cursor = prev; // Unwind one character first--; } break; case '$': case '.': case '^': case '(': case '[': case '|': case ')': break; case '\\': ch = nextEscaped(); if (ch == 'p' || ch == 'P') { // Property if (first > 0) { // Slice is waiting; handle it first unread(); break; } else { // No slice; just return the family node boolean comp = (ch == 'P'); boolean oneLetter = true; ch = next(); // Consume { if present if (ch != '{') unread(); else oneLetter = false; return family(oneLetter).maybeComplement(comp); } } unread(); prev = cursor; ch = escape(false, first == 0); if (ch >= 0) { append(ch, first); first++; if (isSupplementary(ch)) { hasSupplementary = true; } ch = peek(); continue; } else if (first == 0) { return root; } // Unwind meta escape sequence cursor = prev; break; case 0: if (cursor >= patternLength) { break; } // Fall through default: prev = cursor; append(ch, first); first++; if (isSupplementary(ch)) { hasSupplementary = true; } ch = next(); continue; } break; } if (first == 1) { return newSingle(buffer[0]); } else { return newSlice(buffer, first, hasSupplementary); } } private void append(int ch, int len) { if (len >= buffer.length) { int[] tmp = new int[len+len]; System.arraycopy(buffer, 0, tmp, 0, len); buffer = tmp; } buffer[len] = ch; } /** {@collect.stats} * {@description.open} * Parses a backref greedily, taking as many numbers as it * can. The first digit is always treated as a backref, but * multi digit numbers are only treated as a backref if at * least that many backrefs exist at this point in the regex. * {@description.close} */ private Node ref(int refNum) { boolean done = false; while(!done) { int ch = peek(); switch(ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': int newRefNum = (refNum * 10) + (ch - '0'); // Add another number if it doesn't make a group // that doesn't exist if (capturingGroupCount - 1 < newRefNum) { done = true; break; } refNum = newRefNum; read(); break; default: done = true; break; } } if (has(CASE_INSENSITIVE)) return new CIBackRef(refNum, has(UNICODE_CASE)); else return new BackRef(refNum); } /** {@collect.stats} * {@description.open} * Parses an escape sequence to determine the actual value that needs * to be matched. * If -1 is returned and create was true a new object was added to the tree * to handle the escape sequence. * If the returned value is greater than zero, it is the value that * matches the escape sequence. * {@description.close} */ private int escape(boolean inclass, boolean create) { int ch = skip(); switch (ch) { case '0': return o(); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (inclass) break; if (create) { root = ref((ch - '0')); } return -1; case 'A': if (inclass) break; if (create) root = new Begin(); return -1; case 'B': if (inclass) break; if (create) root = new Bound(Bound.NONE); return -1; case 'C': break; case 'D': if (create) root = new Ctype(ASCII.DIGIT).complement(); return -1; case 'E': case 'F': break; case 'G': if (inclass) break; if (create) root = new LastMatch(); return -1; case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': break; case 'S': if (create) root = new Ctype(ASCII.SPACE).complement(); return -1; case 'T': case 'U': case 'V': break; case 'W': if (create) root = new Ctype(ASCII.WORD).complement(); return -1; case 'X': case 'Y': break; case 'Z': if (inclass) break; if (create) { if (has(UNIX_LINES)) root = new UnixDollar(false); else root = new Dollar(false); } return -1; case 'a': return '\007'; case 'b': if (inclass) break; if (create) root = new Bound(Bound.BOTH); return -1; case 'c': return c(); case 'd': if (create) root = new Ctype(ASCII.DIGIT); return -1; case 'e': return '\033'; case 'f': return '\f'; case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': break; case 'n': return '\n'; case 'o': case 'p': case 'q': break; case 'r': return '\r'; case 's': if (create) root = new Ctype(ASCII.SPACE); return -1; case 't': return '\t'; case 'u': return u(); case 'v': return '\013'; case 'w': if (create) root = new Ctype(ASCII.WORD); return -1; case 'x': return x(); case 'y': break; case 'z': if (inclass) break; if (create) root = new End(); return -1; default: return ch; } throw error("Illegal/unsupported escape sequence"); } /** {@collect.stats} * {@description.open} * Parse a character class, and return the node that matches it. * * Consumes a ] on the way out if consume is true. Usually consume * is true except for the case of [abc&&def] where def is a separate * right hand node with "understood" brackets. * {@description.close} */ private CharProperty clazz(boolean consume) { CharProperty prev = null; CharProperty node = null; BitClass bits = new BitClass(); boolean include = true; boolean firstInClass = true; int ch = next(); for (;;) { switch (ch) { case '^': // Negates if first char in a class, otherwise literal if (firstInClass) { if (temp[cursor-1] != '[') break; ch = next(); include = !include; continue; } else { // ^ not first in class, treat as literal break; } case '[': firstInClass = false; node = clazz(true); if (prev == null) prev = node; else prev = union(prev, node); ch = peek(); continue; case '&': firstInClass = false; ch = next(); if (ch == '&') { ch = next(); CharProperty rightNode = null; while (ch != ']' && ch != '&') { if (ch == '[') { if (rightNode == null) rightNode = clazz(true); else rightNode = union(rightNode, clazz(true)); } else { // abc&&def unread(); rightNode = clazz(false); } ch = peek(); } if (rightNode != null) node = rightNode; if (prev == null) { if (rightNode == null) throw error("Bad class syntax"); else prev = rightNode; } else { prev = intersection(prev, node); } } else { // treat as a literal & unread(); break; } continue; case 0: firstInClass = false; if (cursor >= patternLength) throw error("Unclosed character class"); break; case ']': firstInClass = false; if (prev != null) { if (consume) next(); return prev; } break; default: firstInClass = false; break; } node = range(bits); if (include) { if (prev == null) { prev = node; } else { if (prev != node) prev = union(prev, node); } } else { if (prev == null) { prev = node.complement(); } else { if (prev != node) prev = setDifference(prev, node); } } ch = peek(); } } private CharProperty bitsOrSingle(BitClass bits, int ch) { /* Bits can only handle codepoints in [u+0000-u+00ff] range. Use "single" node instead of bits when dealing with unicode case folding for codepoints listed below. (1)Uppercase out of range: u+00ff, u+00b5 toUpperCase(u+00ff) -> u+0178 toUpperCase(u+00b5) -> u+039c (2)LatinSmallLetterLongS u+17f toUpperCase(u+017f) -> u+0053 (3)LatinSmallLetterDotlessI u+131 toUpperCase(u+0131) -> u+0049 (4)LatinCapitalLetterIWithDotAbove u+0130 toLowerCase(u+0130) -> u+0069 (5)KelvinSign u+212a toLowerCase(u+212a) ==> u+006B (6)AngstromSign u+212b toLowerCase(u+212b) ==> u+00e5 */ int d; if (ch < 256 && !(has(CASE_INSENSITIVE) && has(UNICODE_CASE) && (ch == 0xff || ch == 0xb5 || ch == 0x49 || ch == 0x69 || //I and i ch == 0x53 || ch == 0x73 || //S and s ch == 0x4b || ch == 0x6b || //K and k ch == 0xc5 || ch == 0xe5))) //A+ring return bits.add(ch, flags()); return newSingle(ch); } /** {@collect.stats} * {@description.open} * Parse a single character or a character range in a character class * and return its representative node. * {@description.close} */ private CharProperty range(BitClass bits) { int ch = peek(); if (ch == '\\') { ch = nextEscaped(); if (ch == 'p' || ch == 'P') { // A property boolean comp = (ch == 'P'); boolean oneLetter = true; // Consume { if present ch = next(); if (ch != '{') unread(); else oneLetter = false; return family(oneLetter).maybeComplement(comp); } else { // ordinary escape unread(); ch = escape(true, true); if (ch == -1) return (CharProperty) root; } } else { ch = single(); } if (ch >= 0) { if (peek() == '-') { int endRange = temp[cursor+1]; if (endRange == '[') { return bitsOrSingle(bits, ch); } if (endRange != ']') { next(); int m = single(); if (m < ch) throw error("Illegal character range"); if (has(CASE_INSENSITIVE)) return caseInsensitiveRangeFor(ch, m); else return rangeFor(ch, m); } } return bitsOrSingle(bits, ch); } throw error("Unexpected character '"+((char)ch)+"'"); } private int single() { int ch = peek(); switch (ch) { case '\\': return escape(true, false); default: next(); return ch; } } /** {@collect.stats} * {@description.open} * Parses a Unicode character family and returns its representative node. * {@description.close} */ private CharProperty family(boolean singleLetter) { next(); String name; if (singleLetter) { int c = temp[cursor]; if (!Character.isSupplementaryCodePoint(c)) { name = String.valueOf((char)c); } else { name = new String(temp, cursor, 1); } read(); } else { int i = cursor; mark('}'); while(read() != '}') { } mark('\000'); int j = cursor; if (j > patternLength) throw error("Unclosed character family"); if (i + 1 >= j) throw error("Empty character family"); name = new String(temp, i, j-i-1); } if (name.startsWith("In")) { return unicodeBlockPropertyFor(name.substring(2)); } else { if (name.startsWith("Is")) name = name.substring(2); return charPropertyNodeFor(name); } } /** {@collect.stats} * {@description.open} * Returns a CharProperty matching all characters in a UnicodeBlock. * {@description.close} */ private CharProperty unicodeBlockPropertyFor(String name) { final Character.UnicodeBlock block; try { block = Character.UnicodeBlock.forName(name); } catch (IllegalArgumentException iae) { throw error("Unknown character block name {" + name + "}"); } return new CharProperty() { boolean isSatisfiedBy(int ch) { return block == Character.UnicodeBlock.of(ch);}}; } /** {@collect.stats} * {@description.open} * Returns a CharProperty matching all characters in a named property. * {@description.close} */ private CharProperty charPropertyNodeFor(String name) { CharProperty p = CharPropertyNames.charPropertyFor(name); if (p == null) throw error("Unknown character property name {" + name + "}"); return p; } /** {@collect.stats} * {@description.open} * Parses a group and returns the head node of a set of nodes that process * the group. Sometimes a double return system is used where the tail is * returned in root. * {@description.close} */ private Node group0() { boolean capturingGroup = false; Node head = null; Node tail = null; int save = flags; root = null; int ch = next(); if (ch == '?') { ch = skip(); switch (ch) { case ':': // (?:xxx) pure group head = createGroup(true); tail = root; head.next = expr(tail); break; case '=': // (?=xxx) and (?!xxx) lookahead case '!': head = createGroup(true); tail = root; head.next = expr(tail); if (ch == '=') { head = tail = new Pos(head); } else { head = tail = new Neg(head); } break; case '>': // (?>xxx) independent group head = createGroup(true); tail = root; head.next = expr(tail); head = tail = new Ques(head, INDEPENDENT); break; case '<': // (?<xxx) look behind ch = read(); int start = cursor; head = createGroup(true); tail = root; head.next = expr(tail); tail.next = lookbehindEnd; TreeInfo info = new TreeInfo(); head.study(info); if (info.maxValid == false) { throw error("Look-behind group does not have " + "an obvious maximum length"); } boolean hasSupplementary = findSupplementary(start, patternLength); if (ch == '=') { head = tail = (hasSupplementary ? new BehindS(head, info.maxLength, info.minLength) : new Behind(head, info.maxLength, info.minLength)); } else if (ch == '!') { head = tail = (hasSupplementary ? new NotBehindS(head, info.maxLength, info.minLength) : new NotBehind(head, info.maxLength, info.minLength)); } else { throw error("Unknown look-behind group"); } break; case '$': case '@': throw error("Unknown group type"); default: // (?xxx:) inlined match flags unread(); addFlag(); ch = read(); if (ch == ')') { return null; // Inline modifier only } if (ch != ':') { throw error("Unknown inline modifier"); } head = createGroup(true); tail = root; head.next = expr(tail); break; } } else { // (xxx) a regular group capturingGroup = true; head = createGroup(false); tail = root; head.next = expr(tail); } accept(')', "Unclosed group"); flags = save; // Check for quantifiers Node node = closure(head); if (node == head) { // No closure root = tail; return node; // Dual return } if (head == tail) { // Zero length assertion root = node; return node; // Dual return } if (node instanceof Ques) { Ques ques = (Ques) node; if (ques.type == POSSESSIVE) { root = node; return node; } tail.next = new BranchConn(); tail = tail.next; if (ques.type == GREEDY) { head = new Branch(head, null, tail); } else { // Reluctant quantifier head = new Branch(null, head, tail); } root = tail; return head; } else if (node instanceof Curly) { Curly curly = (Curly) node; if (curly.type == POSSESSIVE) { root = node; return node; } // Discover if the group is deterministic TreeInfo info = new TreeInfo(); if (head.study(info)) { // Deterministic GroupTail temp = (GroupTail) tail; head = root = new GroupCurly(head.next, curly.cmin, curly.cmax, curly.type, ((GroupTail)tail).localIndex, ((GroupTail)tail).groupIndex, capturingGroup); return head; } else { // Non-deterministic int temp = ((GroupHead) head).localIndex; Loop loop; if (curly.type == GREEDY) loop = new Loop(this.localCount, temp); else // Reluctant Curly loop = new LazyLoop(this.localCount, temp); Prolog prolog = new Prolog(loop); this.localCount += 1; loop.cmin = curly.cmin; loop.cmax = curly.cmax; loop.body = head; tail.next = loop; root = loop; return prolog; // Dual return } } throw error("Internal logic error"); } /** {@collect.stats} * {@description.open} * Create group head and tail nodes using double return. If the group is * created with anonymous true then it is a pure group and should not * affect group counting. * {@description.close} */ private Node createGroup(boolean anonymous) { int localIndex = localCount++; int groupIndex = 0; if (!anonymous) groupIndex = capturingGroupCount++; GroupHead head = new GroupHead(localIndex); root = new GroupTail(localIndex, groupIndex); if (!anonymous && groupIndex < 10) groupNodes[groupIndex] = head; return head; } /** {@collect.stats} * {@description.open} * Parses inlined match flags and set them appropriately. * {@description.close} */ private void addFlag() { int ch = peek(); for (;;) { switch (ch) { case 'i': flags |= CASE_INSENSITIVE; break; case 'm': flags |= MULTILINE; break; case 's': flags |= DOTALL; break; case 'd': flags |= UNIX_LINES; break; case 'u': flags |= UNICODE_CASE; break; case 'c': flags |= CANON_EQ; break; case 'x': flags |= COMMENTS; break; case '-': // subFlag then fall through ch = next(); subFlag(); default: return; } ch = next(); } } /** {@collect.stats} * {@description.open} * Parses the second part of inlined match flags and turns off * flags appropriately. * {@description.close} */ private void subFlag() { int ch = peek(); for (;;) { switch (ch) { case 'i': flags &= ~CASE_INSENSITIVE; break; case 'm': flags &= ~MULTILINE; break; case 's': flags &= ~DOTALL; break; case 'd': flags &= ~UNIX_LINES; break; case 'u': flags &= ~UNICODE_CASE; break; case 'c': flags &= ~CANON_EQ; break; case 'x': flags &= ~COMMENTS; break; default: return; } ch = next(); } } static final int MAX_REPS = 0x7FFFFFFF; static final int GREEDY = 0; static final int LAZY = 1; static final int POSSESSIVE = 2; static final int INDEPENDENT = 3; /** {@collect.stats} * {@description.open} * Processes repetition. If the next character peeked is a quantifier * then new nodes must be appended to handle the repetition. * Prev could be a single or a group, so it could be a chain of nodes. * {@description.close} */ private Node closure(Node prev) { Node atom; int ch = peek(); switch (ch) { case '?': ch = next(); if (ch == '?') { next(); return new Ques(prev, LAZY); } else if (ch == '+') { next(); return new Ques(prev, POSSESSIVE); } return new Ques(prev, GREEDY); case '*': ch = next(); if (ch == '?') { next(); return new Curly(prev, 0, MAX_REPS, LAZY); } else if (ch == '+') { next(); return new Curly(prev, 0, MAX_REPS, POSSESSIVE); } return new Curly(prev, 0, MAX_REPS, GREEDY); case '+': ch = next(); if (ch == '?') { next(); return new Curly(prev, 1, MAX_REPS, LAZY); } else if (ch == '+') { next(); return new Curly(prev, 1, MAX_REPS, POSSESSIVE); } return new Curly(prev, 1, MAX_REPS, GREEDY); case '{': ch = temp[cursor+1]; if (ASCII.isDigit(ch)) { skip(); int cmin = 0; do { cmin = cmin * 10 + (ch - '0'); } while (ASCII.isDigit(ch = read())); int cmax = cmin; if (ch == ',') { ch = read(); cmax = MAX_REPS; if (ch != '}') { cmax = 0; while (ASCII.isDigit(ch)) { cmax = cmax * 10 + (ch - '0'); ch = read(); } } } if (ch != '}') throw error("Unclosed counted closure"); if (((cmin) | (cmax) | (cmax - cmin)) < 0) throw error("Illegal repetition range"); Curly curly; ch = peek(); if (ch == '?') { next(); curly = new Curly(prev, cmin, cmax, LAZY); } else if (ch == '+') { next(); curly = new Curly(prev, cmin, cmax, POSSESSIVE); } else { curly = new Curly(prev, cmin, cmax, GREEDY); } return curly; } else { throw error("Illegal repetition"); } default: return prev; } } /** {@collect.stats} * {@description.open} * Utility method for parsing control escape sequences. * {@description.close} */ private int c() { if (cursor < patternLength) { return read() ^ 64; } throw error("Illegal control escape sequence"); } /** {@collect.stats} * {@description.open} * Utility method for parsing octal escape sequences. * {@description.close} */ private int o() { int n = read(); if (((n-'0')|('7'-n)) >= 0) { int m = read(); if (((m-'0')|('7'-m)) >= 0) { int o = read(); if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) { return (n - '0') * 64 + (m - '0') * 8 + (o - '0'); } unread(); return (n - '0') * 8 + (m - '0'); } unread(); return (n - '0'); } throw error("Illegal octal escape sequence"); } /** {@collect.stats} * {@description.open} * Utility method for parsing hexadecimal escape sequences. * {@description.close} */ private int x() { int n = read(); if (ASCII.isHexDigit(n)) { int m = read(); if (ASCII.isHexDigit(m)) { return ASCII.toDigit(n) * 16 + ASCII.toDigit(m); } } throw error("Illegal hexadecimal escape sequence"); } /** {@collect.stats} * {@description.open} * Utility method for parsing unicode escape sequences. * {@description.close} */ private int u() { int n = 0; for (int i = 0; i < 4; i++) { int ch = read(); if (!ASCII.isHexDigit(ch)) { throw error("Illegal Unicode escape sequence"); } n = n * 16 + ASCII.toDigit(ch); } return n; } // // Utility methods for code point support // /** {@collect.stats} * {@description.open} * Tests a surrogate value. * {@description.close} */ private static final boolean isSurrogate(int c) { return c >= Character.MIN_HIGH_SURROGATE && c <= Character.MAX_LOW_SURROGATE; } private static final int countChars(CharSequence seq, int index, int lengthInCodePoints) { // optimization if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) { assert (index >= 0 && index < seq.length()); return 1; } int length = seq.length(); int x = index; if (lengthInCodePoints >= 0) { assert (index >= 0 && index < length); for (int i = 0; x < length && i < lengthInCodePoints; i++) { if (Character.isHighSurrogate(seq.charAt(x++))) { if (x < length && Character.isLowSurrogate(seq.charAt(x))) { x++; } } } return x - index; } assert (index >= 0 && index <= length); if (index == 0) { return 0; } int len = -lengthInCodePoints; for (int i = 0; x > 0 && i < len; i++) { if (Character.isLowSurrogate(seq.charAt(--x))) { if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) { x--; } } } return index - x; } private static final int countCodePoints(CharSequence seq) { int length = seq.length(); int n = 0; for (int i = 0; i < length; ) { n++; if (Character.isHighSurrogate(seq.charAt(i++))) { if (i < length && Character.isLowSurrogate(seq.charAt(i))) { i++; } } } return n; } /** {@collect.stats} * {@description.open} * Creates a bit vector for matching Latin-1 values. A normal BitClass * never matches values above Latin-1, and a complemented BitClass always * matches values above Latin-1. * {@description.close} */ private static final class BitClass extends BmpCharProperty { final boolean[] bits; BitClass() { bits = new boolean[256]; } private BitClass(boolean[] bits) { this.bits = bits; } BitClass add(int c, int flags) { assert c >= 0 && c <= 255; if ((flags & CASE_INSENSITIVE) != 0) { if (ASCII.isAscii(c)) { bits[ASCII.toUpper(c)] = true; bits[ASCII.toLower(c)] = true; } else if ((flags & UNICODE_CASE) != 0) { bits[Character.toLowerCase(c)] = true; bits[Character.toUpperCase(c)] = true; } } bits[c] = true; return this; } boolean isSatisfiedBy(int ch) { return ch < 256 && bits[ch]; } } /** {@collect.stats} * {@description.open} * Returns a suitably optimized, single character matcher. * {@description.close} */ private CharProperty newSingle(final int ch) { if (has(CASE_INSENSITIVE)) { int lower, upper; if (has(UNICODE_CASE)) { upper = Character.toUpperCase(ch); lower = Character.toLowerCase(upper); if (upper != lower) return new SingleU(lower); } else if (ASCII.isAscii(ch)) { lower = ASCII.toLower(ch); upper = ASCII.toUpper(ch); if (lower != upper) return new SingleI(lower, upper); } } if (isSupplementary(ch)) return new SingleS(ch); // Match a given Unicode character return new Single(ch); // Match a given BMP character } /** {@collect.stats} * {@description.open} * Utility method for creating a string slice matcher. * {@description.close} */ private Node newSlice(int[] buf, int count, boolean hasSupplementary) { int[] tmp = new int[count]; if (has(CASE_INSENSITIVE)) { if (has(UNICODE_CASE)) { for (int i = 0; i < count; i++) { tmp[i] = Character.toLowerCase( Character.toUpperCase(buf[i])); } return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp); } for (int i = 0; i < count; i++) { tmp[i] = ASCII.toLower(buf[i]); } return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp); } for (int i = 0; i < count; i++) { tmp[i] = buf[i]; } return hasSupplementary ? new SliceS(tmp) : new Slice(tmp); } /** {@collect.stats} * {@description.open} * The following classes are the building components of the object * tree that represents a compiled regular expression. The object tree * is made of individual elements that handle constructs in the Pattern. * Each type of object knows how to match its equivalent construct with * the match() method. * {@description.close} */ /** {@collect.stats} * {@description.open} * Base class for all node classes. Subclasses should override the match() * method as appropriate. This class is an accepting node, so its match() * always returns true. * {@description.close} */ static class Node extends Object { Node next; Node() { next = Pattern.accept; } /** {@collect.stats} * {@description.open} * This method implements the classic accept node. * {@description.close} */ boolean match(Matcher matcher, int i, CharSequence seq) { matcher.last = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; return true; } /** {@collect.stats} * {@description.open} * This method is good for all zero length assertions. * {@description.close} */ boolean study(TreeInfo info) { if (next != null) { return next.study(info); } else { return info.deterministic; } } } static class LastNode extends Node { /** {@collect.stats} * {@description.open} * This method implements the classic accept node with * the addition of a check to see if the match occurred * using all of the input. * {@description.close} */ boolean match(Matcher matcher, int i, CharSequence seq) { if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to) return false; matcher.last = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; return true; } } /** {@collect.stats} * {@description.open} * Used for REs that can start anywhere within the input string. * This basically tries to match repeatedly at each spot in the * input string, moving forward after each try. An anchored search * or a BnM will bypass this node completely. * {@description.close} */ static class Start extends Node { int minLength; Start(Node node) { this.next = node; TreeInfo info = new TreeInfo(); next.study(info); minLength = info.minLength; } boolean match(Matcher matcher, int i, CharSequence seq) { if (i > matcher.to - minLength) { matcher.hitEnd = true; return false; } boolean ret = false; int guard = matcher.to - minLength; for (; i <= guard; i++) { if (ret = next.match(matcher, i, seq)) break; if (i == guard) matcher.hitEnd = true; } if (ret) { matcher.first = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; } return ret; } boolean study(TreeInfo info) { next.study(info); info.maxValid = false; info.deterministic = false; return false; } } /* * StartS supports supplementary characters, including unpaired surrogates. */ static final class StartS extends Start { StartS(Node node) { super(node); } boolean match(Matcher matcher, int i, CharSequence seq) { if (i > matcher.to - minLength) { matcher.hitEnd = true; return false; } boolean ret = false; int guard = matcher.to - minLength; while (i <= guard) { if ((ret = next.match(matcher, i, seq)) || i == guard) break; // Optimization to move to the next character. This is // faster than countChars(seq, i, 1). if (Character.isHighSurrogate(seq.charAt(i++))) { if (i < seq.length() && Character.isLowSurrogate(seq.charAt(i))) { i++; } } if (i == guard) matcher.hitEnd = true; } if (ret) { matcher.first = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; } return ret; } } /** {@collect.stats} * {@description.open} * Node to anchor at the beginning of input. This object implements the * match for a \A sequence, and the caret anchor will use this if not in * multiline mode. * {@description.close} */ static final class Begin extends Node { boolean match(Matcher matcher, int i, CharSequence seq) { int fromIndex = (matcher.anchoringBounds) ? matcher.from : 0; if (i == fromIndex && next.match(matcher, i, seq)) { matcher.first = i; matcher.groups[0] = i; matcher.groups[1] = matcher.last; return true; } else { return false; } } } /** {@collect.stats} * {@description.open} * Node to anchor at the end of input. This is the absolute end, so this * should not match at the last newline before the end as $ will. * {@description.close} */ static final class End extends Node { boolean match(Matcher matcher, int i, CharSequence seq) { int endIndex = (matcher.anchoringBounds) ? matcher.to : matcher.getTextLength(); if (i == endIndex) { matcher.hitEnd = true; return next.match(matcher, i, seq); } return false; } } /** {@collect.stats} * {@description.open} * Node to anchor at the beginning of a line. This is essentially the * object to match for the multiline ^. * {@description.close} */ static final class Caret extends Node { boolean match(Matcher matcher, int i, CharSequence seq) { int startIndex = matcher.from; int endIndex = matcher.to; if (!matcher.anchoringBounds) { startIndex = 0; endIndex = matcher.getTextLength(); } // Perl does not match ^ at end of input even after newline if (i == endIndex) { matcher.hitEnd = true; return false; } if (i > startIndex) { char ch = seq.charAt(i-1); if (ch != '\n' && ch != '\r' && (ch|1) != '\u2029' && ch != '\u0085' ) { return false; } // Should treat /r/n as one newline if (ch == '\r' && seq.charAt(i) == '\n') return false; } return next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Node to anchor at the beginning of a line when in unixdot mode. * {@description.close} */ static final class UnixCaret extends Node { boolean match(Matcher matcher, int i, CharSequence seq) { int startIndex = matcher.from; int endIndex = matcher.to; if (!matcher.anchoringBounds) { startIndex = 0; endIndex = matcher.getTextLength(); } // Perl does not match ^ at end of input even after newline if (i == endIndex) { matcher.hitEnd = true; return false; } if (i > startIndex) { char ch = seq.charAt(i-1); if (ch != '\n') { return false; } } return next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Node to match the location where the last match ended. * This is used for the \G construct. * {@description.close} */ static final class LastMatch extends Node { boolean match(Matcher matcher, int i, CharSequence seq) { if (i != matcher.oldLast) return false; return next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Node to anchor at the end of a line or the end of input based on the * multiline mode. * * When not in multiline mode, the $ can only match at the very end * of the input, unless the input ends in a line terminator in which * it matches right before the last line terminator. * * Note that \r\n is considered an atomic line terminator. * * Like ^ the $ operator matches at a position, it does not match the * line terminators themselves. * {@description.close} */ static final class Dollar extends Node { boolean multiline; Dollar(boolean mul) { multiline = mul; } boolean match(Matcher matcher, int i, CharSequence seq) { int endIndex = (matcher.anchoringBounds) ? matcher.to : matcher.getTextLength(); if (!multiline) { if (i < endIndex - 2) return false; if (i == endIndex - 2) { char ch = seq.charAt(i); if (ch != '\r') return false; ch = seq.charAt(i + 1); if (ch != '\n') return false; } } // Matches before any line terminator; also matches at the // end of input // Before line terminator: // If multiline, we match here no matter what // If not multiline, fall through so that the end // is marked as hit; this must be a /r/n or a /n // at the very end so the end was hit; more input // could make this not match here if (i < endIndex) { char ch = seq.charAt(i); if (ch == '\n') { // No match between \r\n if (i > 0 && seq.charAt(i-1) == '\r') return false; if (multiline) return next.match(matcher, i, seq); } else if (ch == '\r' || ch == '\u0085' || (ch|1) == '\u2029') { if (multiline) return next.match(matcher, i, seq); } else { // No line terminator, no match return false; } } // Matched at current end so hit end matcher.hitEnd = true; // If a $ matches because of end of input, then more input // could cause it to fail! matcher.requireEnd = true; return next.match(matcher, i, seq); } boolean study(TreeInfo info) { next.study(info); return info.deterministic; } } /** {@collect.stats} * {@description.open} * Node to anchor at the end of a line or the end of input based on the * multiline mode when in unix lines mode. * {@description.close} */ static final class UnixDollar extends Node { boolean multiline; UnixDollar(boolean mul) { multiline = mul; } boolean match(Matcher matcher, int i, CharSequence seq) { int endIndex = (matcher.anchoringBounds) ? matcher.to : matcher.getTextLength(); if (i < endIndex) { char ch = seq.charAt(i); if (ch == '\n') { // If not multiline, then only possible to // match at very end or one before end if (multiline == false && i != endIndex - 1) return false; // If multiline return next.match without setting // matcher.hitEnd if (multiline) return next.match(matcher, i, seq); } else { return false; } } // Matching because at the end or 1 before the end; // more input could change this so set hitEnd matcher.hitEnd = true; // If a $ matches because of end of input, then more input // could cause it to fail! matcher.requireEnd = true; return next.match(matcher, i, seq); } boolean study(TreeInfo info) { next.study(info); return info.deterministic; } } /** {@collect.stats} * {@description.open} * Abstract node class to match one character satisfying some * boolean property. * {@description.close} */ private static abstract class CharProperty extends Node { abstract boolean isSatisfiedBy(int ch); CharProperty complement() { return new CharProperty() { boolean isSatisfiedBy(int ch) { return ! CharProperty.this.isSatisfiedBy(ch);}}; } CharProperty maybeComplement(boolean complement) { return complement ? complement() : this; } boolean match(Matcher matcher, int i, CharSequence seq) { if (i < matcher.to) { int ch = Character.codePointAt(seq, i); return isSatisfiedBy(ch) && next.match(matcher, i+Character.charCount(ch), seq); } else { matcher.hitEnd = true; return false; } } boolean study(TreeInfo info) { info.minLength++; info.maxLength++; return next.study(info); } } /** {@collect.stats} * {@description.open} * Optimized version of CharProperty that works only for * properties never satisfied by Supplementary characters. * {@description.close} */ private static abstract class BmpCharProperty extends CharProperty { boolean match(Matcher matcher, int i, CharSequence seq) { if (i < matcher.to) { return isSatisfiedBy(seq.charAt(i)) && next.match(matcher, i+1, seq); } else { matcher.hitEnd = true; return false; } } } /** {@collect.stats} * {@description.open} * Node class that matches a Supplementary Unicode character * {@description.close} */ static final class SingleS extends CharProperty { final int c; SingleS(int c) { this.c = c; } boolean isSatisfiedBy(int ch) { return ch == c; } } /** {@collect.stats} * {@description.open} * Optimization -- matches a given BMP character * {@description.close} */ static final class Single extends BmpCharProperty { final int c; Single(int c) { this.c = c; } boolean isSatisfiedBy(int ch) { return ch == c; } } /** {@collect.stats} * {@description.open} * Case insensitive matches a given BMP character * {@description.close} */ static final class SingleI extends BmpCharProperty { final int lower; final int upper; SingleI(int lower, int upper) { this.lower = lower; this.upper = upper; } boolean isSatisfiedBy(int ch) { return ch == lower || ch == upper; } } /** {@collect.stats} * {@description.open} * Unicode case insensitive matches a given Unicode character * {@description.close} */ static final class SingleU extends CharProperty { final int lower; SingleU(int lower) { this.lower = lower; } boolean isSatisfiedBy(int ch) { return lower == ch || lower == Character.toLowerCase(Character.toUpperCase(ch)); } } /** {@collect.stats} * {@description.open} * Node class that matches a Unicode category. * {@description.close} */ static final class Category extends CharProperty { final int typeMask; Category(int typeMask) { this.typeMask = typeMask; } boolean isSatisfiedBy(int ch) { return (typeMask & (1 << Character.getType(ch))) != 0; } } /** {@collect.stats} * {@description.open} * Node class that matches a POSIX type. * {@description.close} */ static final class Ctype extends BmpCharProperty { final int ctype; Ctype(int ctype) { this.ctype = ctype; } boolean isSatisfiedBy(int ch) { return ch < 128 && ASCII.isType(ch, ctype); } } /** {@collect.stats} * {@description.open} * Base class for all Slice nodes * {@description.close} */ static class SliceNode extends Node { int[] buffer; SliceNode(int[] buf) { buffer = buf; } boolean study(TreeInfo info) { info.minLength += buffer.length; info.maxLength += buffer.length; return next.study(info); } } /** {@collect.stats} * {@description.open} * Node class for a case sensitive/BMP-only sequence of literal * characters. * {@description.close} */ static final class Slice extends SliceNode { Slice(int[] buf) { super(buf); } boolean match(Matcher matcher, int i, CharSequence seq) { int[] buf = buffer; int len = buf.length; for (int j=0; j<len; j++) { if ((i+j) >= matcher.to) { matcher.hitEnd = true; return false; } if (buf[j] != seq.charAt(i+j)) return false; } return next.match(matcher, i+len, seq); } } /** {@collect.stats} * {@description.open} * Node class for a case_insensitive/BMP-only sequence of literal * characters. * {@description.close} */ static class SliceI extends SliceNode { SliceI(int[] buf) { super(buf); } boolean match(Matcher matcher, int i, CharSequence seq) { int[] buf = buffer; int len = buf.length; for (int j=0; j<len; j++) { if ((i+j) >= matcher.to) { matcher.hitEnd = true; return false; } int c = seq.charAt(i+j); if (buf[j] != c && buf[j] != ASCII.toLower(c)) return false; } return next.match(matcher, i+len, seq); } } /** {@collect.stats} * {@description.open} * Node class for a unicode_case_insensitive/BMP-only sequence of * literal characters. Uses unicode case folding. * {@description.close} */ static final class SliceU extends SliceNode { SliceU(int[] buf) { super(buf); } boolean match(Matcher matcher, int i, CharSequence seq) { int[] buf = buffer; int len = buf.length; for (int j=0; j<len; j++) { if ((i+j) >= matcher.to) { matcher.hitEnd = true; return false; } int c = seq.charAt(i+j); if (buf[j] != c && buf[j] != Character.toLowerCase(Character.toUpperCase(c))) return false; } return next.match(matcher, i+len, seq); } } /** {@collect.stats} * {@description.open} * Node class for a case sensitive sequence of literal characters * including supplementary characters. * {@description.close} */ static final class SliceS extends SliceNode { SliceS(int[] buf) { super(buf); } boolean match(Matcher matcher, int i, CharSequence seq) { int[] buf = buffer; int x = i; for (int j = 0; j < buf.length; j++) { if (x >= matcher.to) { matcher.hitEnd = true; return false; } int c = Character.codePointAt(seq, x); if (buf[j] != c) return false; x += Character.charCount(c); if (x > matcher.to) { matcher.hitEnd = true; return false; } } return next.match(matcher, x, seq); } } /** {@collect.stats} * {@description.open} * Node class for a case insensitive sequence of literal characters * including supplementary characters. * {@description.close} */ static class SliceIS extends SliceNode { SliceIS(int[] buf) { super(buf); } int toLower(int c) { return ASCII.toLower(c); } boolean match(Matcher matcher, int i, CharSequence seq) { int[] buf = buffer; int x = i; for (int j = 0; j < buf.length; j++) { if (x >= matcher.to) { matcher.hitEnd = true; return false; } int c = Character.codePointAt(seq, x); if (buf[j] != c && buf[j] != toLower(c)) return false; x += Character.charCount(c); if (x > matcher.to) { matcher.hitEnd = true; return false; } } return next.match(matcher, x, seq); } } /** {@collect.stats} * {@description.open} * Node class for a case insensitive sequence of literal characters. * Uses unicode case folding. * {@description.close} */ static final class SliceUS extends SliceIS { SliceUS(int[] buf) { super(buf); } int toLower(int c) { return Character.toLowerCase(Character.toUpperCase(c)); } } private static boolean inRange(int lower, int ch, int upper) { return lower <= ch && ch <= upper; } /** {@collect.stats} * {@description.open} * Returns node for matching characters within an explicit value range. * {@description.close} */ private static CharProperty rangeFor(final int lower, final int upper) { return new CharProperty() { boolean isSatisfiedBy(int ch) { return inRange(lower, ch, upper);}}; } /** {@collect.stats} * {@description.open} * Returns node for matching characters within an explicit value * range in a case insensitive manner. * {@description.close} */ private CharProperty caseInsensitiveRangeFor(final int lower, final int upper) { if (has(UNICODE_CASE)) return new CharProperty() { boolean isSatisfiedBy(int ch) { if (inRange(lower, ch, upper)) return true; int up = Character.toUpperCase(ch); return inRange(lower, up, upper) || inRange(lower, Character.toLowerCase(up), upper);}}; return new CharProperty() { boolean isSatisfiedBy(int ch) { return inRange(lower, ch, upper) || ASCII.isAscii(ch) && (inRange(lower, ASCII.toUpper(ch), upper) || inRange(lower, ASCII.toLower(ch), upper)); }}; } /** {@collect.stats} * {@description.open} * Implements the Unicode category ALL and the dot metacharacter when * in dotall mode. * {@description.close} */ static final class All extends CharProperty { boolean isSatisfiedBy(int ch) { return true; } } /** {@collect.stats} * {@description.open} * Node class for the dot metacharacter when dotall is not enabled. * {@description.close} */ static final class Dot extends CharProperty { boolean isSatisfiedBy(int ch) { return (ch != '\n' && ch != '\r' && (ch|1) != '\u2029' && ch != '\u0085'); } } /** {@collect.stats} * {@description.open} * Node class for the dot metacharacter when dotall is not enabled * but UNIX_LINES is enabled. * {@description.close} */ static final class UnixDot extends CharProperty { boolean isSatisfiedBy(int ch) { return ch != '\n'; } } /** {@collect.stats} * {@description.open} * The 0 or 1 quantifier. This one class implements all three types. * {@description.close} */ static final class Ques extends Node { Node atom; int type; Ques(Node node, int type) { this.atom = node; this.type = type; } boolean match(Matcher matcher, int i, CharSequence seq) { switch (type) { case GREEDY: return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq)) || next.match(matcher, i, seq); case LAZY: return next.match(matcher, i, seq) || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq)); case POSSESSIVE: if (atom.match(matcher, i, seq)) i = matcher.last; return next.match(matcher, i, seq); default: return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq); } } boolean study(TreeInfo info) { if (type != INDEPENDENT) { int minL = info.minLength; atom.study(info); info.minLength = minL; info.deterministic = false; return next.study(info); } else { atom.study(info); return next.study(info); } } } /** {@collect.stats} * {@description.open} * Handles the curly-brace style repetition with a specified minimum and * maximum occurrences. The * quantifier is handled as a special case. * This class handles the three types. * {@description.close} */ static final class Curly extends Node { Node atom; int type; int cmin; int cmax; Curly(Node node, int cmin, int cmax, int type) { this.atom = node; this.type = type; this.cmin = cmin; this.cmax = cmax; } boolean match(Matcher matcher, int i, CharSequence seq) { int j; for (j = 0; j < cmin; j++) { if (atom.match(matcher, i, seq)) { i = matcher.last; continue; } return false; } if (type == GREEDY) return match0(matcher, i, j, seq); else if (type == LAZY) return match1(matcher, i, j, seq); else return match2(matcher, i, j, seq); } // Greedy match. // i is the index to start matching at // j is the number of atoms that have matched boolean match0(Matcher matcher, int i, int j, CharSequence seq) { if (j >= cmax) { // We have matched the maximum... continue with the rest of // the regular expression return next.match(matcher, i, seq); } int backLimit = j; while (atom.match(matcher, i, seq)) { // k is the length of this match int k = matcher.last - i; if (k == 0) // Zero length match break; // Move up index and number matched i = matcher.last; j++; // We are greedy so match as many as we can while (j < cmax) { if (!atom.match(matcher, i, seq)) break; if (i + k != matcher.last) { if (match0(matcher, matcher.last, j+1, seq)) return true; break; } i += k; j++; } // Handle backing off if match fails while (j >= backLimit) { if (next.match(matcher, i, seq)) return true; i -= k; j--; } return false; } return next.match(matcher, i, seq); } // Reluctant match. At this point, the minimum has been satisfied. // i is the index to start matching at // j is the number of atoms that have matched boolean match1(Matcher matcher, int i, int j, CharSequence seq) { for (;;) { // Try finishing match without consuming any more if (next.match(matcher, i, seq)) return true; // At the maximum, no match found if (j >= cmax) return false; // Okay, must try one more atom if (!atom.match(matcher, i, seq)) return false; // If we haven't moved forward then must break out if (i == matcher.last) return false; // Move up index and number matched i = matcher.last; j++; } } boolean match2(Matcher matcher, int i, int j, CharSequence seq) { for (; j < cmax; j++) { if (!atom.match(matcher, i, seq)) break; if (i == matcher.last) break; i = matcher.last; } return next.match(matcher, i, seq); } boolean study(TreeInfo info) { // Save original info int minL = info.minLength; int maxL = info.maxLength; boolean maxV = info.maxValid; boolean detm = info.deterministic; info.reset(); atom.study(info); int temp = info.minLength * cmin + minL; if (temp < minL) { temp = 0xFFFFFFF; // arbitrary large number } info.minLength = temp; if (maxV & info.maxValid) { temp = info.maxLength * cmax + maxL; info.maxLength = temp; if (temp < maxL) { info.maxValid = false; } } else { info.maxValid = false; } if (info.deterministic && cmin == cmax) info.deterministic = detm; else info.deterministic = false; return next.study(info); } } /** {@collect.stats} * {@description.open} * Handles the curly-brace style repetition with a specified minimum and * maximum occurrences in deterministic cases. This is an iterative * optimization over the Prolog and Loop system which would handle this * in a recursive way. The * quantifier is handled as a special case. * If capture is true then this class saves group settings and ensures * that groups are unset when backing off of a group match. * {@description.close} */ static final class GroupCurly extends Node { Node atom; int type; int cmin; int cmax; int localIndex; int groupIndex; boolean capture; GroupCurly(Node node, int cmin, int cmax, int type, int local, int group, boolean capture) { this.atom = node; this.type = type; this.cmin = cmin; this.cmax = cmax; this.localIndex = local; this.groupIndex = group; this.capture = capture; } boolean match(Matcher matcher, int i, CharSequence seq) { int[] groups = matcher.groups; int[] locals = matcher.locals; int save0 = locals[localIndex]; int save1 = 0; int save2 = 0; if (capture) { save1 = groups[groupIndex]; save2 = groups[groupIndex+1]; } // Notify GroupTail there is no need to setup group info // because it will be set here locals[localIndex] = -1; boolean ret = true; for (int j = 0; j < cmin; j++) { if (atom.match(matcher, i, seq)) { if (capture) { groups[groupIndex] = i; groups[groupIndex+1] = matcher.last; } i = matcher.last; } else { ret = false; break; } } if (ret) { if (type == GREEDY) { ret = match0(matcher, i, cmin, seq); } else if (type == LAZY) { ret = match1(matcher, i, cmin, seq); } else { ret = match2(matcher, i, cmin, seq); } } if (!ret) { locals[localIndex] = save0; if (capture) { groups[groupIndex] = save1; groups[groupIndex+1] = save2; } } return ret; } // Aggressive group match boolean match0(Matcher matcher, int i, int j, CharSequence seq) { int[] groups = matcher.groups; int save0 = 0; int save1 = 0; if (capture) { save0 = groups[groupIndex]; save1 = groups[groupIndex+1]; } for (;;) { if (j >= cmax) break; if (!atom.match(matcher, i, seq)) break; int k = matcher.last - i; if (k <= 0) { if (capture) { groups[groupIndex] = i; groups[groupIndex+1] = i + k; } i = i + k; break; } for (;;) { if (capture) { groups[groupIndex] = i; groups[groupIndex+1] = i + k; } i = i + k; if (++j >= cmax) break; if (!atom.match(matcher, i, seq)) break; if (i + k != matcher.last) { if (match0(matcher, i, j, seq)) return true; break; } } while (j > cmin) { if (next.match(matcher, i, seq)) { if (capture) { groups[groupIndex+1] = i; groups[groupIndex] = i - k; } i = i - k; return true; } // backing off if (capture) { groups[groupIndex+1] = i; groups[groupIndex] = i - k; } i = i - k; j--; } break; } if (capture) { groups[groupIndex] = save0; groups[groupIndex+1] = save1; } return next.match(matcher, i, seq); } // Reluctant matching boolean match1(Matcher matcher, int i, int j, CharSequence seq) { for (;;) { if (next.match(matcher, i, seq)) return true; if (j >= cmax) return false; if (!atom.match(matcher, i, seq)) return false; if (i == matcher.last) return false; if (capture) { matcher.groups[groupIndex] = i; matcher.groups[groupIndex+1] = matcher.last; } i = matcher.last; j++; } } // Possessive matching boolean match2(Matcher matcher, int i, int j, CharSequence seq) { for (; j < cmax; j++) { if (!atom.match(matcher, i, seq)) { break; } if (capture) { matcher.groups[groupIndex] = i; matcher.groups[groupIndex+1] = matcher.last; } if (i == matcher.last) { break; } i = matcher.last; } return next.match(matcher, i, seq); } boolean study(TreeInfo info) { // Save original info int minL = info.minLength; int maxL = info.maxLength; boolean maxV = info.maxValid; boolean detm = info.deterministic; info.reset(); atom.study(info); int temp = info.minLength * cmin + minL; if (temp < minL) { temp = 0xFFFFFFF; // Arbitrary large number } info.minLength = temp; if (maxV & info.maxValid) { temp = info.maxLength * cmax + maxL; info.maxLength = temp; if (temp < maxL) { info.maxValid = false; } } else { info.maxValid = false; } if (info.deterministic && cmin == cmax) { info.deterministic = detm; } else { info.deterministic = false; } return next.study(info); } } /** {@collect.stats} * {@description.open} * A Guard node at the end of each atom node in a Branch. It * serves the purpose of chaining the "match" operation to * "next" but not the "study", so we can collect the TreeInfo * of each atom node without including the TreeInfo of the * "next". * {@description.close} */ static final class BranchConn extends Node { BranchConn() {}; boolean match(Matcher matcher, int i, CharSequence seq) { return next.match(matcher, i, seq); } boolean study(TreeInfo info) { return info.deterministic; } } /** {@collect.stats} * {@description.open} * Handles the branching of alternations. Note this is also used for * the ? quantifier to branch between the case where it matches once * and where it does not occur. * {@description.close} */ static final class Branch extends Node { Node[] atoms = new Node[2]; int size = 2; Node conn; Branch(Node first, Node second, Node branchConn) { conn = branchConn; atoms[0] = first; atoms[1] = second; } void add(Node node) { if (size >= atoms.length) { Node[] tmp = new Node[atoms.length*2]; System.arraycopy(atoms, 0, tmp, 0, atoms.length); atoms = tmp; } atoms[size++] = node; } boolean match(Matcher matcher, int i, CharSequence seq) { for (int n = 0; n < size; n++) { if (atoms[n] == null) { if (conn.next.match(matcher, i, seq)) return true; } else if (atoms[n].match(matcher, i, seq)) { return true; } } return false; } boolean study(TreeInfo info) { int minL = info.minLength; int maxL = info.maxLength; boolean maxV = info.maxValid; int minL2 = Integer.MAX_VALUE; //arbitrary large enough num int maxL2 = -1; for (int n = 0; n < size; n++) { info.reset(); if (atoms[n] != null) atoms[n].study(info); minL2 = Math.min(minL2, info.minLength); maxL2 = Math.max(maxL2, info.maxLength); maxV = (maxV & info.maxValid); } minL += minL2; maxL += maxL2; info.reset(); conn.next.study(info); info.minLength += minL; info.maxLength += maxL; info.maxValid &= maxV; info.deterministic = false; return false; } } /** {@collect.stats} * {@description.open} * The GroupHead saves the location where the group begins in the locals * and restores them when the match is done. * * The matchRef is used when a reference to this group is accessed later * in the expression. The locals will have a negative value in them to * indicate that we do not want to unset the group if the reference * doesn't match. * {@description.close} */ static final class GroupHead extends Node { int localIndex; GroupHead(int localCount) { localIndex = localCount; } boolean match(Matcher matcher, int i, CharSequence seq) { int save = matcher.locals[localIndex]; matcher.locals[localIndex] = i; boolean ret = next.match(matcher, i, seq); matcher.locals[localIndex] = save; return ret; } boolean matchRef(Matcher matcher, int i, CharSequence seq) { int save = matcher.locals[localIndex]; matcher.locals[localIndex] = ~i; // HACK boolean ret = next.match(matcher, i, seq); matcher.locals[localIndex] = save; return ret; } } /** {@collect.stats} * {@description.open} * Recursive reference to a group in the regular expression. It calls * matchRef because if the reference fails to match we would not unset * the group. * {@description.close} */ static final class GroupRef extends Node { GroupHead head; GroupRef(GroupHead head) { this.head = head; } boolean match(Matcher matcher, int i, CharSequence seq) { return head.matchRef(matcher, i, seq) && next.match(matcher, matcher.last, seq); } boolean study(TreeInfo info) { info.maxValid = false; info.deterministic = false; return next.study(info); } } /** {@collect.stats} * {@description.open} * The GroupTail handles the setting of group beginning and ending * locations when groups are successfully matched. It must also be able to * unset groups that have to be backed off of. * * The GroupTail node is also used when a previous group is referenced, * and in that case no group information needs to be set. * {@description.close} */ static final class GroupTail extends Node { int localIndex; int groupIndex; GroupTail(int localCount, int groupCount) { localIndex = localCount; groupIndex = groupCount + groupCount; } boolean match(Matcher matcher, int i, CharSequence seq) { int tmp = matcher.locals[localIndex]; if (tmp >= 0) { // This is the normal group case. // Save the group so we can unset it if it // backs off of a match. int groupStart = matcher.groups[groupIndex]; int groupEnd = matcher.groups[groupIndex+1]; matcher.groups[groupIndex] = tmp; matcher.groups[groupIndex+1] = i; if (next.match(matcher, i, seq)) { return true; } matcher.groups[groupIndex] = groupStart; matcher.groups[groupIndex+1] = groupEnd; return false; } else { // This is a group reference case. We don't need to save any // group info because it isn't really a group. matcher.last = i; return true; } } } /** {@collect.stats} * {@description.open} * This sets up a loop to handle a recursive quantifier structure. * {@description.close} */ static final class Prolog extends Node { Loop loop; Prolog(Loop loop) { this.loop = loop; } boolean match(Matcher matcher, int i, CharSequence seq) { return loop.matchInit(matcher, i, seq); } boolean study(TreeInfo info) { return loop.study(info); } } /** {@collect.stats} * {@description.open} * Handles the repetition count for a greedy Curly. The matchInit * is called from the Prolog to save the index of where the group * beginning is stored. A zero length group check occurs in the * normal match but is skipped in the matchInit. * {@description.close} */ static class Loop extends Node { Node body; int countIndex; // local count index in matcher locals int beginIndex; // group beginning index int cmin, cmax; Loop(int countIndex, int beginIndex) { this.countIndex = countIndex; this.beginIndex = beginIndex; } boolean match(Matcher matcher, int i, CharSequence seq) { // Avoid infinite loop in zero-length case. if (i > matcher.locals[beginIndex]) { int count = matcher.locals[countIndex]; // This block is for before we reach the minimum // iterations required for the loop to match if (count < cmin) { matcher.locals[countIndex] = count + 1; boolean b = body.match(matcher, i, seq); // If match failed we must backtrack, so // the loop count should NOT be incremented if (!b) matcher.locals[countIndex] = count; // Return success or failure since we are under // minimum return b; } // This block is for after we have the minimum // iterations required for the loop to match if (count < cmax) { matcher.locals[countIndex] = count + 1; boolean b = body.match(matcher, i, seq); // If match failed we must backtrack, so // the loop count should NOT be incremented if (!b) matcher.locals[countIndex] = count; else return true; } } return next.match(matcher, i, seq); } boolean matchInit(Matcher matcher, int i, CharSequence seq) { int save = matcher.locals[countIndex]; boolean ret = false; if (0 < cmin) { matcher.locals[countIndex] = 1; ret = body.match(matcher, i, seq); } else if (0 < cmax) { matcher.locals[countIndex] = 1; ret = body.match(matcher, i, seq); if (ret == false) ret = next.match(matcher, i, seq); } else { ret = next.match(matcher, i, seq); } matcher.locals[countIndex] = save; return ret; } boolean study(TreeInfo info) { info.maxValid = false; info.deterministic = false; return false; } } /** {@collect.stats} * {@description.open} * Handles the repetition count for a reluctant Curly. The matchInit * is called from the Prolog to save the index of where the group * beginning is stored. A zero length group check occurs in the * normal match but is skipped in the matchInit. * {@description.close} */ static final class LazyLoop extends Loop { LazyLoop(int countIndex, int beginIndex) { super(countIndex, beginIndex); } boolean match(Matcher matcher, int i, CharSequence seq) { // Check for zero length group if (i > matcher.locals[beginIndex]) { int count = matcher.locals[countIndex]; if (count < cmin) { matcher.locals[countIndex] = count + 1; boolean result = body.match(matcher, i, seq); // If match failed we must backtrack, so // the loop count should NOT be incremented if (!result) matcher.locals[countIndex] = count; return result; } if (next.match(matcher, i, seq)) return true; if (count < cmax) { matcher.locals[countIndex] = count + 1; boolean result = body.match(matcher, i, seq); // If match failed we must backtrack, so // the loop count should NOT be incremented if (!result) matcher.locals[countIndex] = count; return result; } return false; } return next.match(matcher, i, seq); } boolean matchInit(Matcher matcher, int i, CharSequence seq) { int save = matcher.locals[countIndex]; boolean ret = false; if (0 < cmin) { matcher.locals[countIndex] = 1; ret = body.match(matcher, i, seq); } else if (next.match(matcher, i, seq)) { ret = true; } else if (0 < cmax) { matcher.locals[countIndex] = 1; ret = body.match(matcher, i, seq); } matcher.locals[countIndex] = save; return ret; } boolean study(TreeInfo info) { info.maxValid = false; info.deterministic = false; return false; } } /** {@collect.stats} * {@description.open} * Refers to a group in the regular expression. Attempts to match * whatever the group referred to last matched. * {@description.close} */ static class BackRef extends Node { int groupIndex; BackRef(int groupCount) { super(); groupIndex = groupCount + groupCount; } boolean match(Matcher matcher, int i, CharSequence seq) { int j = matcher.groups[groupIndex]; int k = matcher.groups[groupIndex+1]; int groupSize = k - j; // If the referenced group didn't match, neither can this if (j < 0) return false; // If there isn't enough input left no match if (i + groupSize > matcher.to) { matcher.hitEnd = true; return false; } // Check each new char to make sure it matches what the group // referenced matched last time around for (int index=0; index<groupSize; index++) if (seq.charAt(i+index) != seq.charAt(j+index)) return false; return next.match(matcher, i+groupSize, seq); } boolean study(TreeInfo info) { info.maxValid = false; return next.study(info); } } static class CIBackRef extends Node { int groupIndex; boolean doUnicodeCase; CIBackRef(int groupCount, boolean doUnicodeCase) { super(); groupIndex = groupCount + groupCount; this.doUnicodeCase = doUnicodeCase; } boolean match(Matcher matcher, int i, CharSequence seq) { int j = matcher.groups[groupIndex]; int k = matcher.groups[groupIndex+1]; int groupSize = k - j; // If the referenced group didn't match, neither can this if (j < 0) return false; // If there isn't enough input left no match if (i + groupSize > matcher.to) { matcher.hitEnd = true; return false; } // Check each new char to make sure it matches what the group // referenced matched last time around int x = i; for (int index=0; index<groupSize; index++) { int c1 = Character.codePointAt(seq, x); int c2 = Character.codePointAt(seq, j); if (c1 != c2) { if (doUnicodeCase) { int cc1 = Character.toUpperCase(c1); int cc2 = Character.toUpperCase(c2); if (cc1 != cc2 && Character.toLowerCase(cc1) != Character.toLowerCase(cc2)) return false; } else { if (ASCII.toLower(c1) != ASCII.toLower(c2)) return false; } } x += Character.charCount(c1); j += Character.charCount(c2); } return next.match(matcher, i+groupSize, seq); } boolean study(TreeInfo info) { info.maxValid = false; return next.study(info); } } /** {@collect.stats} * {@description.open} * Searches until the next instance of its atom. This is useful for * finding the atom efficiently without passing an instance of it * (greedy problem) and without a lot of wasted search time (reluctant * problem). * {@description.close} */ static final class First extends Node { Node atom; First(Node node) { this.atom = BnM.optimize(node); } boolean match(Matcher matcher, int i, CharSequence seq) { if (atom instanceof BnM) { return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq); } for (;;) { if (i > matcher.to) { matcher.hitEnd = true; return false; } if (atom.match(matcher, i, seq)) { return next.match(matcher, matcher.last, seq); } i += countChars(seq, i, 1); matcher.first++; } } boolean study(TreeInfo info) { atom.study(info); info.maxValid = false; info.deterministic = false; return next.study(info); } } static final class Conditional extends Node { Node cond, yes, not; Conditional(Node cond, Node yes, Node not) { this.cond = cond; this.yes = yes; this.not = not; } boolean match(Matcher matcher, int i, CharSequence seq) { if (cond.match(matcher, i, seq)) { return yes.match(matcher, i, seq); } else { return not.match(matcher, i, seq); } } boolean study(TreeInfo info) { int minL = info.minLength; int maxL = info.maxLength; boolean maxV = info.maxValid; info.reset(); yes.study(info); int minL2 = info.minLength; int maxL2 = info.maxLength; boolean maxV2 = info.maxValid; info.reset(); not.study(info); info.minLength = minL + Math.min(minL2, info.minLength); info.maxLength = maxL + Math.max(maxL2, info.maxLength); info.maxValid = (maxV & maxV2 & info.maxValid); info.deterministic = false; return next.study(info); } } /** {@collect.stats} * {@description.open} * Zero width positive lookahead. * {@description.close} */ static final class Pos extends Node { Node cond; Pos(Node cond) { this.cond = cond; } boolean match(Matcher matcher, int i, CharSequence seq) { int savedTo = matcher.to; boolean conditionMatched = false; // Relax transparent region boundaries for lookahead if (matcher.transparentBounds) matcher.to = matcher.getTextLength(); try { conditionMatched = cond.match(matcher, i, seq); } finally { // Reinstate region boundaries matcher.to = savedTo; } return conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Zero width negative lookahead. * {@description.close} */ static final class Neg extends Node { Node cond; Neg(Node cond) { this.cond = cond; } boolean match(Matcher matcher, int i, CharSequence seq) { int savedTo = matcher.to; boolean conditionMatched = false; // Relax transparent region boundaries for lookahead if (matcher.transparentBounds) matcher.to = matcher.getTextLength(); try { if (i < matcher.to) { conditionMatched = !cond.match(matcher, i, seq); } else { // If a negative lookahead succeeds then more input // could cause it to fail! matcher.requireEnd = true; conditionMatched = !cond.match(matcher, i, seq); } } finally { // Reinstate region boundaries matcher.to = savedTo; } return conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * For use with lookbehinds; matches the position where the lookbehind * was encountered. * {@description.close} */ static Node lookbehindEnd = new Node() { boolean match(Matcher matcher, int i, CharSequence seq) { return i == matcher.lookbehindTo; } }; /** {@collect.stats} * {@description.open} * Zero width positive lookbehind. * {@description.close} */ static class Behind extends Node { Node cond; int rmax, rmin; Behind(Node cond, int rmax, int rmin) { this.cond = cond; this.rmax = rmax; this.rmin = rmin; } boolean match(Matcher matcher, int i, CharSequence seq) { int savedFrom = matcher.from; boolean conditionMatched = false; int startIndex = (!matcher.transparentBounds) ? matcher.from : 0; int from = Math.max(i - rmax, startIndex); // Set end boundary int savedLBT = matcher.lookbehindTo; matcher.lookbehindTo = i; // Relax transparent region boundaries for lookbehind if (matcher.transparentBounds) matcher.from = 0; for (int j = i - rmin; !conditionMatched && j >= from; j--) { conditionMatched = cond.match(matcher, j, seq); } matcher.from = savedFrom; matcher.lookbehindTo = savedLBT; return conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Zero width positive lookbehind, including supplementary * characters or unpaired surrogates. * {@description.close} */ static final class BehindS extends Behind { BehindS(Node cond, int rmax, int rmin) { super(cond, rmax, rmin); } boolean match(Matcher matcher, int i, CharSequence seq) { int rmaxChars = countChars(seq, i, -rmax); int rminChars = countChars(seq, i, -rmin); int savedFrom = matcher.from; int startIndex = (!matcher.transparentBounds) ? matcher.from : 0; boolean conditionMatched = false; int from = Math.max(i - rmaxChars, startIndex); // Set end boundary int savedLBT = matcher.lookbehindTo; matcher.lookbehindTo = i; // Relax transparent region boundaries for lookbehind if (matcher.transparentBounds) matcher.from = 0; for (int j = i - rminChars; !conditionMatched && j >= from; j -= j>from ? countChars(seq, j, -1) : 1) { conditionMatched = cond.match(matcher, j, seq); } matcher.from = savedFrom; matcher.lookbehindTo = savedLBT; return conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Zero width negative lookbehind. * {@description.close} */ static class NotBehind extends Node { Node cond; int rmax, rmin; NotBehind(Node cond, int rmax, int rmin) { this.cond = cond; this.rmax = rmax; this.rmin = rmin; } boolean match(Matcher matcher, int i, CharSequence seq) { int savedLBT = matcher.lookbehindTo; int savedFrom = matcher.from; boolean conditionMatched = false; int startIndex = (!matcher.transparentBounds) ? matcher.from : 0; int from = Math.max(i - rmax, startIndex); matcher.lookbehindTo = i; // Relax transparent region boundaries for lookbehind if (matcher.transparentBounds) matcher.from = 0; for (int j = i - rmin; !conditionMatched && j >= from; j--) { conditionMatched = cond.match(matcher, j, seq); } // Reinstate region boundaries matcher.from = savedFrom; matcher.lookbehindTo = savedLBT; return !conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Zero width negative lookbehind, including supplementary * characters or unpaired surrogates. * {@description.close} */ static final class NotBehindS extends NotBehind { NotBehindS(Node cond, int rmax, int rmin) { super(cond, rmax, rmin); } boolean match(Matcher matcher, int i, CharSequence seq) { int rmaxChars = countChars(seq, i, -rmax); int rminChars = countChars(seq, i, -rmin); int savedFrom = matcher.from; int savedLBT = matcher.lookbehindTo; boolean conditionMatched = false; int startIndex = (!matcher.transparentBounds) ? matcher.from : 0; int from = Math.max(i - rmaxChars, startIndex); matcher.lookbehindTo = i; // Relax transparent region boundaries for lookbehind if (matcher.transparentBounds) matcher.from = 0; for (int j = i - rminChars; !conditionMatched && j >= from; j -= j>from ? countChars(seq, j, -1) : 1) { conditionMatched = cond.match(matcher, j, seq); } //Reinstate region boundaries matcher.from = savedFrom; matcher.lookbehindTo = savedLBT; return !conditionMatched && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Returns the set union of two CharProperty nodes. * {@description.close} */ private static CharProperty union(final CharProperty lhs, final CharProperty rhs) { return new CharProperty() { boolean isSatisfiedBy(int ch) { return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}}; } /** {@collect.stats} * {@description.open} * Returns the set intersection of two CharProperty nodes. * {@description.close} */ private static CharProperty intersection(final CharProperty lhs, final CharProperty rhs) { return new CharProperty() { boolean isSatisfiedBy(int ch) { return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}}; } /** {@collect.stats} * {@description.open} * Returns the set difference of two CharProperty nodes. * {@description.close} */ private static CharProperty setDifference(final CharProperty lhs, final CharProperty rhs) { return new CharProperty() { boolean isSatisfiedBy(int ch) { return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}}; } /** {@collect.stats} * {@description.open} * Handles word boundaries. Includes a field to allow this one class to * deal with the different types of word boundaries we can match. The word * characters include underscores, letters, and digits. Non spacing marks * can are also part of a word if they have a base character, otherwise * they are ignored for purposes of finding word boundaries. * {@description.close} */ static final class Bound extends Node { static int LEFT = 0x1; static int RIGHT= 0x2; static int BOTH = 0x3; static int NONE = 0x4; int type; Bound(int n) { type = n; } int check(Matcher matcher, int i, CharSequence seq) { int ch; boolean left = false; int startIndex = matcher.from; int endIndex = matcher.to; if (matcher.transparentBounds) { startIndex = 0; endIndex = matcher.getTextLength(); } if (i > startIndex) { ch = Character.codePointBefore(seq, i); left = (ch == '_' || Character.isLetterOrDigit(ch) || ((Character.getType(ch) == Character.NON_SPACING_MARK) && hasBaseCharacter(matcher, i-1, seq))); } boolean right = false; if (i < endIndex) { ch = Character.codePointAt(seq, i); right = (ch == '_' || Character.isLetterOrDigit(ch) || ((Character.getType(ch) == Character.NON_SPACING_MARK) && hasBaseCharacter(matcher, i, seq))); } else { // Tried to access char past the end matcher.hitEnd = true; // The addition of another char could wreck a boundary matcher.requireEnd = true; } return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE); } boolean match(Matcher matcher, int i, CharSequence seq) { return (check(matcher, i, seq) & type) > 0 && next.match(matcher, i, seq); } } /** {@collect.stats} * {@description.open} * Non spacing marks only count as word characters in bounds calculations * if they have a base character. * {@description.close} */ private static boolean hasBaseCharacter(Matcher matcher, int i, CharSequence seq) { int start = (!matcher.transparentBounds) ? matcher.from : 0; for (int x=i; x >= start; x--) { int ch = Character.codePointAt(seq, x); if (Character.isLetterOrDigit(ch)) return true; if (Character.getType(ch) == Character.NON_SPACING_MARK) continue; return false; } return false; } /** {@collect.stats} * {@description.open} * Attempts to match a slice in the input using the Boyer-Moore string * matching algorithm. The algorithm is based on the idea that the * pattern can be shifted farther ahead in the search text if it is * matched right to left. * <p> * The pattern is compared to the input one character at a time, from * the rightmost character in the pattern to the left. If the characters * all match the pattern has been found. If a character does not match, * the pattern is shifted right a distance that is the maximum of two * functions, the bad character shift and the good suffix shift. This * shift moves the attempted match position through the input more * quickly than a naive one position at a time check. * <p> * The bad character shift is based on the character from the text that * did not match. If the character does not appear in the pattern, the * pattern can be shifted completely beyond the bad character. If the * character does occur in the pattern, the pattern can be shifted to * line the pattern up with the next occurrence of that character. * <p> * The good suffix shift is based on the idea that some subset on the right * side of the pattern has matched. When a bad character is found, the * pattern can be shifted right by the pattern length if the subset does * not occur again in pattern, or by the amount of distance to the * next occurrence of the subset in the pattern. * * Boyer-Moore search methods adapted from code by Amy Yu. * {@description.close} */ static class BnM extends Node { int[] buffer; int[] lastOcc; int[] optoSft; /** {@collect.stats} * {@description.open} * Pre calculates arrays needed to generate the bad character * shift and the good suffix shift. Only the last seven bits * are used to see if chars match; This keeps the tables small * and covers the heavily used ASCII range, but occasionally * results in an aliased match for the bad character shift. * {@description.close} */ static Node optimize(Node node) { if (!(node instanceof Slice)) { return node; } int[] src = ((Slice) node).buffer; int patternLength = src.length; // The BM algorithm requires a bit of overhead; // If the pattern is short don't use it, since // a shift larger than the pattern length cannot // be used anyway. if (patternLength < 4) { return node; } int i, j, k; int[] lastOcc = new int[128]; int[] optoSft = new int[patternLength]; // Precalculate part of the bad character shift // It is a table for where in the pattern each // lower 7-bit value occurs for (i = 0; i < patternLength; i++) { lastOcc[src[i]&0x7F] = i + 1; } // Precalculate the good suffix shift // i is the shift amount being considered NEXT: for (i = patternLength; i > 0; i--) { // j is the beginning index of suffix being considered for (j = patternLength - 1; j >= i; j--) { // Testing for good suffix if (src[j] == src[j-i]) { // src[j..len] is a good suffix optoSft[j-1] = i; } else { // No match. The array has already been // filled up with correct values before. continue NEXT; } } // This fills up the remaining of optoSft // any suffix can not have larger shift amount // then its sub-suffix. Why??? while (j > 0) { optoSft[--j] = i; } } // Set the guard value because of unicode compression optoSft[patternLength-1] = 1; if (node instanceof SliceS) return new BnMS(src, lastOcc, optoSft, node.next); return new BnM(src, lastOcc, optoSft, node.next); } BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) { this.buffer = src; this.lastOcc = lastOcc; this.optoSft = optoSft; this.next = next; } boolean match(Matcher matcher, int i, CharSequence seq) { int[] src = buffer; int patternLength = src.length; int last = matcher.to - patternLength; // Loop over all possible match positions in text NEXT: while (i <= last) { // Loop over pattern from right to left for (int j = patternLength - 1; j >= 0; j--) { int ch = seq.charAt(i+j); if (ch != src[j]) { // Shift search to the right by the maximum of the // bad character shift and the good suffix shift i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]); continue NEXT; } } // Entire pattern matched starting at i matcher.first = i; boolean ret = next.match(matcher, i + patternLength, seq); if (ret) { matcher.first = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; return true; } i++; } // BnM is only used as the leading node in the unanchored case, // and it replaced its Start() which always searches to the end // if it doesn't find what it's looking for, so hitEnd is true. matcher.hitEnd = true; return false; } boolean study(TreeInfo info) { info.minLength += buffer.length; info.maxValid = false; return next.study(info); } } /** {@collect.stats} * {@description.open} * Supplementary support version of BnM(). Unpaired surrogates are * also handled by this class. * {@description.close} */ static final class BnMS extends BnM { int lengthInChars; BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) { super(src, lastOcc, optoSft, next); for (int x = 0; x < buffer.length; x++) { lengthInChars += Character.charCount(buffer[x]); } } boolean match(Matcher matcher, int i, CharSequence seq) { int[] src = buffer; int patternLength = src.length; int last = matcher.to - lengthInChars; // Loop over all possible match positions in text NEXT: while (i <= last) { // Loop over pattern from right to left int ch; for (int j = countChars(seq, i, patternLength), x = patternLength - 1; j > 0; j -= Character.charCount(ch), x--) { ch = Character.codePointBefore(seq, i+j); if (ch != src[x]) { // Shift search to the right by the maximum of the // bad character shift and the good suffix shift int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]); i += countChars(seq, i, n); continue NEXT; } } // Entire pattern matched starting at i matcher.first = i; boolean ret = next.match(matcher, i + lengthInChars, seq); if (ret) { matcher.first = i; matcher.groups[0] = matcher.first; matcher.groups[1] = matcher.last; return true; } i += countChars(seq, i, 1); } matcher.hitEnd = true; return false; } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /** {@collect.stats} * {@description.open} * This must be the very first initializer. * {@description.close} */ static Node accept = new Node(); static Node lastAccept = new LastNode(); private static class CharPropertyNames { static CharProperty charPropertyFor(String name) { CharPropertyFactory m = map.get(name); return m == null ? null : m.make(); } private static abstract class CharPropertyFactory { abstract CharProperty make(); } private static void defCategory(String name, final int typeMask) { map.put(name, new CharPropertyFactory() { CharProperty make() { return new Category(typeMask);}}); } private static void defRange(String name, final int lower, final int upper) { map.put(name, new CharPropertyFactory() { CharProperty make() { return rangeFor(lower, upper);}}); } private static void defCtype(String name, final int ctype) { map.put(name, new CharPropertyFactory() { CharProperty make() { return new Ctype(ctype);}}); } private static abstract class CloneableProperty extends CharProperty implements Cloneable { public CloneableProperty clone() { try { return (CloneableProperty) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } } private static void defClone(String name, final CloneableProperty p) { map.put(name, new CharPropertyFactory() { CharProperty make() { return p.clone();}}); } private static final HashMap<String, CharPropertyFactory> map = new HashMap<String, CharPropertyFactory>(); static { // Unicode character property aliases, defined in // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt defCategory("Cn", 1<<Character.UNASSIGNED); defCategory("Lu", 1<<Character.UPPERCASE_LETTER); defCategory("Ll", 1<<Character.LOWERCASE_LETTER); defCategory("Lt", 1<<Character.TITLECASE_LETTER); defCategory("Lm", 1<<Character.MODIFIER_LETTER); defCategory("Lo", 1<<Character.OTHER_LETTER); defCategory("Mn", 1<<Character.NON_SPACING_MARK); defCategory("Me", 1<<Character.ENCLOSING_MARK); defCategory("Mc", 1<<Character.COMBINING_SPACING_MARK); defCategory("Nd", 1<<Character.DECIMAL_DIGIT_NUMBER); defCategory("Nl", 1<<Character.LETTER_NUMBER); defCategory("No", 1<<Character.OTHER_NUMBER); defCategory("Zs", 1<<Character.SPACE_SEPARATOR); defCategory("Zl", 1<<Character.LINE_SEPARATOR); defCategory("Zp", 1<<Character.PARAGRAPH_SEPARATOR); defCategory("Cc", 1<<Character.CONTROL); defCategory("Cf", 1<<Character.FORMAT); defCategory("Co", 1<<Character.PRIVATE_USE); defCategory("Cs", 1<<Character.SURROGATE); defCategory("Pd", 1<<Character.DASH_PUNCTUATION); defCategory("Ps", 1<<Character.START_PUNCTUATION); defCategory("Pe", 1<<Character.END_PUNCTUATION); defCategory("Pc", 1<<Character.CONNECTOR_PUNCTUATION); defCategory("Po", 1<<Character.OTHER_PUNCTUATION); defCategory("Sm", 1<<Character.MATH_SYMBOL); defCategory("Sc", 1<<Character.CURRENCY_SYMBOL); defCategory("Sk", 1<<Character.MODIFIER_SYMBOL); defCategory("So", 1<<Character.OTHER_SYMBOL); defCategory("Pi", 1<<Character.INITIAL_QUOTE_PUNCTUATION); defCategory("Pf", 1<<Character.FINAL_QUOTE_PUNCTUATION); defCategory("L", ((1<<Character.UPPERCASE_LETTER) | (1<<Character.LOWERCASE_LETTER) | (1<<Character.TITLECASE_LETTER) | (1<<Character.MODIFIER_LETTER) | (1<<Character.OTHER_LETTER))); defCategory("M", ((1<<Character.NON_SPACING_MARK) | (1<<Character.ENCLOSING_MARK) | (1<<Character.COMBINING_SPACING_MARK))); defCategory("N", ((1<<Character.DECIMAL_DIGIT_NUMBER) | (1<<Character.LETTER_NUMBER) | (1<<Character.OTHER_NUMBER))); defCategory("Z", ((1<<Character.SPACE_SEPARATOR) | (1<<Character.LINE_SEPARATOR) | (1<<Character.PARAGRAPH_SEPARATOR))); defCategory("C", ((1<<Character.CONTROL) | (1<<Character.FORMAT) | (1<<Character.PRIVATE_USE) | (1<<Character.SURROGATE))); // Other defCategory("P", ((1<<Character.DASH_PUNCTUATION) | (1<<Character.START_PUNCTUATION) | (1<<Character.END_PUNCTUATION) | (1<<Character.CONNECTOR_PUNCTUATION) | (1<<Character.OTHER_PUNCTUATION) | (1<<Character.INITIAL_QUOTE_PUNCTUATION) | (1<<Character.FINAL_QUOTE_PUNCTUATION))); defCategory("S", ((1<<Character.MATH_SYMBOL) | (1<<Character.CURRENCY_SYMBOL) | (1<<Character.MODIFIER_SYMBOL) | (1<<Character.OTHER_SYMBOL))); defCategory("LC", ((1<<Character.UPPERCASE_LETTER) | (1<<Character.LOWERCASE_LETTER) | (1<<Character.TITLECASE_LETTER))); defCategory("LD", ((1<<Character.UPPERCASE_LETTER) | (1<<Character.LOWERCASE_LETTER) | (1<<Character.TITLECASE_LETTER) | (1<<Character.MODIFIER_LETTER) | (1<<Character.OTHER_LETTER) | (1<<Character.DECIMAL_DIGIT_NUMBER))); defRange("L1", 0x00, 0xFF); // Latin-1 map.put("all", new CharPropertyFactory() { CharProperty make() { return new All(); }}); // Posix regular expression character classes, defined in // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html defRange("ASCII", 0x00, 0x7F); // ASCII defCtype("Alnum", ASCII.ALNUM); // Alphanumeric characters defCtype("Alpha", ASCII.ALPHA); // Alphabetic characters defCtype("Blank", ASCII.BLANK); // Space and tab characters defCtype("Cntrl", ASCII.CNTRL); // Control characters defRange("Digit", '0', '9'); // Numeric characters defCtype("Graph", ASCII.GRAPH); // printable and visible defRange("Lower", 'a', 'z'); // Lower-case alphabetic defRange("Print", 0x20, 0x7E); // Printable characters defCtype("Punct", ASCII.PUNCT); // Punctuation characters defCtype("Space", ASCII.SPACE); // Space characters defRange("Upper", 'A', 'Z'); // Upper-case alphabetic defCtype("XDigit",ASCII.XDIGIT); // hexadecimal digits // Java character properties, defined by methods in Character.java defClone("javaLowerCase", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isLowerCase(ch);}}); defClone("javaUpperCase", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isUpperCase(ch);}}); defClone("javaTitleCase", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isTitleCase(ch);}}); defClone("javaDigit", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isDigit(ch);}}); defClone("javaDefined", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isDefined(ch);}}); defClone("javaLetter", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isLetter(ch);}}); defClone("javaLetterOrDigit", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isLetterOrDigit(ch);}}); defClone("javaJavaIdentifierStart", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isJavaIdentifierStart(ch);}}); defClone("javaJavaIdentifierPart", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isJavaIdentifierPart(ch);}}); defClone("javaUnicodeIdentifierStart", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isUnicodeIdentifierStart(ch);}}); defClone("javaUnicodeIdentifierPart", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isUnicodeIdentifierPart(ch);}}); defClone("javaIdentifierIgnorable", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isIdentifierIgnorable(ch);}}); defClone("javaSpaceChar", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isSpaceChar(ch);}}); defClone("javaWhitespace", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isWhitespace(ch);}}); defClone("javaISOControl", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isISOControl(ch);}}); defClone("javaMirrored", new CloneableProperty() { boolean isSatisfiedBy(int ch) { return Character.isMirrored(ch);}}); } } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.regex; /** {@collect.stats} * {@description.open} * An engine that performs match operations on a {@link java.lang.CharSequence * </code>character sequence<code>} by interpreting a {@link Pattern}. * * <p> A matcher is created from a pattern by invoking the pattern's {@link * Pattern#matcher matcher} method. Once created, a matcher can be used to * perform three different kinds of match operations: * * <ul> * * <li><p> The {@link #matches matches} method attempts to match the entire * input sequence against the pattern. </p></li> * * <li><p> The {@link #lookingAt lookingAt} method attempts to match the * input sequence, starting at the beginning, against the pattern. </p></li> * * <li><p> The {@link #find find} method scans the input sequence looking for * the next subsequence that matches the pattern. </p></li> * * </ul> * * <p> Each of these methods returns a boolean indicating success or failure. * More information about a successful match can be obtained by querying the * state of the matcher. * * <p> A matcher finds matches in a subset of its input called the * <i>region</i>. By default, the region contains all of the matcher's input. * The region can be modified via the{@link #region region} method and queried * via the {@link #regionStart regionStart} and {@link #regionEnd regionEnd} * methods. The way that the region boundaries interact with some pattern * constructs can be changed. See {@link #useAnchoringBounds * useAnchoringBounds} and {@link #useTransparentBounds useTransparentBounds} * for more details. * * <p> This class also defines methods for replacing matched subsequences with * new strings whose contents can, if desired, be computed from the match * result. The {@link #appendReplacement appendReplacement} and {@link * #appendTail appendTail} methods can be used in tandem in order to collect * the result into an existing string buffer, or the more convenient {@link * #replaceAll replaceAll} method can be used to create a string in which every * matching subsequence in the input sequence is replaced. * * <p> The explicit state of a matcher includes the start and end indices of * the most recent successful match. It also includes the start and end * indices of the input subsequence captured by each <a * href="Pattern.html#cg">capturing group</a> in the pattern as well as a total * count of such subsequences. As a convenience, methods are also provided for * returning these captured subsequences in string form. * * <p> The explicit state of a matcher is initially undefined; attempting to * query any part of it before a successful match will cause an {@link * IllegalStateException} to be thrown. The explicit state of a matcher is * recomputed by every match operation. * * <p> The implicit state of a matcher includes the input character sequence as * well as the <i>append position</i>, which is initially zero and is updated * by the {@link #appendReplacement appendReplacement} method. * * <p> A matcher may be reset explicitly by invoking its {@link #reset()} * method or, if a new input sequence is desired, its {@link * #reset(java.lang.CharSequence) reset(CharSequence)} method. Resetting a * matcher discards its explicit state information and sets the append position * to zero. * {@description.close} * * {@property.open} * <p> Instances of this class are not safe for use by multiple concurrent * threads. </p> * {@property.close} * * @author Mike McCloskey * @author Mark Reinhold * @author JSR-51 Expert Group * @since 1.4 * @spec JSR-51 */ public final class Matcher implements MatchResult { /** {@collect.stats} * {@description.open} * The Pattern object that created this Matcher. * {@description.close} */ Pattern parentPattern; /** {@collect.stats} * {@description.open} * The storage used by groups. They may contain invalid values if * a group was skipped during the matching. * {@description.close} */ int[] groups; /** {@collect.stats} * {@description.open} * The range within the sequence that is to be matched. Anchors * will match at these "hard" boundaries. Changing the region * changes these values. * {@description.close} */ int from, to; /** {@collect.stats} * {@description.open} * Lookbehind uses this value to ensure that the subexpression * match ends at the point where the lookbehind was encountered. * {@description.close} */ int lookbehindTo; /** {@collect.stats} * {@description.open} * The original string being matched. * {@description.close} */ CharSequence text; /** {@collect.stats} * {@description.open} * Matcher state used by the last node. NOANCHOR is used when a * match does not have to consume all of the input. ENDANCHOR is * the mode used for matching all the input. * {@description.close} */ static final int ENDANCHOR = 1; static final int NOANCHOR = 0; int acceptMode = NOANCHOR; /** {@collect.stats} * {@description.open} * The range of string that last matched the pattern. If the last * match failed then first is -1; last initially holds 0 then it * holds the index of the end of the last match (which is where the * next search starts). * {@description.close} */ int first = -1, last = 0; /** {@collect.stats} * {@description.open} * The end index of what matched in the last match operation. * {@description.close} */ int oldLast = -1; /** {@collect.stats} * {@description.open} * The index of the last position appended in a substitution. * {@description.close} */ int lastAppendPosition = 0; /** {@collect.stats} * {@description.open} * Storage used by nodes to tell what repetition they are on in * a pattern, and where groups begin. The nodes themselves are stateless, * so they rely on this field to hold state during a match. * {@description.close} */ int[] locals; /** {@collect.stats} * {@description.open} * Boolean indicating whether or not more input could change * the results of the last match. * * If hitEnd is true, and a match was found, then more input * might cause a different match to be found. * If hitEnd is true and a match was not found, then more * input could cause a match to be found. * If hitEnd is false and a match was found, then more input * will not change the match. * If hitEnd is false and a match was not found, then more * input will not cause a match to be found. * {@description.close} */ boolean hitEnd; /** {@collect.stats} * {@description.open} * Boolean indicating whether or not more input could change * a positive match into a negative one. * * If requireEnd is true, and a match was found, then more * input could cause the match to be lost. * If requireEnd is false and a match was found, then more * input might change the match but the match won't be lost. * If a match was not found, then requireEnd has no meaning. * {@description.close} */ boolean requireEnd; /** {@collect.stats} * {@description.open} * If transparentBounds is true then the boundaries of this * matcher's region are transparent to lookahead, lookbehind, * and boundary matching constructs that try to see beyond them. * {@description.close} */ boolean transparentBounds = false; /** {@collect.stats} * {@description.open} * If anchoringBounds is true then the boundaries of this * matcher's region match anchors such as ^ and $. * {@description.close} */ boolean anchoringBounds = true; /** {@collect.stats} * {@description.open} * No default constructor. * {@description.close} */ Matcher() { } /** {@collect.stats} * {@description.open} * All matchers have the state used by Pattern during a match. * {@description.close} */ Matcher(Pattern parent, CharSequence text) { this.parentPattern = parent; this.text = text; // Allocate state storage int parentGroupCount = Math.max(parent.capturingGroupCount, 10); groups = new int[parentGroupCount * 2]; locals = new int[parent.localCount]; // Put fields into initial states reset(); } /** {@collect.stats} * {@description.open} * Returns the pattern that is interpreted by this matcher. * {@description.close} * * @return The pattern for which this matcher was created */ public Pattern pattern() { return parentPattern; } /** {@collect.stats} * {@description.open} * Returns the match state of this matcher as a {@link MatchResult}. * The result is unaffected by subsequent operations performed upon this * matcher. * {@description.close} * * @return a <code>MatchResult</code> with the state of this matcher * @since 1.5 */ public MatchResult toMatchResult() { Matcher result = new Matcher(this.parentPattern, text.toString()); result.first = this.first; result.last = this.last; result.groups = (int[])(this.groups.clone()); return result; } /** {@collect.stats} * {@description.open} * Changes the <tt>Pattern</tt> that this <tt>Matcher</tt> uses to * find matches with. * * <p> This method causes this matcher to lose information * about the groups of the last match that occurred. The * matcher's position in the input is maintained and its * last append position is unaffected.</p> * {@description.close} * * @param newPattern * The new pattern used by this matcher * @return This matcher * @throws IllegalArgumentException * If newPattern is <tt>null</tt> * @since 1.5 */ public Matcher usePattern(Pattern newPattern) { if (newPattern == null) throw new IllegalArgumentException("Pattern cannot be null"); parentPattern = newPattern; // Reallocate state storage int parentGroupCount = Math.max(newPattern.capturingGroupCount, 10); groups = new int[parentGroupCount * 2]; locals = new int[newPattern.localCount]; for (int i = 0; i < groups.length; i++) groups[i] = -1; for (int i = 0; i < locals.length; i++) locals[i] = -1; return this; } /** {@collect.stats} * {@description.open} * Resets this matcher. * {@description.close} * * {@property.open} * <p> Resetting a matcher discards all of its explicit state information * and sets its append position to zero. The matcher's region is set to the * default region, which is its entire character sequence. The anchoring * and transparency of this matcher's region boundaries are unaffected. * {@property.close} * * @return This matcher */ public Matcher reset() { first = -1; last = 0; oldLast = -1; for(int i=0; i<groups.length; i++) groups[i] = -1; for(int i=0; i<locals.length; i++) locals[i] = -1; lastAppendPosition = 0; from = 0; to = getTextLength(); return this; } /** {@collect.stats} * {@description.open} * Resets this matcher with a new input sequence. * {@description.close} * * {@property.open} * <p> Resetting a matcher discards all of its explicit state information * and sets its append position to zero. The matcher's region is set to * the default region, which is its entire character sequence. The * anchoring and transparency of this matcher's region boundaries are * unaffected. * {@property.close} * * @param input * The new input character sequence * * @return This matcher */ public Matcher reset(CharSequence input) { text = input; return reset(); } /** {@collect.stats} * {@description.open} * Returns the start index of the previous match. </p> * {@description.close} * * @return The index of the first character matched * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public int start() { if (first < 0) throw new IllegalStateException("No match available"); return first; } /** {@collect.stats} * {@description.open} * Returns the start index of the subsequence captured by the given group * during the previous match operation. * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <i>m.</i><tt>start(0)</tt> is equivalent to * <i>m.</i><tt>start()</tt>. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The index of the first character captured by the group, * or <tt>-1</tt> if the match was successful but the group * itself did not match anything * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public int start(int group) { if (first < 0) throw new IllegalStateException("No match available"); if (group > groupCount()) throw new IndexOutOfBoundsException("No group " + group); return groups[group * 2]; } /** {@collect.stats} * {@description.open} * Returns the offset after the last character matched. </p> * {@description.close} * * @return The offset after the last character matched * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public int end() { if (first < 0) throw new IllegalStateException("No match available"); return last; } /** {@collect.stats} * {@description.open} * Returns the offset after the last character of the subsequence * captured by the given group during the previous match operation. * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <i>m.</i><tt>end(0)</tt> is equivalent to * <i>m.</i><tt>end()</tt>. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The offset after the last character captured by the group, * or <tt>-1</tt> if the match was successful * but the group itself did not match anything * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public int end(int group) { if (first < 0) throw new IllegalStateException("No match available"); if (group > groupCount()) throw new IndexOutOfBoundsException("No group " + group); return groups[group * 2 + 1]; } /** {@collect.stats} * {@description.open} * Returns the input subsequence matched by the previous match. * * <p> For a matcher <i>m</i> with input sequence <i>s</i>, * the expressions <i>m.</i><tt>group()</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt>&nbsp;<i>m.</i><tt>end())</tt> * are equivalent. </p> * * <p> Note that some patterns, for example <tt>a*</tt>, match the empty * string. This method will return the empty string when the pattern * successfully matches the empty string in the input. </p> * {@description.close} * * @return The (possibly empty) subsequence matched by the previous match, * in string form * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public String group() { return group(0); } /** {@collect.stats} * {@description.open} * Returns the input subsequence captured by the given group during the * previous match operation. * * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt>&nbsp;<i>m.</i><tt>end(</tt><i>g</i><tt>))</tt> * are equivalent. </p> * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>. * </p> * * <p> If the match was successful but the group specified failed to match * any part of the input sequence, then <tt>null</tt> is returned. Note * that some groups, for example <tt>(a*)</tt>, match the empty string. * This method will return the empty string when such a group successfully * matches the empty string in the input. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The (possibly empty) subsequence captured by the group * during the previous match, or <tt>null</tt> if the group * failed to match part of the input * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public String group(int group) { if (first < 0) throw new IllegalStateException("No match found"); if (group < 0 || group > groupCount()) throw new IndexOutOfBoundsException("No group " + group); if ((groups[group*2] == -1) || (groups[group*2+1] == -1)) return null; return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString(); } /** {@collect.stats} * {@description.open} * Returns the number of capturing groups in this matcher's pattern. * * <p> Group zero denotes the entire pattern by convention. It is not * included in this count. * * <p> Any non-negative integer smaller than or equal to the value * returned by this method is guaranteed to be a valid group index for * this matcher. </p> * {@description.close} * * @return The number of capturing groups in this matcher's pattern */ public int groupCount() { return parentPattern.capturingGroupCount - 1; } /** {@collect.stats} * {@description.open} * Attempts to match the entire region against the pattern. * * <p> If the match succeeds then more information can be obtained via the * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> * {@description.close} * * @return <tt>true</tt> if, and only if, the entire region sequence * matches this matcher's pattern */ public boolean matches() { return match(from, ENDANCHOR); } /** {@collect.stats} * {@description.open} * Attempts to find the next subsequence of the input sequence that matches * the pattern. * * <p> This method starts at the beginning of this matcher's region, or, if * a previous invocation of the method was successful and the matcher has * not since been reset, at the first character not matched by the previous * match. * * <p> If the match succeeds then more information can be obtained via the * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> * {@description.close} * * @return <tt>true</tt> if, and only if, a subsequence of the input * sequence matches this matcher's pattern */ public boolean find() { int nextSearchIndex = last; if (nextSearchIndex == first) nextSearchIndex++; // If next search starts before region, start it at region if (nextSearchIndex < from) nextSearchIndex = from; // If next search starts beyond region then it fails if (nextSearchIndex > to) { for (int i = 0; i < groups.length; i++) groups[i] = -1; return false; } return search(nextSearchIndex); } /** {@collect.stats} * {@description.open} * Resets this matcher and then attempts to find the next subsequence of * the input sequence that matches the pattern, starting at the specified * index. * * <p> If the match succeeds then more information can be obtained via the * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods, and subsequent * invocations of the {@link #find()} method will start at the first * character not matched by this match. </p> * {@description.close} * * @throws IndexOutOfBoundsException * If start is less than zero or if start is greater than the * length of the input sequence. * * @return <tt>true</tt> if, and only if, a subsequence of the input * sequence starting at the given index matches this matcher's * pattern */ public boolean find(int start) { int limit = getTextLength(); if ((start < 0) || (start > limit)) throw new IndexOutOfBoundsException("Illegal start index"); reset(); return search(start); } /** {@collect.stats} * {@description.open} * Attempts to match the input sequence, starting at the beginning of the * region, against the pattern. * * <p> Like the {@link #matches matches} method, this method always starts * at the beginning of the region; unlike that method, it does not * require that the entire region be matched. * {@description.close} * * {@property.open} * <p> If the match succeeds then more information can be obtained via the * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> * {@property.close} * * @return <tt>true</tt> if, and only if, a prefix of the input * sequence matches this matcher's pattern */ public boolean lookingAt() { return match(from, NOANCHOR); } /** {@collect.stats} * {@description.open} * Returns a literal replacement <code>String</code> for the specified * <code>String</code>. * * This method produces a <code>String</code> that will work * as a literal replacement <code>s</code> in the * <code>appendReplacement</code> method of the {@link Matcher} class. * The <code>String</code> produced will match the sequence of characters * in <code>s</code> treated as a literal sequence. Slashes ('\') and * dollar signs ('$') will be given no special meaning. * {@description.close} * * @param s The string to be literalized * @return A literal string replacement * @since 1.5 */ public static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) return s; StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c == '\\' || c == '$') { sb.append('\\'); } sb.append(c); } return sb.toString(); } /** {@collect.stats} * {@description.open} * Implements a non-terminal append-and-replace step. * * <p> This method performs the following actions: </p> * * <ol> * * <li><p> It reads characters from the input sequence, starting at the * append position, and appends them to the given string buffer. It * stops after reading the last character preceding the previous match, * that is, the character at index {@link * #start()}&nbsp;<tt>-</tt>&nbsp;<tt>1</tt>. </p></li> * * <li><p> It appends the given replacement string to the string buffer. * </p></li> * * <li><p> It sets the append position of this matcher to the index of * the last character matched, plus one, that is, to {@link #end()}. * </p></li> * * </ol> * * <p> The replacement string may contain references to subsequences * captured during the previous match: Each occurrence of * <tt>$</tt><i>g</i><tt></tt> will be replaced by the result of * evaluating {@link #group(int) group}<tt>(</tt><i>g</i><tt>)</tt>. * The first number after the <tt>$</tt> is always treated as part of * the group reference. Subsequent numbers are incorporated into g if * they would form a legal group reference. Only the numerals '0' * through '9' are considered as potential components of the group * reference. If the second group matched the string <tt>"foo"</tt>, for * example, then passing the replacement string <tt>"$2bar"</tt> would * cause <tt>"foobar"</tt> to be appended to the string buffer. A dollar * sign (<tt>$</tt>) may be included as a literal in the replacement * string by preceding it with a backslash (<tt>\$</tt>). * * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in * the replacement string may cause the results to be different than if it * were being treated as a literal replacement string. Dollar signs may be * treated as references to captured subsequences as described above, and * backslashes are used to escape literal characters in the replacement * string. * {@description.close} * * {@property.open} * <p> This method is intended to be used in a loop together with the * {@link #appendTail appendTail} and {@link #find find} methods. * {@property.close} * {@description.open} * The * following code, for example, writes <tt>one dog two dogs in the * yard</tt> to the standard-output stream: </p> * * <blockquote><pre> * Pattern p = Pattern.compile("cat"); * Matcher m = p.matcher("one cat two cats in the yard"); * StringBuffer sb = new StringBuffer(); * while (m.find()) { * m.appendReplacement(sb, "dog"); * } * m.appendTail(sb); * System.out.println(sb.toString());</pre></blockquote> * {@description.close} * * @param sb * The target string buffer * * @param replacement * The replacement string * * @return This matcher * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If the replacement string refers to a capturing group * that does not exist in the pattern */ public Matcher appendReplacement(StringBuffer sb, String replacement) { // If no match, return error if (first < 0) throw new IllegalStateException("No match available"); // Process substitution string to replace group references with groups int cursor = 0; StringBuilder result = new StringBuilder(); while (cursor < replacement.length()) { char nextChar = replacement.charAt(cursor); if (nextChar == '\\') { cursor++; nextChar = replacement.charAt(cursor); result.append(nextChar); cursor++; } else if (nextChar == '$') { // Skip past $ cursor++; // The first number is always a group int refNum = (int)replacement.charAt(cursor) - '0'; if ((refNum < 0)||(refNum > 9)) throw new IllegalArgumentException( "Illegal group reference"); cursor++; // Capture the largest legal group string boolean done = false; while (!done) { if (cursor >= replacement.length()) { break; } int nextDigit = replacement.charAt(cursor) - '0'; if ((nextDigit < 0)||(nextDigit > 9)) { // not a number break; } int newRefNum = (refNum * 10) + nextDigit; if (groupCount() < newRefNum) { done = true; } else { refNum = newRefNum; cursor++; } } // Append group if (start(refNum) != -1 && end(refNum) != -1) result.append(text, start(refNum), end(refNum)); } else { result.append(nextChar); cursor++; } } // Append the intervening text sb.append(text, lastAppendPosition, first); // Append the match substitution sb.append(result); lastAppendPosition = last; return this; } /** {@collect.stats} * {@description.open} * Implements a terminal append-and-replace step. * * <p> This method reads characters from the input sequence, starting at * the append position, and appends them to the given string buffer. It is * intended to be invoked after one or more invocations of the {@link * #appendReplacement appendReplacement} method in order to copy the * remainder of the input sequence. </p> * {@description.close} * * @param sb * The target string buffer * * @return The target string buffer */ public StringBuffer appendTail(StringBuffer sb) { sb.append(text, lastAppendPosition, getTextLength()); return sb; } /** {@collect.stats} * {@description.open} * Replaces every subsequence of the input sequence that matches the * pattern with the given replacement string. * * <p> This method first resets this matcher. It then scans the input * sequence looking for matches of the pattern. Characters that are not * part of any match are appended directly to the result string; each match * is replaced in the result by the replacement string. The replacement * string may contain references to captured subsequences as in the {@link * #appendReplacement appendReplacement} method. * * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in * the replacement string may cause the results to be different than if it * were being treated as a literal replacement string. Dollar signs may be * treated as references to captured subsequences as described above, and * backslashes are used to escape literal characters in the replacement * string. * * <p> Given the regular expression <tt>a*b</tt>, the input * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string * <tt>"-"</tt>, an invocation of this method on a matcher for that * expression would yield the string <tt>"-foo-foo-foo-"</tt>. * * <p> Invoking this method changes this matcher's state. If the matcher * is to be used in further matching operations then it should first be * reset. </p> * {@description.close} * * @param replacement * The replacement string * * @return The string constructed by replacing each matching subsequence * by the replacement string, substituting captured subsequences * as needed */ public String replaceAll(String replacement) { reset(); boolean result = find(); if (result) { StringBuffer sb = new StringBuffer(); do { appendReplacement(sb, replacement); result = find(); } while (result); appendTail(sb); return sb.toString(); } return text.toString(); } /** {@collect.stats} * {@description.open} * Replaces the first subsequence of the input sequence that matches the * pattern with the given replacement string. * * <p> This method first resets this matcher. It then scans the input * sequence looking for a match of the pattern. Characters that are not * part of the match are appended directly to the result string; the match * is replaced in the result by the replacement string. The replacement * string may contain references to captured subsequences as in the {@link * #appendReplacement appendReplacement} method. * * <p>Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in * the replacement string may cause the results to be different than if it * were being treated as a literal replacement string. Dollar signs may be * treated as references to captured subsequences as described above, and * backslashes are used to escape literal characters in the replacement * string. * * <p> Given the regular expression <tt>dog</tt>, the input * <tt>"zzzdogzzzdogzzz"</tt>, and the replacement string * <tt>"cat"</tt>, an invocation of this method on a matcher for that * expression would yield the string <tt>"zzzcatzzzdogzzz"</tt>. </p> * * <p> Invoking this method changes this matcher's state. If the matcher * is to be used in further matching operations then it should first be * reset. </p> * {@description.close} * * @param replacement * The replacement string * @return The string constructed by replacing the first matching * subsequence by the replacement string, substituting captured * subsequences as needed */ public String replaceFirst(String replacement) { if (replacement == null) throw new NullPointerException("replacement"); reset(); if (!find()) return text.toString(); StringBuffer sb = new StringBuffer(); appendReplacement(sb, replacement); appendTail(sb); return sb.toString(); } /** {@collect.stats} * {@description.open} * Sets the limits of this matcher's region. The region is the part of the * input sequence that will be searched to find a match. Invoking this * method resets the matcher, and then sets the region to start at the * index specified by the <code>start</code> parameter and end at the * index specified by the <code>end</code> parameter. * * <p>Depending on the transparency and anchoring being used (see * {@link #useTransparentBounds useTransparentBounds} and * {@link #useAnchoringBounds useAnchoringBounds}), certain constructs such * as anchors may behave differently at or around the boundaries of the * region. * {@description.close} * * @param start * The index to start searching at (inclusive) * @param end * The index to end searching at (exclusive) * @throws IndexOutOfBoundsException * If start or end is less than zero, if * start is greater than the length of the input sequence, if * end is greater than the length of the input sequence, or if * start is greater than end. * @return this matcher * @since 1.5 */ public Matcher region(int start, int end) { if ((start < 0) || (start > getTextLength())) throw new IndexOutOfBoundsException("start"); if ((end < 0) || (end > getTextLength())) throw new IndexOutOfBoundsException("end"); if (start > end) throw new IndexOutOfBoundsException("start > end"); reset(); from = start; to = end; return this; } /** {@collect.stats} * {@description.open} * Reports the start index of this matcher's region. The * searches this matcher conducts are limited to finding matches * within {@link #regionStart regionStart} (inclusive) and * {@link #regionEnd regionEnd} (exclusive). * {@description.close} * * @return The starting point of this matcher's region * @since 1.5 */ public int regionStart() { return from; } /** {@collect.stats} * {@description.open} * Reports the end index (exclusive) of this matcher's region. * The searches this matcher conducts are limited to finding matches * within {@link #regionStart regionStart} (inclusive) and * {@link #regionEnd regionEnd} (exclusive). * {@description.close} * * @return the ending point of this matcher's region * @since 1.5 */ public int regionEnd() { return to; } /** {@collect.stats} * {@description.open} * Queries the transparency of region bounds for this matcher. * * <p> This method returns <tt>true</tt> if this matcher uses * <i>transparent</i> bounds, <tt>false</tt> if it uses <i>opaque</i> * bounds. * * <p> See {@link #useTransparentBounds useTransparentBounds} for a * description of transparent and opaque bounds. * * <p> By default, a matcher uses opaque region boundaries. * {@description.close} * * @return <tt>true</tt> iff this matcher is using transparent bounds, * <tt>false</tt> otherwise. * @see java.util.regex.Matcher#useTransparentBounds(boolean) * @since 1.5 */ public boolean hasTransparentBounds() { return transparentBounds; } /** {@collect.stats} * {@description.open} * Sets the transparency of region bounds for this matcher. * * <p> Invoking this method with an argument of <tt>true</tt> will set this * matcher to use <i>transparent</i> bounds. If the boolean * argument is <tt>false</tt>, then <i>opaque</i> bounds will be used. * * <p> Using transparent bounds, the boundaries of this * matcher's region are transparent to lookahead, lookbehind, * and boundary matching constructs. Those constructs can see beyond the * boundaries of the region to see if a match is appropriate. * * <p> Using opaque bounds, the boundaries of this matcher's * region are opaque to lookahead, lookbehind, and boundary matching * constructs that may try to see beyond them. Those constructs cannot * look past the boundaries so they will fail to match anything outside * of the region. * * <p> By default, a matcher uses opaque bounds. * {@description.close} * * @param b a boolean indicating whether to use opaque or transparent * regions * @return this matcher * @see java.util.regex.Matcher#hasTransparentBounds * @since 1.5 */ public Matcher useTransparentBounds(boolean b) { transparentBounds = b; return this; } /** {@collect.stats} * {@description.open} * Queries the anchoring of region bounds for this matcher. * * <p> This method returns <tt>true</tt> if this matcher uses * <i>anchoring</i> bounds, <tt>false</tt> otherwise. * * <p> See {@link #useAnchoringBounds useAnchoringBounds} for a * description of anchoring bounds. * * <p> By default, a matcher uses anchoring region boundaries. * {@description.close} * * @return <tt>true</tt> iff this matcher is using anchoring bounds, * <tt>false</tt> otherwise. * @see java.util.regex.Matcher#useAnchoringBounds(boolean) * @since 1.5 */ public boolean hasAnchoringBounds() { return anchoringBounds; } /** {@collect.stats} * {@description.open} * Sets the anchoring of region bounds for this matcher. * * <p> Invoking this method with an argument of <tt>true</tt> will set this * matcher to use <i>anchoring</i> bounds. If the boolean * argument is <tt>false</tt>, then <i>non-anchoring</i> bounds will be * used. * * <p> Using anchoring bounds, the boundaries of this * matcher's region match anchors such as ^ and $. * * <p> Without anchoring bounds, the boundaries of this * matcher's region will not match anchors such as ^ and $. * * <p> By default, a matcher uses anchoring region boundaries. * {@description.close} * * @param b a boolean indicating whether or not to use anchoring bounds. * @return this matcher * @see java.util.regex.Matcher#hasAnchoringBounds * @since 1.5 */ public Matcher useAnchoringBounds(boolean b) { anchoringBounds = b; return this; } /** {@collect.stats} * {@description.open} * <p>Returns the string representation of this matcher. The * string representation of a <code>Matcher</code> contains information * that may be useful for debugging. The exact format is unspecified. * {@description.close} * * @return The string representation of this matcher * @since 1.5 */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("java.util.regex.Matcher"); sb.append("[pattern=" + pattern()); sb.append(" region="); sb.append(regionStart() + "," + regionEnd()); sb.append(" lastmatch="); if ((first >= 0) && (group() != null)) { sb.append(group()); } sb.append("]"); return sb.toString(); } /** {@collect.stats} * {@description.open} * <p>Returns true if the end of input was hit by the search engine in * the last match operation performed by this matcher. * * <p>When this method returns true, then it is possible that more input * would have changed the result of the last search. * {@description.close} * * @return true iff the end of input was hit in the last match; false * otherwise * @since 1.5 */ public boolean hitEnd() { return hitEnd; } /** {@collect.stats} * {@description.open} * <p>Returns true if more input could change a positive match into a * negative one. * * <p>If this method returns true, and a match was found, then more * input could cause the match to be lost. If this method returns false * and a match was found, then more input might change the match but the * match won't be lost. If a match was not found, then requireEnd has no * meaning. * {@description.close} * * @return true iff more input could change a positive match into a * negative one. * @since 1.5 */ public boolean requireEnd() { return requireEnd; } /** {@collect.stats} * {@description.open} * Initiates a search to find a Pattern within the given bounds. * The groups are filled with default values and the match of the root * of the state machine is called. The state machine will hold the state * of the match as it proceeds in this matcher. * * Matcher.from is not set here, because it is the "hard" boundary * of the start of the search which anchors will set to. The from param * is the "soft" boundary of the start of the search, meaning that the * regex tries to match at that index but ^ won't match there. Subsequent * calls to the search methods start at a new "soft" boundary which is * the end of the previous match. * {@description.close} */ boolean search(int from) { this.hitEnd = false; this.requireEnd = false; from = from < 0 ? 0 : from; this.first = from; this.oldLast = oldLast < 0 ? from : oldLast; for (int i = 0; i < groups.length; i++) groups[i] = -1; acceptMode = NOANCHOR; boolean result = parentPattern.root.match(this, from, text); if (!result) this.first = -1; this.oldLast = this.last; return result; } /** {@collect.stats} * {@description.open} * Initiates a search for an anchored match to a Pattern within the given * bounds. The groups are filled with default values and the match of the * root of the state machine is called. The state machine will hold the * state of the match as it proceeds in this matcher. * {@description.close} */ boolean match(int from, int anchor) { this.hitEnd = false; this.requireEnd = false; from = from < 0 ? 0 : from; this.first = from; this.oldLast = oldLast < 0 ? from : oldLast; for (int i = 0; i < groups.length; i++) groups[i] = -1; acceptMode = anchor; boolean result = parentPattern.matchRoot.match(this, from, text); if (!result) this.first = -1; this.oldLast = this.last; return result; } /** {@collect.stats} * {@description.open} * Returns the end index of the text. * {@description.close} * * @return the index after the last character in the text */ int getTextLength() { return text.length(); } /** {@collect.stats} * {@description.open} * Generates a String from this Matcher's input in the specified range. * {@description.close} * * @param beginIndex the beginning index, inclusive * @param endIndex the ending index, exclusive * @return A String generated from this Matcher's input */ CharSequence getSubSequence(int beginIndex, int endIndex) { return text.subSequence(beginIndex, endIndex); } /** {@collect.stats} * {@description.open} * Returns this Matcher's input character at index i. * {@description.close} * * @return A char from the specified index */ char charAt(int i) { return text.charAt(i); } }
Java
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.regex; /** {@collect.stats} * {@description.open} * The result of a match operation. * * <p>This interface contains query methods used to determine the * results of a match against a regular expression. The match boundaries, * groups and group boundaries can be seen but not modified through * a <code>MatchResult</code>. * {@description.close} * * @author Michael McCloskey * @see Matcher * @since 1.5 */ public interface MatchResult { /** {@collect.stats} * {@description.open} * Returns the start index of the match. * {@description.close} * * @return The index of the first character matched * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public int start(); /** {@collect.stats} * {@description.open} * Returns the start index of the subsequence captured by the given group * during this match. * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <i>m.</i><tt>start(0)</tt> is equivalent to * <i>m.</i><tt>start()</tt>. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The index of the first character captured by the group, * or <tt>-1</tt> if the match was successful but the group * itself did not match anything * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public int start(int group); /** {@collect.stats} * {@description.open} * Returns the offset after the last character matched. </p> * {@description.close} * * @return @return The offset after the last character matched * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public int end(); /** {@collect.stats} * {@description.open} * Returns the offset after the last character of the subsequence * captured by the given group during this match. * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <i>m.</i><tt>end(0)</tt> is equivalent to * <i>m.</i><tt>end()</tt>. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The offset after the last character captured by the group, * or <tt>-1</tt> if the match was successful * but the group itself did not match anything * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public int end(int group); /** {@collect.stats} * {@description.open} * Returns the input subsequence matched by the previous match. * * <p> For a matcher <i>m</i> with input sequence <i>s</i>, * the expressions <i>m.</i><tt>group()</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt>&nbsp;<i>m.</i><tt>end())</tt> * are equivalent. </p> * * <p> Note that some patterns, for example <tt>a*</tt>, match the empty * string. This method will return the empty string when the pattern * successfully matches the empty string in the input. </p> * {@description.close} * * @return The (possibly empty) subsequence matched by the previous match, * in string form * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed */ public String group(); /** {@collect.stats} * {@description.open} * Returns the input subsequence captured by the given group during the * previous match operation. * * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt>&nbsp;<i>m.</i><tt>end(</tt><i>g</i><tt>))</tt> * are equivalent. </p> * * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left * to right, starting at one. Group zero denotes the entire pattern, so * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>. * </p> * * <p> If the match was successful but the group specified failed to match * any part of the input sequence, then <tt>null</tt> is returned. Note * that some groups, for example <tt>(a*)</tt>, match the empty string. * This method will return the empty string when such a group successfully * matches the empty string in the input. </p> * {@description.close} * * @param group * The index of a capturing group in this matcher's pattern * * @return The (possibly empty) subsequence captured by the group * during the previous match, or <tt>null</tt> if the group * failed to match part of the input * * @throws IllegalStateException * If no match has yet been attempted, * or if the previous match operation failed * * @throws IndexOutOfBoundsException * If there is no capturing group in the pattern * with the given index */ public String group(int group); /** {@collect.stats} * {@description.open} * Returns the number of capturing groups in this match result's pattern. * * <p> Group zero denotes the entire pattern by convention. It is not * included in this count. * * <p> Any non-negative integer smaller than or equal to the value * returned by this method is guaranteed to be a valid group index for * this matcher. </p> * {@description.close} * * @return The number of capturing groups in this matcher's pattern */ public int groupCount(); }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A {@link Set} that further provides a <i>total ordering</i> on its elements. * The elements are ordered using their {@linkplain Comparable natural * ordering}, or by a {@link Comparator} typically provided at sorted * set creation time. The set's iterator will traverse the set in * ascending element order. Several additional operations are provided * to take advantage of the ordering. (This interface is the set * analogue of {@link SortedMap}.) * {@description.close} * * {@property.open formal:java.util.SortedSet_Comparable} * <p>All elements inserted into a sorted set must implement the <tt>Comparable</tt> * interface (or be accepted by the specified comparator). Furthermore, all * such elements must be <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> * (or <tt>comparator.compare(e1, e2)</tt>) must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and <tt>e2</tt> in * the sorted set. Attempts to violate this restriction will cause the * offending method or constructor invocation to throw a * <tt>ClassCastException</tt>. * {@property.close} * * {@description.open} * <p>Note that the ordering maintained by a sorted set (whether or not an * explicit comparator is provided) must be <i>consistent with equals</i> if * the sorted set is to correctly implement the <tt>Set</tt> interface. (See * the <tt>Comparable</tt> interface or <tt>Comparator</tt> interface for a * precise definition of <i>consistent with equals</i>.) This is so because * the <tt>Set</tt> interface is defined in terms of the <tt>equals</tt> * operation, but a sorted set performs all element comparisons using its * <tt>compareTo</tt> (or <tt>compare</tt>) method, so two elements that are * deemed equal by this method are, from the standpoint of the sorted set, * equal. The behavior of a sorted set <i>is</i> well-defined even if its * ordering is inconsistent with equals; it just fails to obey the general * contract of the <tt>Set</tt> interface. * {@description.close} * * {@property.open formal:java.util.SortedSet_StandardConstructors} * <p>All general-purpose sorted set implementation classes should * provide four "standard" constructors: 1) A void (no arguments) * constructor, which creates an empty sorted set sorted according to * the natural ordering of its elements. 2) A constructor with a * single argument of type <tt>Comparator</tt>, which creates an empty * sorted set sorted according to the specified comparator. 3) A * constructor with a single argument of type <tt>Collection</tt>, * which creates a new sorted set with the same elements as its * argument, sorted according to the natural ordering of the elements. * 4) A constructor with a single argument of type <tt>SortedSet</tt>, * which creates a new sorted set with the same elements and the same * ordering as the input sorted set. There is no way to enforce this * recommendation, as interfaces cannot contain constructors. * {@property.close} * * {@description.open} * <p>Note: several methods return subsets with restricted ranges. * Such ranges are <i>half-open</i>, that is, they include their low * endpoint but not their high endpoint (where applicable). * If you need a <i>closed range</i> (which includes both endpoints), and * the element type allows for calculation of the successor of a given * value, merely request the subrange from <tt>lowEndpoint</tt> to * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt> * is a sorted set of strings. The following idiom obtains a view * containing all of the strings in <tt>s</tt> from <tt>low</tt> to * <tt>high</tt>, inclusive:<pre> * SortedSet&lt;String&gt; sub = s.subSet(low, high+"\0");</pre> * * A similar technique can be used to generate an <i>open range</i> (which * contains neither endpoint). The following idiom obtains a view * containing all of the Strings in <tt>s</tt> from <tt>low</tt> to * <tt>high</tt>, exclusive:<pre> * SortedSet&lt;String&gt; sub = s.subSet(low+"\0", high);</pre> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @see Set * @see TreeSet * @see SortedMap * @see Collection * @see Comparable * @see Comparator * @see ClassCastException * @since 1.2 */ public interface SortedSet<E> extends Set<E> { /** {@collect.stats} * {@description.open} * Returns the comparator used to order the elements in this set, * or <tt>null</tt> if this set uses the {@linkplain Comparable * natural ordering} of its elements. * {@description.close} * * @return the comparator used to order the elements in this set, * or <tt>null</tt> if this set uses the natural ordering * of its elements */ Comparator<? super E> comparator(); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements range * from <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, * exclusive. (If <tt>fromElement</tt> and <tt>toElement</tt> are * equal, the returned set is empty.) The returned set is backed * by this set, so changes in the returned set are reflected in * this set, and vice-versa. The returned set supports all * optional set operations that this set supports. * * <p>The returned set will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert an element outside its range. * {@description.close} * * @param fromElement low endpoint (inclusive) of the returned set * @param toElement high endpoint (exclusive) of the returned set * @return a view of the portion of this set whose elements range from * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, exclusive * @throws ClassCastException if <tt>fromElement</tt> and * <tt>toElement</tt> cannot be compared to one another using this * set's comparator (or, if the set has no comparator, using * natural ordering). Implementations may, but are not required * to, throw this exception if <tt>fromElement</tt> or * <tt>toElement</tt> cannot be compared to elements currently in * the set. * @throws NullPointerException if <tt>fromElement</tt> or * <tt>toElement</tt> is null and this set does not permit null * elements * @throws IllegalArgumentException if <tt>fromElement</tt> is * greater than <tt>toElement</tt>; or if this set itself * has a restricted range, and <tt>fromElement</tt> or * <tt>toElement</tt> lies outside the bounds of the range */ SortedSet<E> subSet(E fromElement, E toElement); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements are * strictly less than <tt>toElement</tt>. The returned set is * backed by this set, so changes in the returned set are * reflected in this set, and vice-versa. The returned set * supports all optional set operations that this set supports. * * <p>The returned set will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert an element outside its range. * {@description.close} * * @param toElement high endpoint (exclusive) of the returned set * @return a view of the portion of this set whose elements are strictly * less than <tt>toElement</tt> * @throws ClassCastException if <tt>toElement</tt> is not compatible * with this set's comparator (or, if the set has no comparator, * if <tt>toElement</tt> does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if <tt>toElement</tt> cannot be compared to elements * currently in the set. * @throws NullPointerException if <tt>toElement</tt> is null and * this set does not permit null elements * @throws IllegalArgumentException if this set itself has a * restricted range, and <tt>toElement</tt> lies outside the * bounds of the range */ SortedSet<E> headSet(E toElement); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this set whose elements are * greater than or equal to <tt>fromElement</tt>. The returned * set is backed by this set, so changes in the returned set are * reflected in this set, and vice-versa. The returned set * supports all optional set operations that this set supports. * * <p>The returned set will throw an <tt>IllegalArgumentException</tt> * on an attempt to insert an element outside its range. * {@description.close} * * @param fromElement low endpoint (inclusive) of the returned set * @return a view of the portion of this set whose elements are greater * than or equal to <tt>fromElement</tt> * @throws ClassCastException if <tt>fromElement</tt> is not compatible * with this set's comparator (or, if the set has no comparator, * if <tt>fromElement</tt> does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if <tt>fromElement</tt> cannot be compared to elements * currently in the set. * @throws NullPointerException if <tt>fromElement</tt> is null * and this set does not permit null elements * @throws IllegalArgumentException if this set itself has a * restricted range, and <tt>fromElement</tt> lies outside the * bounds of the range */ SortedSet<E> tailSet(E fromElement); /** {@collect.stats} * {@description.open} * Returns the first (lowest) element currently in this set. * {@description.close} * * @return the first (lowest) element currently in this set * @throws NoSuchElementException if this set is empty */ E first(); /** {@collect.stats} * {@description.open} * Returns the last (highest) element currently in this set. * {@description.close} * * @return the last (highest) element currently in this set * @throws NoSuchElementException if this set is empty */ E last(); }
Java
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when an unknown conversion is given. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to * any method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class UnknownFormatConversionException extends IllegalFormatException { private static final long serialVersionUID = 19060418L; private String s; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the unknown conversion. * {@description.close} * * @param s * Unknown conversion */ public UnknownFormatConversionException(String s) { if (s == null) throw new NullPointerException(); this.s = s; } /** {@collect.stats} * {@description.open} * Returns the unknown conversion. * {@description.close} * * @return The unknown conversion. */ public String getConversion() { return s; } // javadoc inherited from Throwable.java public String getMessage() { return String.format("Conversion = '%s'", s); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the <tt>List</tt> * interface to minimize the effort required to implement this interface * backed by a "sequential access" data store (such as a linked list). For * random access data (such as an array), <tt>AbstractList</tt> should be used * in preference to this class.<p> * * This class is the opposite of the <tt>AbstractList</tt> class in the sense * that it implements the "random access" methods (<tt>get(int index)</tt>, * <tt>set(int index, E element)</tt>, <tt>add(int index, E element)</tt> and * <tt>remove(int index)</tt>) on top of the list's list iterator, instead of * the other way around.<p> * {@description.close} * * {@property.open enforced} * To implement a list the programmer needs only to extend this class and * provide implementations for the <tt>listIterator</tt> and <tt>size</tt> * methods. * {@property.close} * {@property.open unknown} * For an unmodifiable list, the programmer need only implement the * list iterator's <tt>hasNext</tt>, <tt>next</tt>, <tt>hasPrevious</tt>, * <tt>previous</tt> and <tt>index</tt> methods.<p> * {@property.close} * * {@property.open unknown} * For a modifiable list the programmer should additionally implement the list * iterator's <tt>set</tt> method. For a variable-size list the programmer * should additionally implement the list iterator's <tt>remove</tt> and * <tt>add</tt> methods.<p> * {@property.close} * * {@property.open formal:java.util.Collection_StandardConstructors} * The programmer should generally provide a void (no argument) and collection * constructor, as per the recommendation in the <tt>Collection</tt> interface * specification.<p> * {@property.close} * * {@description.open} * This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see AbstractList * @see AbstractCollection * @since 1.2 */ public abstract class AbstractSequentialList<E> extends AbstractList<E> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected AbstractSequentialList() { } /** {@collect.stats} * {@description.open} * Returns the element at the specified position in this list. * * <p>This implementation first gets a list iterator pointing to the * indexed element (with <tt>listIterator(index)</tt>). Then, it gets * the element using <tt>ListIterator.next</tt> and returns it. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { try { return listIterator(index).next(); } catch (NoSuchElementException exc) { throw new IndexOutOfBoundsException("Index: "+index); } } /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this list with the * specified element (optional operation). * * <p>This implementation first gets a list iterator pointing to the * indexed element (with <tt>listIterator(index)</tt>). Then, it gets * the current element using <tt>ListIterator.next</tt> and replaces it * with <tt>ListIterator.set</tt>. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the list iterator does not * implement the <tt>set</tt> operation. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { try { ListIterator<E> e = listIterator(index); E oldVal = e.next(); e.set(element); return oldVal; } catch (NoSuchElementException exc) { throw new IndexOutOfBoundsException("Index: "+index); } } /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). * * <p>This implementation first gets a list iterator pointing to the * indexed element (with <tt>listIterator(index)</tt>). Then, it * inserts the specified element with <tt>ListIterator.add</tt>. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the list iterator does not * implement the <tt>add</tt> operation. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { try { listIterator(index).add(element); } catch (NoSuchElementException exc) { throw new IndexOutOfBoundsException("Index: "+index); } } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * * <p>This implementation first gets a list iterator pointing to the * indexed element (with <tt>listIterator(index)</tt>). Then, it removes * the element with <tt>ListIterator.remove</tt>. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the list iterator does not * implement the <tt>remove</tt> operation. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { try { ListIterator<E> e = listIterator(index); E outCast = e.next(); e.remove(); return outCast; } catch (NoSuchElementException exc) { throw new IndexOutOfBoundsException("Index: "+index); } } // Bulk Operations /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified collection into this * list at the specified position (optional operation). Shifts the * element currently at that position (if any) and any subsequent * elements to the right (increases their indices). The new elements * will appear in this list in the order that they are returned by the * specified collection's iterator. The behavior of this operation is * undefined if the specified collection is modified while the * operation is in progress. (Note that this will occur if the specified * collection is this list, and it's nonempty.) * * <p>This implementation gets an iterator over the specified collection and * a list iterator over this list pointing to the indexed element (with * <tt>listIterator(index)</tt>). Then, it iterates over the specified * collection, inserting the elements obtained from the iterator into this * list, one at a time, using <tt>ListIterator.add</tt> followed by * <tt>ListIterator.next</tt> (to skip over the added element). * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the list iterator returned by * the <tt>listIterator</tt> method does not implement the <tt>add</tt> * operation. * {@description.close} * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ public boolean addAll(int index, Collection<? extends E> c) { try { boolean modified = false; ListIterator<E> e1 = listIterator(index); Iterator<? extends E> e2 = c.iterator(); while (e2.hasNext()) { e1.add(e2.next()); modified = true; } return modified; } catch (NoSuchElementException exc) { throw new IndexOutOfBoundsException("Index: "+index); } } // Iterators /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list (in proper * sequence).<p> * * This implementation merely returns a list iterator over the list. * {@description.close} * * @return an iterator over the elements in this list (in proper sequence) */ public Iterator<E> iterator() { return listIterator(); } /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence). * {@description.close} * * @param index index of first element to be returned from the list * iterator (by a call to the <code>next</code> method) * @return a list iterator over the elements in this list (in proper * sequence) * @throws IndexOutOfBoundsException {@inheritDoc} */ public abstract ListIterator<E> listIterator(int index); }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An ordered collection (also known as a <i>sequence</i>). The user of this * interface has precise control over where in the list each element is * inserted. The user can access elements by their integer index (position in * the list), and search for elements in the list.<p> * * Unlike sets, lists typically allow duplicate elements. More formally, * lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt> * such that <tt>e1.equals(e2)</tt>, and they typically allow multiple * null elements if they allow null elements at all. It is not inconceivable * that someone might wish to implement a list that prohibits duplicates, by * throwing runtime exceptions when the user attempts to insert them, but we * expect this usage to be rare.<p> * * The <tt>List</tt> interface places additional stipulations, beyond those * specified in the <tt>Collection</tt> interface, on the contracts of the * <tt>iterator</tt>, <tt>add</tt>, <tt>remove</tt>, <tt>equals</tt>, and * <tt>hashCode</tt> methods. Declarations for other inherited methods are * also included here for convenience.<p> * * The <tt>List</tt> interface provides four methods for positional (indexed) * access to list elements. Lists (like Java arrays) are zero based. Note * that these operations may execute in time proportional to the index value * for some implementations (the <tt>LinkedList</tt> class, for * example). Thus, iterating over the elements in a list is typically * preferable to indexing through it if the caller does not know the * implementation.<p> * * The <tt>List</tt> interface provides a special iterator, called a * <tt>ListIterator</tt>, that allows element insertion and replacement, and * bidirectional access in addition to the normal operations that the * <tt>Iterator</tt> interface provides. A method is provided to obtain a * list iterator that starts at a specified position in the list.<p> * * The <tt>List</tt> interface provides two methods to search for a specified * object. From a performance standpoint, these methods should be used with * caution. In many implementations they will perform costly linear * searches.<p> * * The <tt>List</tt> interface provides two methods to efficiently insert and * remove multiple elements at an arbitrary point in the list.<p> * * Note: While it is permissible for lists to contain themselves as elements, * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt> * methods are no longer well defined on such a list. * * <p>Some list implementations have restrictions on the elements that * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * to query the presence of an ineligible element may throw an exception, * or it may simply return false; some implementations will exhibit the former * behavior and some will exhibit the latter. More generally, attempting an * operation on an ineligible element whose completion would not result in * the insertion of an ineligible element into the list may throw an * exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see ArrayList * @see LinkedList * @see Vector * @see Arrays#asList(Object[]) * @see Collections#nCopies(int, Object) * @see Collections#EMPTY_LIST * @see AbstractList * @see AbstractSequentialList * @since 1.2 */ public interface List<E> extends Collection<E> { // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of elements in this list. If this list contains * more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * {@description.close} * * @return the number of elements in this list */ int size(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains no elements. * {@description.close} * * @return <tt>true</tt> if this list contains no elements */ boolean isEmpty(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional) * @throws NullPointerException if the specified element is null and this * list does not permit null elements (optional) */ boolean contains(Object o); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list in proper sequence. * {@description.close} * * @return an iterator over the elements in this list in proper sequence */ Iterator<E> iterator(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list in proper * sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must * allocate a new array even if this list is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this list in proper * sequence * @see Arrays#asList(Object[]) */ Object[] toArray(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <p>If the list fits in the specified array with room to spare (i.e., * the array has more elements than the list), the element in the array * immediately following the end of the list is set to <tt>null</tt>. * (This is useful in determining the length of the list <i>only</i> if * the caller knows that the list does not contain any null elements.) * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of this list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of this list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ <T> T[] toArray(T[] a); // Modification Operations /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list (optional * operation). * * <p>Lists that support this operation may place limitations on what * elements may be added to this list. In particular, some * lists will refuse to add null elements, and others will impose * restrictions on the type of elements that may be added. List * classes should clearly specify in their documentation any restrictions * on what elements may be added. * {@description.close} * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and this * list does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this list */ boolean add(E e); /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this list, * if it is present (optional operation). If this list does not contain * the element, it is unchanged. More formally, removes the element with * the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list changed * as a result of the call). * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional) * @throws NullPointerException if the specified element is null and this * list does not permit null elements (optional) * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this list */ boolean remove(Object o); // Bulk Modification Operations /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains all of the elements of the * specified collection. * {@description.close} * * @param c collection to be checked for containment in this list * @return <tt>true</tt> if this list contains all of the elements of the * specified collection * @throws ClassCastException if the types of one or more elements * in the specified collection are incompatible with this * list (optional) * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not permit null * elements (optional), or if the specified collection is null * @see #contains(Object) */ boolean containsAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the specified * collection's iterator (optional operation). * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this * operation is undefined if the specified collection is modified while * the operation is in progress. (Note that this will occur if the * specified collection is this list, and it's nonempty.) * {@property.close} * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this list * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not permit null * elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this list * @see #add(Object) */ boolean addAll(Collection<? extends E> c); /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified collection into this * list at the specified position (optional operation). Shifts the * element currently at that position (if any) and any subsequent * elements to the right (increases their indices). The new elements * will appear in this list in the order that they are returned by the * specified collection's iterator. * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is * undefined if the specified collection is modified while the * operation is in progress. (Note that this will occur if the specified * collection is this list, and it's nonempty.) * {@property.close} * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this list * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not permit null * elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this list * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt; size()</tt>) */ boolean addAll(int index, Collection<? extends E> c); /** {@collect.stats} * {@description.open} * Removes from this list all of its elements that are contained in the * specified collection (optional operation). * {@description.close} * * @param c collection containing elements to be removed from this list * @return <tt>true</tt> if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean removeAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Retains only the elements in this list that are contained in the * specified collection (optional operation). In other words, removes * from this list all of its elements that are not contained in the * specified collection. * {@description.close} * * @param c collection containing elements to be retained in this list * @return <tt>true</tt> if this list changed as a result of the call * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean retainAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Removes all of the elements from this list (optional operation). * The list will be empty after this call returns. * {@description.close} * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * is not supported by this list */ void clear(); // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this list for equality. Returns * <tt>true</tt> if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and * <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null : * e1.equals(e2))</tt>.) In other words, two lists are defined to be * equal if they contain the same elements in the same order. This * definition ensures that the equals method works properly across * different implementations of the <tt>List</tt> interface. * {@description.close} * * @param o the object to be compared for equality with this list * @return <tt>true</tt> if the specified object is equal to this list */ boolean equals(Object o); /** {@collect.stats} * {@description.open} * Returns the hash code value for this list. The hash code of a list * is defined to be the result of the following calculation: * <pre> * int hashCode = 1; * for (E e : list) * hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); * </pre> * This ensures that <tt>list1.equals(list2)</tt> implies that * <tt>list1.hashCode()==list2.hashCode()</tt> for any two lists, * <tt>list1</tt> and <tt>list2</tt>, as required by the general * contract of {@link Object#hashCode}. * {@description.close} * * @return the hash code value for this list * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); // Positional Access Operations /** {@collect.stats} * {@description.open} * Returns the element at the specified position in this list. * {@description.close} * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt;= size()</tt>) */ E get(int index); /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this list with the * specified element (optional operation). * {@description.close} * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws UnsupportedOperationException if the <tt>set</tt> operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and * this list does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this list * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt;= size()</tt>) */ E set(int index, E element); /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). * {@description.close} * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and * this list does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this list * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt; size()</tt>) */ void add(int index, E element); /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * {@description.close} * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this list * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &lt; 0 || index &gt;= size()</tt>) */ E remove(int index); // Search Operations /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the first occurrence of the specified element in * this list, or -1 if this list does not contain the element * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional) * @throws NullPointerException if the specified element is null and this * list does not permit null elements (optional) */ int indexOf(Object o); /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the last occurrence of the specified element in * this list, or -1 if this list does not contain the element * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional) * @throws NullPointerException if the specified element is null and this * list does not permit null elements (optional) */ int lastIndexOf(Object o); // List Iterators /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence). * {@description.close} * * @return a list iterator over the elements in this list (in proper * sequence) */ ListIterator<E> listIterator(); /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list. * The specified index indicates the first element that would be * returned by an initial call to {@link ListIterator#next next}. * An initial call to {@link ListIterator#previous previous} would * return the element with the specified index minus one. * {@description.close} * * @param index index of the first element to be returned from the * list iterator (by a call to {@link ListIterator#next next}) * @return a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list * @throws IndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) */ ListIterator<E> listIterator(int index); // View /** {@collect.stats} * {@description.open} * Returns a view of the portion of this list between the specified * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. (If * <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations supported * by this list.<p> * * This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list. For example, the following idiom * removes a range of elements from a list: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for <tt>indexOf</tt> and * <tt>lastIndexOf</tt>, and all of the algorithms in the * <tt>Collections</tt> class can be applied to a subList.<p> * {@description.close} * * {@property.open formal:java.util.List_UnsynchronizedSubList} * The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list. (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * {@property.close} * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this list * @throws IndexOutOfBoundsException for an illegal endpoint index value * (<tt>fromIndex &lt; 0 || toIndex &gt; size || * fromIndex &gt; toIndex</tt>) */ List<E> subList(int fromIndex, int toIndex); }
Java
/* * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.io.Serializable; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PermissionCollection; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.text.DateFormat; import java.text.DateFormatSymbols; import sun.util.BuddhistCalendar; import sun.util.calendar.ZoneInfo; import sun.util.resources.LocaleData; /** {@collect.stats} * {@description.open} * The <code>Calendar</code> class is an abstract class that provides methods * for converting between a specific instant in time and a set of {@link * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>, * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for * manipulating the calendar fields, such as getting the date of the next * week. An instant in time can be represented by a millisecond value that is * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970 * 00:00:00.000 GMT (Gregorian). * * <p>The class also provides additional fields and methods for * implementing a concrete calendar system outside the package. Those * fields and methods are defined as <code>protected</code>. * * <p> * Like other locale-sensitive classes, <code>Calendar</code> provides a * class method, <code>getInstance</code>, for getting a generally useful * object of this type. <code>Calendar</code>'s <code>getInstance</code> method * returns a <code>Calendar</code> object whose * calendar fields have been initialized with the current date and time: * <blockquote> * <pre> * Calendar rightNow = Calendar.getInstance(); * </pre> * </blockquote> * * <p>A <code>Calendar</code> object can produce all the calendar field values * needed to implement the date-time formatting for a particular language and * calendar style (for example, Japanese-Gregorian, Japanese-Traditional). * <code>Calendar</code> defines the range of values returned by * certain calendar fields, as well as their meaning. For example, * the first month of the calendar system has value <code>MONTH == * JANUARY</code> for all calendars. Other values are defined by the * concrete subclass, such as <code>ERA</code>. See individual field * documentation and subclass documentation for details. * * <h4>Getting and Setting Calendar Field Values</h4> * * <p>The calendar field values can be set by calling the <code>set</code> * methods. Any field values set in a <code>Calendar</code> will not be * interpreted until it needs to calculate its time value (milliseconds from * the Epoch) or values of the calendar fields. Calling the * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>, * <code>add</code> and <code>roll</code> involves such calculation. * * <h4>Leniency</h4> * * <p><code>Calendar</code> has two modes for interpreting the calendar * fields, <em>lenient</em> and <em>non-lenient</em>. When a * <code>Calendar</code> is in lenient mode, it accepts a wider range of * calendar field values than it produces. When a <code>Calendar</code> * recomputes calendar field values for return by <code>get()</code>, all of * the calendar fields are normalized. For example, a lenient * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>, * <code>DAY_OF_MONTH == 32</code> as February 1. * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an * exception if there is any inconsistency in its calendar fields. For * example, a <code>GregorianCalendar</code> always produces * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A * non-lenient <code>GregorianCalendar</code> throws an exception upon * calculating its time or calendar field values if any out-of-range field * value has been set. * * <h4>First Week</h4> * * <code>Calendar</code> defines a locale-specific seven day week using two * parameters: the first day of the week and the minimal days in first week * (from 1 to 7). These numbers are taken from the locale resource data when a * <code>Calendar</code> is constructed. They may also be specified explicitly * through the methods for setting their values. * * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the * first week of the month or year as a reference point. The first week of a * month or year is defined as the earliest seven day period beginning on * <code>getFirstDayOfWeek()</code> and containing at least * <code>getMinimalDaysInFirstWeek()</code> days of that month or year. Weeks * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow * it. Note that the normalized numbering returned by <code>get()</code> may be * different. For example, a specific <code>Calendar</code> subclass may * designate the week before week 1 of a year as week <code><i>n</i></code> of * the previous year. * * <h4>Calendar Fields Resolution</h4> * * When computing a date and time from the calendar fields, there * may be insufficient information for the computation (such as only * year and month with no day of month), or there may be inconsistent * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15, * 1996 is actually a Monday). <code>Calendar</code> will resolve * calendar field values to determine the date and time in the * following way. * * <p>If there is any conflict in calendar field values, * <code>Calendar</code> gives priorities to calendar fields that have been set * more recently. The following are the default combinations of the * calendar fields. The most recent combination, as determined by the * most recently set single field, will be used. * * <p><a name="date_resolution">For the date fields</a>: * <blockquote> * <pre> * YEAR + MONTH + DAY_OF_MONTH * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK * YEAR + DAY_OF_YEAR * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR * </pre></blockquote> * * <a name="time_resolution">For the time of day fields</a>: * <blockquote> * <pre> * HOUR_OF_DAY * AM_PM + HOUR * </pre></blockquote> * * <p>If there are any calendar fields whose values haven't been set in the selected * field combination, <code>Calendar</code> uses their default values. The default * value of each field may vary by concrete calendar systems. For example, in * <code>GregorianCalendar</code>, the default of a field is the same as that * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH = * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc. * * <p> * <strong>Note:</strong> There are certain possible ambiguities in * interpretation of certain singular times, which are resolved in the * following ways: * <ol> * <li> 23:59 is the last minute of the day and 00:00 is the first * minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on * Jan 1, 2000 &lt; 00:01 on Jan 1, 2000. * * <li> Although historically not precise, midnight also belongs to "am", * and noon belongs to "pm", so on the same day, * 12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm * </ol> * * <p> * The date or time format strings are not part of the definition of a * calendar, as those must be modifiable or overridable by the user at * runtime. Use {@link DateFormat} * to format dates. * * <h4>Field Manipulation</h4> * * The calendar fields can be changed using three methods: * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p> * * <p><strong><code>set(f, value)</code></strong> changes calendar field * <code>f</code> to <code>value</code>. In addition, it sets an * internal member variable to indicate that calendar field <code>f</code> has * been changed. Although calendar field <code>f</code> is changed immediately, * the calendar's time value in milliseconds is not recomputed until the next call to * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>, * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to * <code>set()</code> do not trigger multiple, unnecessary * computations. As a result of changing a calendar field using * <code>set()</code>, other calendar fields may also change, depending on the * calendar field, the calendar field value, and the calendar system. In addition, * <code>get(f)</code> will not necessarily return <code>value</code> set by * the call to the <code>set</code> method * after the calendar fields have been recomputed. The specifics are determined by * the concrete calendar class.</p> * * <p><em>Example</em>: Consider a <code>GregorianCalendar</code> * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH, * Calendar.SEPTEMBER)</code> sets the date to September 31, * 1999. This is a temporary internal representation that resolves to * October 1, 1999 if <code>getTime()</code>is then called. However, a * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to * <code>getTime()</code> sets the date to September 30, 1999, since * no recomputation occurs after <code>set()</code> itself.</p> * * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code> * to field <code>f</code>. This is equivalent to calling <code>set(f, * get(f) + delta)</code> with two adjustments:</p> * * <blockquote> * <p><strong>Add rule 1</strong>. The value of field <code>f</code> * after the call minus the value of field <code>f</code> before the * call is <code>delta</code>, modulo any overflow that has occurred in * field <code>f</code>. Overflow occurs when a field value exceeds its * range and, as a result, the next larger field is incremented or * decremented and the field value is adjusted back into its range.</p> * * <p><strong>Add rule 2</strong>. If a smaller field is expected to be * invariant, but it is impossible for it to be equal to its * prior value because of changes in its minimum or maximum after field * <code>f</code> is changed or other constraints, such as time zone * offset changes, then its value is adjusted to be as close * as possible to its expected value. A smaller field represents a * smaller unit of time. <code>HOUR</code> is a smaller field than * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields * that are not expected to be invariant. The calendar system * determines what fields are expected to be invariant.</p> * </blockquote> * * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces * an immediate recomputation of the calendar's milliseconds and all * fields.</p> * * <p><em>Example</em>: Consider a <code>GregorianCalendar</code> * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH, * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule * 1</strong> sets the <code>MONTH</code> field to September, since * adding 13 months to August gives September of the next year. Since * <code>DAY_OF_MONTH</code> cannot be 31 in September in a * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by * rule 2, since it is expected to change when the month changes in a * <code>GregorianCalendar</code>.</p> * * <p><strong><code>roll(f, delta)</code></strong> adds * <code>delta</code> to field <code>f</code> without changing larger * fields. This is equivalent to calling <code>add(f, delta)</code> with * the following adjustment:</p> * * <blockquote> * <p><strong>Roll rule</strong>. Larger fields are unchanged after the * call. A larger field represents a larger unit of * time. <code>DAY_OF_MONTH</code> is a larger field than * <code>HOUR</code>.</p> * </blockquote> * * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}. * * <p><strong>Usage model</strong>. To motivate the behavior of * <code>add()</code> and <code>roll()</code>, consider a user interface * component with increment and decrement buttons for the month, day, and * year, and an underlying <code>GregorianCalendar</code>. If the * interface reads January 31, 1999 and the user presses the month * increment button, what should it read? If the underlying * implementation uses <code>set()</code>, it might read March 3, 1999. A * better result would be February 28, 1999. Furthermore, if the user * presses the month increment button again, it should read March 31, * 1999, not March 28, 1999. By saving the original date and using either * <code>add()</code> or <code>roll()</code>, depending on whether larger * fields should be affected, the user interface can behave as most users * will intuitively expect.</p> * {@description.close} * * @see java.lang.System#currentTimeMillis() * @see Date * @see GregorianCalendar * @see TimeZone * @see java.text.DateFormat * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu * @since JDK1.1 */ public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> { // Data flow in Calendar // --------------------- // The current time is represented in two ways by Calendar: as UTC // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the // millis from the fields, and vice versa. The data needed to do this // conversion is encapsulated by a TimeZone object owned by the Calendar. // The data provided by the TimeZone object may also be overridden if the // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class // keeps track of what information was most recently set by the caller, and // uses that to compute any other information as needed. // If the user sets the fields using set(), the data flow is as follows. // This is implemented by the Calendar subclass's computeTime() method. // During this process, certain fields may be ignored. The disambiguation // algorithm for resolving which fields to pay attention to is described // in the class documentation. // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) // | // | Using Calendar-specific algorithm // V // local standard millis // | // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET // V // UTC millis (in time data member) // If the user sets the UTC millis using setTime() or setTimeInMillis(), // the data flow is as follows. This is implemented by the Calendar // subclass's computeFields() method. // UTC millis (in time data member) // | // | Using TimeZone getOffset() // V // local standard millis // | // | Using Calendar-specific algorithm // V // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.) // In general, a round trip from fields, through local and UTC millis, and // back out to fields is made when necessary. This is implemented by the // complete() method. Resolving a partial set of fields into a UTC millis // value allows all remaining fields to be generated from that value. If // the Calendar is lenient, the fields are also renormalized to standard // ranges when they are regenerated. /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific * value; see subclass documentation. * {@description.close} * * @see GregorianCalendar#AD * @see GregorianCalendar#BC */ public final static int ERA = 0; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * year. This is a calendar-specific value; see subclass documentation. * {@description.close} */ public final static int YEAR = 1; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * month. This is a calendar-specific value. The first month of * the year in the Gregorian and Julian calendars is * <code>JANUARY</code> which is 0; the last depends on the number * of months in a year. * {@description.close} * * @see #JANUARY * @see #FEBRUARY * @see #MARCH * @see #APRIL * @see #MAY * @see #JUNE * @see #JULY * @see #AUGUST * @see #SEPTEMBER * @see #OCTOBER * @see #NOVEMBER * @see #DECEMBER * @see #UNDECIMBER */ public final static int MONTH = 2; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * week number within the current year. The first week of the year, as * defined by <code>getFirstDayOfWeek()</code> and * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define * the value of <code>WEEK_OF_YEAR</code> for days before the first week of * the year. * {@description.close} * * @see #getFirstDayOfWeek * @see #getMinimalDaysInFirstWeek */ public final static int WEEK_OF_YEAR = 3; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * week number within the current month. The first week of the month, as * defined by <code>getFirstDayOfWeek()</code> and * <code>getMinimalDaysInFirstWeek()</code>, has value 1. Subclasses define * the value of <code>WEEK_OF_MONTH</code> for days before the first week of * the month. * {@description.close} * * @see #getFirstDayOfWeek * @see #getMinimalDaysInFirstWeek */ public final static int WEEK_OF_MONTH = 4; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>. * The first day of the month has value 1. * {@description.close} * * @see #DAY_OF_MONTH */ public final static int DATE = 5; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * day of the month. This is a synonym for <code>DATE</code>. * The first day of the month has value 1. * {@description.close} * * @see #DATE */ public final static int DAY_OF_MONTH = 5; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the day * number within the current year. The first day of the year has value 1. * {@description.close} */ public final static int DAY_OF_YEAR = 6; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the day * of the week. This field takes values <code>SUNDAY</code>, * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>, * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>. * {@description.close} * * @see #SUNDAY * @see #MONDAY * @see #TUESDAY * @see #WEDNESDAY * @see #THURSDAY * @see #FRIDAY * @see #SATURDAY */ public final static int DAY_OF_WEEK = 7; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * ordinal number of the day of the week within the current month. Together * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day * within a month. Unlike <code>WEEK_OF_MONTH</code> and * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on * <code>getFirstDayOfWeek()</code> or * <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code> * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH * 1</code>; <code>8</code> through <code>14</code> correspond to * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on. * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before * <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the * end of the month, so the last Sunday of a month is specified as * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because * negative values count backward they will usually be aligned differently * within the month than positive values. For example, if a month has 31 * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>. * {@description.close} * * @see #DAY_OF_WEEK * @see #WEEK_OF_MONTH */ public final static int DAY_OF_WEEK_IN_MONTH = 8; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating * whether the <code>HOUR</code> is before or after noon. * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>. * {@description.close} * * @see #AM * @see #PM * @see #HOUR */ public final static int AM_PM = 9; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * hour of the morning or afternoon. <code>HOUR</code> is used for the * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10. * {@description.close} * * @see #AM_PM * @see #HOUR_OF_DAY */ public final static int HOUR = 10; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock. * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22. * {@description.close} * * @see #HOUR */ public final static int HOUR_OF_DAY = 11; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * minute within the hour. * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4. * {@description.close} */ public final static int MINUTE = 12; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * second within the minute. * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15. * {@description.close} */ public final static int SECOND = 13; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * millisecond within the second. * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250. * {@description.close} */ public final static int MILLISECOND = 14; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> * indicating the raw offset from GMT in milliseconds. * <p> * This field reflects the correct GMT offset value of the time * zone of this <code>Calendar</code> if the * <code>TimeZone</code> implementation subclass supports * historical GMT offset changes. * {@description.close} */ public final static int ZONE_OFFSET = 15; /** {@collect.stats} * {@description.open} * Field number for <code>get</code> and <code>set</code> indicating the * daylight savings offset in milliseconds. * <p> * This field reflects the correct daylight saving offset value of * the time zone of this <code>Calendar</code> if the * <code>TimeZone</code> implementation subclass supports * historical Daylight Saving Time schedule changes. * {@description.close} */ public final static int DST_OFFSET = 16; /** {@collect.stats} * {@description.open} * The number of distinct fields recognized by <code>get</code> and <code>set</code>. * Field numbers range from <code>0..FIELD_COUNT-1</code>. * {@description.close} */ public final static int FIELD_COUNT = 17; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Sunday. * {@description.close} */ public final static int SUNDAY = 1; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Monday. * {@description.close} */ public final static int MONDAY = 2; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Tuesday. * {@description.close} */ public final static int TUESDAY = 3; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Wednesday. * {@description.close} */ public final static int WEDNESDAY = 4; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Thursday. * {@description.close} */ public final static int THURSDAY = 5; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Friday. * {@description.close} */ public final static int FRIDAY = 6; /** {@collect.stats} * {@description.open} * Value of the {@link #DAY_OF_WEEK} field indicating * Saturday. * {@description.close} */ public final static int SATURDAY = 7; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * first month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int JANUARY = 0; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * second month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int FEBRUARY = 1; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * third month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int MARCH = 2; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * fourth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int APRIL = 3; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * fifth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int MAY = 4; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * sixth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int JUNE = 5; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * seventh month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int JULY = 6; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * eighth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int AUGUST = 7; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * ninth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int SEPTEMBER = 8; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * tenth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int OCTOBER = 9; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * eleventh month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int NOVEMBER = 10; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * twelfth month of the year in the Gregorian and Julian calendars. * {@description.close} */ public final static int DECEMBER = 11; /** {@collect.stats} * {@description.open} * Value of the {@link #MONTH} field indicating the * thirteenth month of the year. Although <code>GregorianCalendar</code> * does not use this value, lunar calendars do. * {@description.close} */ public final static int UNDECIMBER = 12; /** {@collect.stats} * {@description.open} * Value of the {@link #AM_PM} field indicating the * period of the day from midnight to just before noon. * {@description.close} */ public final static int AM = 0; /** {@collect.stats} * {@description.open} * Value of the {@link #AM_PM} field indicating the * period of the day from noon to just before midnight. * {@description.close} */ public final static int PM = 1; /** {@collect.stats} * {@description.open} * A style specifier for {@link #getDisplayNames(int, int, Locale) * getDisplayNames} indicating names in all styles, such as * "January" and "Jan". * {@description.close} * * @see #SHORT * @see #LONG * @since 1.6 */ public static final int ALL_STYLES = 0; /** {@collect.stats} * {@description.open} * A style specifier for {@link #getDisplayName(int, int, Locale) * getDisplayName} and {@link #getDisplayNames(int, int, Locale) * getDisplayNames} indicating a short name, such as "Jan". * {@description.close} * * @see #LONG * @since 1.6 */ public static final int SHORT = 1; /** {@collect.stats} * {@description.open} * A style specifier for {@link #getDisplayName(int, int, Locale) * getDisplayName} and {@link #getDisplayNames(int, int, Locale) * getDisplayNames} indicating a long name, such as "January". * {@description.close} * * @see #SHORT * @since 1.6 */ public static final int LONG = 2; // Internal notes: // Calendar contains two kinds of time representations: current "time" in // milliseconds, and a set of calendar "fields" representing the current time. // The two representations are usually in sync, but can get out of sync // as follows. // 1. Initially, no fields are set, and the time is invalid. // 2. If the time is set, all fields are computed and in sync. // 3. If a single field is set, the time is invalid. // Recomputation of the time and fields happens when the object needs // to return a result to the user, or use a result for a computation. /** {@collect.stats} * {@description.open} * The calendar field values for the currently set time for this calendar. * This is an array of <code>FIELD_COUNT</code> integers, with index values * <code>ERA</code> through <code>DST_OFFSET</code>. * {@description.close} * @serial */ protected int fields[]; /** {@collect.stats} * {@description.open} * The flags which tell if a specified calendar field for the calendar is set. * A new object has no fields set. After the first call to a method * which generates the fields, they all remain set after that. * This is an array of <code>FIELD_COUNT</code> booleans, with index values * <code>ERA</code> through <code>DST_OFFSET</code>. * {@description.close} * @serial */ protected boolean isSet[]; /** {@collect.stats} * {@description.open} * Pseudo-time-stamps which specify when each field was set. There * are two special values, UNSET and COMPUTED. Values from * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values. * {@description.close} */ transient private int stamp[]; /** {@collect.stats} * {@description.open} * The currently set time for this calendar, expressed in milliseconds after * January 1, 1970, 0:00:00 GMT. * {@description.close} * @see #isTimeSet * @serial */ protected long time; /** {@collect.stats} * {@description.open} * True if then the value of <code>time</code> is valid. * The time is made invalid by a change to an item of <code>field[]</code>. * {@description.close} * @see #time * @serial */ protected boolean isTimeSet; /** {@collect.stats} * {@description.open} * True if <code>fields[]</code> are in sync with the currently set time. * If false, then the next attempt to get the value of a field will * force a recomputation of all fields from the current value of * <code>time</code>. * {@description.close} * @serial */ protected boolean areFieldsSet; /** {@collect.stats} * {@description.open} * True if all fields have been set. * {@description.close} * @serial */ transient boolean areAllFieldsSet; /** {@collect.stats} * {@description.open} * <code>True</code> if this calendar allows out-of-range field values during computation * of <code>time</code> from <code>fields[]</code>. * {@description.close} * @see #setLenient * @see #isLenient * @serial */ private boolean lenient = true; /** {@collect.stats} * {@description.open} * The <code>TimeZone</code> used by this calendar. <code>Calendar</code> * uses the time zone data to translate between locale and GMT time. * {@description.close} * @serial */ private TimeZone zone; /** {@collect.stats} * {@description.open} * <code>True</code> if zone references to a shared TimeZone object. * {@description.close} */ transient private boolean sharedZone = false; /** {@collect.stats} * {@description.open} * The first day of the week, with possible values <code>SUNDAY</code>, * <code>MONDAY</code>, etc. This is a locale-dependent value. * {@description.close} * @serial */ private int firstDayOfWeek; /** {@collect.stats} * {@description.open} * The number of days required for the first week in a month or year, * with possible values from 1 to 7. This is a locale-dependent value. * {@description.close} * @serial */ private int minimalDaysInFirstWeek; /** {@collect.stats} * {@description.open} * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek * of a Locale. * {@description.close} */ private static Hashtable<Locale, int[]> cachedLocaleData = new Hashtable<Locale, int[]>(3); // Special values of stamp[] /** {@collect.stats} * {@description.open} * The corresponding fields[] has no value. * {@description.close} */ private static final int UNSET = 0; /** {@collect.stats} * {@description.open} * The value of the corresponding fields[] has been calculated internally. * {@description.close} */ private static final int COMPUTED = 1; /** {@collect.stats} * {@description.open} * The value of the corresponding fields[] has been set externally. Stamp * values which are greater than 1 represents the (pseudo) time when the * corresponding fields[] value was set. * {@description.close} */ private static final int MINIMUM_USER_STAMP = 2; /** {@collect.stats} * {@description.open} * The mask value that represents all of the fields. * {@description.close} */ static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1; /** {@collect.stats} * {@description.open} * The next available value for <code>stamp[]</code>, an internal array. * This actually should not be written out to the stream, and will probably * be removed from the stream in the near future. In the meantime, * a value of <code>MINIMUM_USER_STAMP</code> should be used. * {@description.close} * @serial */ private int nextStamp = MINIMUM_USER_STAMP; // the internal serial version which says which version was written // - 0 (default) for version up to JDK 1.1.5 // - 1 for version from JDK 1.1.6, which writes a correct 'time' value // as well as compatible values for other fields. This is a // transitional format. // - 2 (not implemented yet) a future version, in which fields[], // areFieldsSet, and isTimeSet become transient, and isSet[] is // removed. In JDK 1.1.6 we write a format compatible with version 2. static final int currentSerialVersion = 1; /** {@collect.stats} * {@description.open} * The version of the serialized data on the stream. Possible values: * <dl> * <dt><b>0</b> or not present on stream</dt> * <dd> * JDK 1.1.5 or earlier. * </dd> * <dt><b>1</b></dt> * <dd> * JDK 1.1.6 or later. Writes a correct 'time' value * as well as compatible values for other fields. This is a * transitional format. * </dd> * </dl> * When streaming out this class, the most recent format * and the highest allowable <code>serialVersionOnStream</code> * is written. * {@description.close} * @serial * @since JDK1.1.6 */ private int serialVersionOnStream = currentSerialVersion; // Proclaim serialization compatibility with JDK 1.1 static final long serialVersionUID = -1807547505821590642L; // Mask values for calendar fields final static int ERA_MASK = (1 << ERA); final static int YEAR_MASK = (1 << YEAR); final static int MONTH_MASK = (1 << MONTH); final static int WEEK_OF_YEAR_MASK = (1 << WEEK_OF_YEAR); final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH); final static int DAY_OF_MONTH_MASK = (1 << DAY_OF_MONTH); final static int DATE_MASK = DAY_OF_MONTH_MASK; final static int DAY_OF_YEAR_MASK = (1 << DAY_OF_YEAR); final static int DAY_OF_WEEK_MASK = (1 << DAY_OF_WEEK); final static int DAY_OF_WEEK_IN_MONTH_MASK = (1 << DAY_OF_WEEK_IN_MONTH); final static int AM_PM_MASK = (1 << AM_PM); final static int HOUR_MASK = (1 << HOUR); final static int HOUR_OF_DAY_MASK = (1 << HOUR_OF_DAY); final static int MINUTE_MASK = (1 << MINUTE); final static int SECOND_MASK = (1 << SECOND); final static int MILLISECOND_MASK = (1 << MILLISECOND); final static int ZONE_OFFSET_MASK = (1 << ZONE_OFFSET); final static int DST_OFFSET_MASK = (1 << DST_OFFSET); /** {@collect.stats} * {@description.open} * Constructs a Calendar with the default time zone * and locale. * {@description.close} * @see TimeZone#getDefault */ protected Calendar() { this(TimeZone.getDefaultRef(), Locale.getDefault()); sharedZone = true; } /** {@collect.stats} * {@description.open} * Constructs a calendar with the specified time zone and locale. * {@description.close} * * @param zone the time zone to use * @param aLocale the locale for the week data */ protected Calendar(TimeZone zone, Locale aLocale) { fields = new int[FIELD_COUNT]; isSet = new boolean[FIELD_COUNT]; stamp = new int[FIELD_COUNT]; this.zone = zone; setWeekCountData(aLocale); } /** {@collect.stats} * {@description.open} * Gets a calendar using the default time zone and locale. The * <code>Calendar</code> returned is based on the current time * in the default time zone with the default locale. * {@description.close} * * @return a Calendar. */ public static Calendar getInstance() { Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault()); cal.sharedZone = true; return cal; } /** {@collect.stats} * {@description.open} * Gets a calendar using the specified time zone and default locale. * The <code>Calendar</code> returned is based on the current time * in the given time zone with the default locale. * {@description.close} * * @param zone the time zone to use * @return a Calendar. */ public static Calendar getInstance(TimeZone zone) { return createCalendar(zone, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Gets a calendar using the default time zone and specified locale. * The <code>Calendar</code> returned is based on the current time * in the default time zone with the given locale. * {@description.close} * * @param aLocale the locale for the week data * @return a Calendar. */ public static Calendar getInstance(Locale aLocale) { Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale); cal.sharedZone = true; return cal; } /** {@collect.stats} * {@description.open} * Gets a calendar with the specified time zone and locale. * The <code>Calendar</code> returned is based on the current time * in the given time zone with the given locale. * {@description.close} * * @param zone the time zone to use * @param aLocale the locale for the week data * @return a Calendar. */ public static Calendar getInstance(TimeZone zone, Locale aLocale) { return createCalendar(zone, aLocale); } private static Calendar createCalendar(TimeZone zone, Locale aLocale) { // If the specified locale is a Thai locale, returns a BuddhistCalendar // instance. if ("th".equals(aLocale.getLanguage()) && ("TH".equals(aLocale.getCountry()))) { return new sun.util.BuddhistCalendar(zone, aLocale); } else if ("JP".equals(aLocale.getVariant()) && "JP".equals(aLocale.getCountry()) && "ja".equals(aLocale.getLanguage())) { return new JapaneseImperialCalendar(zone, aLocale); } // else create the default calendar return new GregorianCalendar(zone, aLocale); } /** {@collect.stats} * {@description.open} * Returns an array of all locales for which the <code>getInstance</code> * methods of this class can return localized instances. * The array returned must contain at least a <code>Locale</code> * instance equal to {@link java.util.Locale#US Locale.US}. * {@description.close} * * @return An array of locales for which localized * <code>Calendar</code> instances are available. */ public static synchronized Locale[] getAvailableLocales() { return DateFormat.getAvailableLocales(); } /** {@collect.stats} * {@description.open} * Converts the current calendar field values in {@link #fields fields[]} * to the millisecond time value * {@link #time}. * {@description.close} * * @see #complete() * @see #computeFields() */ protected abstract void computeTime(); /** {@collect.stats} * {@description.open} * Converts the current millisecond time value {@link #time} * to calendar field values in {@link #fields fields[]}. * This allows you to sync up the calendar field values with * a new time that is set for the calendar. * {@description.close} * {@property.open internal} * The time is <em>not</em> * recomputed first; to recompute the time, then the fields, call the * {@link #complete()} method. * {@property.close} * * @see #computeTime() */ protected abstract void computeFields(); /** {@collect.stats} * {@description.open} * Returns a <code>Date</code> object representing this * <code>Calendar</code>'s time value (millisecond offset from the <a * href="#Epoch">Epoch</a>"). * {@description.close} * * @return a <code>Date</code> representing the time value. * @see #setTime(Date) * @see #getTimeInMillis() */ public final Date getTime() { return new Date(getTimeInMillis()); } /** {@collect.stats} * {@description.open} * Sets this Calendar's time with the given <code>Date</code>. * <p> * Note: Calling <code>setTime()</code> with * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code> * may yield incorrect field values from <code>get()</code>. * {@description.close} * * @param date the given Date. * @see #getTime() * @see #setTimeInMillis(long) */ public final void setTime(Date date) { setTimeInMillis(date.getTime()); } /** {@collect.stats} * {@description.open} * Returns this Calendar's time value in milliseconds. * {@description.close} * * @return the current time as UTC milliseconds from the epoch. * @see #getTime() * @see #setTimeInMillis(long) */ public long getTimeInMillis() { if (!isTimeSet) { updateTime(); } return time; } /** {@collect.stats} * {@description.open} * Sets this Calendar's current time from the given long value. * {@description.close} * * @param millis the new time in UTC milliseconds from the epoch. * @see #setTime(Date) * @see #getTimeInMillis() */ public void setTimeInMillis(long millis) { // If we don't need to recalculate the calendar field values, // do nothing. if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) { return; } time = millis; isTimeSet = true; areFieldsSet = false; computeFields(); areAllFieldsSet = areFieldsSet = true; } /** {@collect.stats} * {@description.open} * Returns the value of the given calendar field. In lenient mode, * all calendar fields are normalized. In non-lenient mode, all * calendar fields are validated and this method throws an * exception if any calendar fields have out-of-range values. The * normalization and validation are handled by the * {@link #complete()} method, which process is calendar * system dependent. * {@description.close} * * @param field the given calendar field. * @return the value for the given calendar field. * @throws ArrayIndexOutOfBoundsException if the specified field is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * @see #set(int,int) * @see #complete() */ public int get(int field) { complete(); return internalGet(field); } /** {@collect.stats} * {@description.open} * Returns the value of the given calendar field. This method does * not involve normalization or validation of the field value. * {@description.close} * * @param field the given calendar field. * @return the value for the given calendar field. * @see #get(int) */ protected final int internalGet(int field) { return fields[field]; } /** {@collect.stats} * {@description.open} * Sets the value of the given calendar field. This method does * not affect any setting state of the field in this * <code>Calendar</code> instance. * {@description.close} * * @throws IndexOutOfBoundsException if the specified field is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * @see #areFieldsSet * @see #isTimeSet * @see #areAllFieldsSet * @see #set(int,int) */ final void internalSet(int field, int value) { fields[field] = value; } /** {@collect.stats} * {@description.open} * Sets the given calendar field to the given value. The value is not * interpreted by this method regardless of the leniency mode. * {@description.close} * * @param field the given calendar field. * @param value the value to be set for the given calendar field. * @throws ArrayIndexOutOfBoundsException if the specified field is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * in non-lenient mode. * @see #set(int,int,int) * @see #set(int,int,int,int,int) * @see #set(int,int,int,int,int,int) * @see #get(int) */ public void set(int field, int value) { if (isLenient() && areFieldsSet && !areAllFieldsSet) { computeFields(); } internalSet(field, value); isTimeSet = false; areFieldsSet = false; isSet[field] = true; stamp[field] = nextStamp++; if (nextStamp == Integer.MAX_VALUE) { adjustStamp(); } } /** {@collect.stats} * {@description.open} * Sets the values for the calendar fields <code>YEAR</code>, * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>. * Previous values of other calendar fields are retained. If this is not desired, * call {@link #clear()} first. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field. * @param month the value used to set the <code>MONTH</code> calendar field. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. * @see #set(int,int) * @see #set(int,int,int,int,int) * @see #set(int,int,int,int,int,int) */ public final void set(int year, int month, int date) { set(YEAR, year); set(MONTH, month); set(DATE, date); } /** {@collect.stats} * {@description.open} * Sets the values for the calendar fields <code>YEAR</code>, * <code>MONTH</code>, <code>DAY_OF_MONTH</code>, * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>. * Previous values of other fields are retained. If this is not desired, * call {@link #clear()} first. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field. * @param month the value used to set the <code>MONTH</code> calendar field. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field. * @param minute the value used to set the <code>MINUTE</code> calendar field. * @see #set(int,int) * @see #set(int,int,int) * @see #set(int,int,int,int,int,int) */ public final void set(int year, int month, int date, int hourOfDay, int minute) { set(YEAR, year); set(MONTH, month); set(DATE, date); set(HOUR_OF_DAY, hourOfDay); set(MINUTE, minute); } /** {@collect.stats} * {@description.open} * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>, * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and * <code>SECOND</code>. * Previous values of other fields are retained. If this is not desired, * call {@link #clear()} first. * {@description.close} * * @param year the value used to set the <code>YEAR</code> calendar field. * @param month the value used to set the <code>MONTH</code> calendar field. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field. * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field. * @param minute the value used to set the <code>MINUTE</code> calendar field. * @param second the value used to set the <code>SECOND</code> calendar field. * @see #set(int,int) * @see #set(int,int,int) * @see #set(int,int,int,int,int) */ public final void set(int year, int month, int date, int hourOfDay, int minute, int second) { set(YEAR, year); set(MONTH, month); set(DATE, date); set(HOUR_OF_DAY, hourOfDay); set(MINUTE, minute); set(SECOND, second); } /** {@collect.stats} * {@description.open} * Sets all the calendar field values and the time value * (millisecond offset from the <a href="#Epoch">Epoch</a>) of * this <code>Calendar</code> undefined. This means that {@link * #isSet(int) isSet()} will return <code>false</code> for all the * calendar fields, and the date and time calculations will treat * the fields as if they had never been set. A * <code>Calendar</code> implementation class may use its specific * default field values for date/time calculations. For example, * <code>GregorianCalendar</code> uses 1970 if the * <code>YEAR</code> field value is undefined. * {@description.close} * * @see #clear(int) */ public final void clear() { for (int i = 0; i < fields.length; ) { stamp[i] = fields[i] = 0; // UNSET == 0 isSet[i++] = false; } areAllFieldsSet = areFieldsSet = false; isTimeSet = false; } /** {@collect.stats} * {@description.open} * Sets the given calendar field value and the time value * (millisecond offset from the <a href="#Epoch">Epoch</a>) of * this <code>Calendar</code> undefined. This means that {@link * #isSet(int) isSet(field)} will return <code>false</code>, and * the date and time calculations will treat the field as if it * had never been set. A <code>Calendar</code> implementation * class may use the field's specific default value for date and * time calculations. * * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM} * fields are handled independently and the <a * href="#time_resolution">the resolution rule for the time of * day</a> is applied. Clearing one of the fields doesn't reset * the hour of day value of this <code>Calendar</code>. Use {@link * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour * value. * {@description.close} * * @param field the calendar field to be cleared. * @see #clear() */ public final void clear(int field) { fields[field] = 0; stamp[field] = UNSET; isSet[field] = false; areAllFieldsSet = areFieldsSet = false; isTimeSet = false; } /** {@collect.stats} * {@description.open} * Determines if the given calendar field has a value set, * including cases that the value has been set by internal fields * calculations triggered by a <code>get</code> method call. * {@description.close} * * @return <code>true</code> if the given calendar field has a value set; * <code>false</code> otherwise. */ public final boolean isSet(int field) { return stamp[field] != UNSET; } /** {@collect.stats} * {@description.open} * Returns the string representation of the calendar * <code>field</code> value in the given <code>style</code> and * <code>locale</code>. If no string representation is * applicable, <code>null</code> is returned. This method calls * {@link Calendar#get(int) get(field)} to get the calendar * <code>field</code> value if the string representation is * applicable to the given calendar <code>field</code>. * * <p>For example, if this <code>Calendar</code> is a * <code>GregorianCalendar</code> and its date is 2005-01-01, then * the string representation of the {@link #MONTH} field would be * "January" in the long style in an English locale or "Jan" in * the short style. However, no string representation would be * available for the {@link #DAY_OF_MONTH} field, and this method * would return <code>null</code>. * * <p>The default implementation supports the calendar fields for * which a {@link DateFormatSymbols} has names in the given * <code>locale</code>. * {@description.close} * * @param field * the calendar field for which the string representation * is returned * @param style * the style applied to the string representation; one of * {@link #SHORT} or {@link #LONG}. * @param locale * the locale for the string representation * @return the string representation of the given * <code>field</code> in the given <code>style</code>, or * <code>null</code> if no string representation is * applicable. * @exception IllegalArgumentException * if <code>field</code> or <code>style</code> is invalid, * or if this <code>Calendar</code> is non-lenient and any * of the calendar fields have invalid values * @exception NullPointerException * if <code>locale</code> is null * @since 1.6 */ public String getDisplayName(int field, int style, Locale locale) { if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale, ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { return null; } DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); String[] strings = getFieldStrings(field, style, symbols); if (strings != null) { int fieldValue = get(field); if (fieldValue < strings.length) { return strings[fieldValue]; } } return null; } /** {@collect.stats} * {@description.open} * Returns a <code>Map</code> containing all names of the calendar * <code>field</code> in the given <code>style</code> and * <code>locale</code> and their corresponding field values. For * example, if this <code>Calendar</code> is a {@link * GregorianCalendar}, the returned map would contain "Jan" to * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the * {@linkplain #SHORT short} style in an English locale. * * <p>The values of other calendar fields may be taken into * account to determine a set of display names. For example, if * this <code>Calendar</code> is a lunisolar calendar system and * the year value given by the {@link #YEAR} field has a leap * month, this method would return month names containing the leap * month name, and month names are mapped to their values specific * for the year. * * <p>The default implementation supports display names contained in * a {@link DateFormatSymbols}. For example, if <code>field</code> * is {@link #MONTH} and <code>style</code> is {@link * #ALL_STYLES}, this method returns a <code>Map</code> containing * all strings returned by {@link DateFormatSymbols#getShortMonths()} * and {@link DateFormatSymbols#getMonths()}. * {@description.close} * * @param field * the calendar field for which the display names are returned * @param style * the style applied to the display names; one of {@link * #SHORT}, {@link #LONG}, or {@link #ALL_STYLES}. * @param locale * the locale for the display names * @return a <code>Map</code> containing all display names in * <code>style</code> and <code>locale</code> and their * field values, or <code>null</code> if no display names * are defined for <code>field</code> * @exception IllegalArgumentException * if <code>field</code> or <code>style</code> is invalid, * or if this <code>Calendar</code> is non-lenient and any * of the calendar fields have invalid values * @exception NullPointerException * if <code>locale</code> is null * @since 1.6 */ public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) { if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale, ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { return null; } // ALL_STYLES if (style == ALL_STYLES) { Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale); if (field == ERA || field == AM_PM) { return shortNames; } Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale); if (shortNames == null) { return longNames; } if (longNames != null) { shortNames.putAll(longNames); } return shortNames; } // SHORT or LONG return getDisplayNamesImpl(field, style, locale); } private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) { DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); String[] strings = getFieldStrings(field, style, symbols); if (strings != null) { Map<String,Integer> names = new HashMap<String,Integer>(); for (int i = 0; i < strings.length; i++) { if (strings[i].length() == 0) { continue; } names.put(strings[i], i); } return names; } return null; } boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle, Locale locale, int fieldMask) { if (field < 0 || field >= fields.length || style < minStyle || style > maxStyle) { throw new IllegalArgumentException(); } if (locale == null) { throw new NullPointerException(); } return isFieldSet(fieldMask, field); } private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) { String[] strings = null; switch (field) { case ERA: strings = symbols.getEras(); break; case MONTH: strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths(); break; case DAY_OF_WEEK: strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays(); break; case AM_PM: strings = symbols.getAmPmStrings(); break; } return strings; } /** {@collect.stats} * {@description.open} * Fills in any unset fields in the calendar fields. First, the {@link * #computeTime()} method is called if the time value (millisecond offset * from the <a href="#Epoch">Epoch</a>) has not been calculated from * calendar field values. Then, the {@link #computeFields()} method is * called to calculate all calendar field values. * {@description.close} */ protected void complete() { if (!isTimeSet) updateTime(); if (!areFieldsSet || !areAllFieldsSet) { computeFields(); // fills in unset fields areAllFieldsSet = areFieldsSet = true; } } /** {@collect.stats} * {@description.open} * Returns whether the value of the specified calendar field has been set * externally by calling one of the setter methods rather than by the * internal time calculation. * {@description.close} * * @return <code>true</code> if the field has been set externally, * <code>false</code> otherwise. * @exception IndexOutOfBoundsException if the specified * <code>field</code> is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * @see #selectFields() * @see #setFieldsComputed(int) */ final boolean isExternallySet(int field) { return stamp[field] >= MINIMUM_USER_STAMP; } /** {@collect.stats} * {@description.open} * Returns a field mask (bit mask) indicating all calendar fields that * have the state of externally or internally set. * {@description.close} * * @return a bit mask indicating set state fields */ final int getSetStateFields() { int mask = 0; for (int i = 0; i < fields.length; i++) { if (stamp[i] != UNSET) { mask |= 1 << i; } } return mask; } /** {@collect.stats} * {@description.open} * Sets the state of the specified calendar fields to * <em>computed</em>. This state means that the specified calendar fields * have valid values that have been set by internal time calculation * rather than by calling one of the setter methods. * {@description.close} * * @param fieldMask the field to be marked as computed. * @exception IndexOutOfBoundsException if the specified * <code>field</code> is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * @see #isExternallySet(int) * @see #selectFields() */ final void setFieldsComputed(int fieldMask) { if (fieldMask == ALL_FIELDS) { for (int i = 0; i < fields.length; i++) { stamp[i] = COMPUTED; isSet[i] = true; } areFieldsSet = areAllFieldsSet = true; } else { for (int i = 0; i < fields.length; i++) { if ((fieldMask & 1) == 1) { stamp[i] = COMPUTED; isSet[i] = true; } else { if (areAllFieldsSet && !isSet[i]) { areAllFieldsSet = false; } } fieldMask >>>= 1; } } } /** {@collect.stats} * {@description.open} * Sets the state of the calendar fields that are <em>not</em> specified * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code> * specifies all the calendar fields, then the state of this * <code>Calendar</code> becomes that all the calendar fields are in sync * with the time value (millisecond offset from the Epoch). * {@description.close} * * @param fieldMask the field mask indicating which calendar fields are in * sync with the time value. * @exception IndexOutOfBoundsException if the specified * <code>field</code> is out of range * (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>). * @see #isExternallySet(int) * @see #selectFields() */ final void setFieldsNormalized(int fieldMask) { if (fieldMask != ALL_FIELDS) { for (int i = 0; i < fields.length; i++) { if ((fieldMask & 1) == 0) { stamp[i] = fields[i] = 0; // UNSET == 0 isSet[i] = false; } fieldMask >>= 1; } } // Some or all of the fields are in sync with the // milliseconds, but the stamp values are not normalized yet. areFieldsSet = true; areAllFieldsSet = false; } /** {@collect.stats} * {@description.open} * Returns whether the calendar fields are partially in sync with the time * value or fully in sync but not stamp values are not normalized yet. * {@description.close} */ final boolean isPartiallyNormalized() { return areFieldsSet && !areAllFieldsSet; } /** {@collect.stats} * {@description.open} * Returns whether the calendar fields are fully in sync with the time * value. * {@description.close} */ final boolean isFullyNormalized() { return areFieldsSet && areAllFieldsSet; } /** {@collect.stats} * {@description.open} * Marks this Calendar as not sync'd. * {@description.close} */ final void setUnnormalized() { areFieldsSet = areAllFieldsSet = false; } /** {@collect.stats} * {@description.open} * Returns whether the specified <code>field</code> is on in the * <code>fieldMask</code>. * {@description.close} */ static final boolean isFieldSet(int fieldMask, int field) { return (fieldMask & (1 << field)) != 0; } /** {@collect.stats} * {@description.open} * Returns a field mask indicating which calendar field values * to be used to calculate the time value. The calendar fields are * returned as a bit mask, each bit of which corresponds to a field, i.e., * the mask value of <code>field</code> is <code>(1 &lt;&lt; * field)</code>. For example, 0x26 represents the <code>YEAR</code>, * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is * equal to * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>. * * <p>This method supports the calendar fields resolution as described in * the class description. If the bit mask for a given field is on and its * field has not been set (i.e., <code>isSet(field)</code> is * <code>false</code>), then the default value of the field has to be * used, which case means that the field has been selected because the * selected combination involves the field. * {@description.close} * * @return a bit mask of selected fields * @see #isExternallySet(int) * @see #setInternallySetState(int) */ final int selectFields() { // This implementation has been taken from the GregorianCalendar class. // The YEAR field must always be used regardless of its SET // state because YEAR is a mandatory field to determine the date // and the default value (EPOCH_YEAR) may change through the // normalization process. int fieldMask = YEAR_MASK; if (stamp[ERA] != UNSET) { fieldMask |= ERA_MASK; } // Find the most recent group of fields specifying the day within // the year. These may be any of the following combinations: // MONTH + DAY_OF_MONTH // MONTH + WEEK_OF_MONTH + DAY_OF_WEEK // MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK // DAY_OF_YEAR // WEEK_OF_YEAR + DAY_OF_WEEK // We look for the most recent of the fields in each group to determine // the age of the group. For groups involving a week-related field such // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the // week-related field and the DAY_OF_WEEK must be set for the group as a // whole to be considered. (See bug 4153860 - liu 7/24/98.) int dowStamp = stamp[DAY_OF_WEEK]; int monthStamp = stamp[MONTH]; int domStamp = stamp[DAY_OF_MONTH]; int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp); int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp); int doyStamp = stamp[DAY_OF_YEAR]; int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp); int bestStamp = domStamp; if (womStamp > bestStamp) { bestStamp = womStamp; } if (dowimStamp > bestStamp) { bestStamp = dowimStamp; } if (doyStamp > bestStamp) { bestStamp = doyStamp; } if (woyStamp > bestStamp) { bestStamp = woyStamp; } /* No complete combination exists. Look for WEEK_OF_MONTH, * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone. Treat DAY_OF_WEEK alone * as DAY_OF_WEEK_IN_MONTH. */ if (bestStamp == UNSET) { womStamp = stamp[WEEK_OF_MONTH]; dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp); woyStamp = stamp[WEEK_OF_YEAR]; bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp); /* Treat MONTH alone or no fields at all as DAY_OF_MONTH. This may * result in bestStamp = domStamp = UNSET if no fields are set, * which indicates DAY_OF_MONTH. */ if (bestStamp == UNSET) { bestStamp = domStamp = monthStamp; } } if (bestStamp == domStamp || (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) || (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) { fieldMask |= MONTH_MASK; if (bestStamp == domStamp) { fieldMask |= DAY_OF_MONTH_MASK; } else { assert (bestStamp == womStamp || bestStamp == dowimStamp); if (dowStamp != UNSET) { fieldMask |= DAY_OF_WEEK_MASK; } if (womStamp == dowimStamp) { // When they are equal, give the priority to // WEEK_OF_MONTH for compatibility. if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) { fieldMask |= WEEK_OF_MONTH_MASK; } else { fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK; } } else { if (bestStamp == womStamp) { fieldMask |= WEEK_OF_MONTH_MASK; } else { assert (bestStamp == dowimStamp); if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) { fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK; } } } } } else { assert (bestStamp == doyStamp || bestStamp == woyStamp || bestStamp == UNSET); if (bestStamp == doyStamp) { fieldMask |= DAY_OF_YEAR_MASK; } else { assert (bestStamp == woyStamp); if (dowStamp != UNSET) { fieldMask |= DAY_OF_WEEK_MASK; } fieldMask |= WEEK_OF_YEAR_MASK; } } // Find the best set of fields specifying the time of day. There // are only two possibilities here; the HOUR_OF_DAY or the // AM_PM and the HOUR. int hourOfDayStamp = stamp[HOUR_OF_DAY]; int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]); bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp; // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659) if (bestStamp == UNSET) { bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]); } // Hours if (bestStamp != UNSET) { if (bestStamp == hourOfDayStamp) { fieldMask |= HOUR_OF_DAY_MASK; } else { fieldMask |= HOUR_MASK; if (stamp[AM_PM] != UNSET) { fieldMask |= AM_PM_MASK; } } } if (stamp[MINUTE] != UNSET) { fieldMask |= MINUTE_MASK; } if (stamp[SECOND] != UNSET) { fieldMask |= SECOND_MASK; } if (stamp[MILLISECOND] != UNSET) { fieldMask |= MILLISECOND_MASK; } if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) { fieldMask |= ZONE_OFFSET_MASK; } if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) { fieldMask |= DST_OFFSET_MASK; } return fieldMask; } /** {@collect.stats} * {@description.open} * Returns the pseudo-time-stamp for two fields, given their * individual pseudo-time-stamps. If either of the fields * is unset, then the aggregate is unset. Otherwise, the * aggregate is the later of the two stamps. * {@description.close} */ private static final int aggregateStamp(int stamp_a, int stamp_b) { if (stamp_a == UNSET || stamp_b == UNSET) { return UNSET; } return (stamp_a > stamp_b) ? stamp_a : stamp_b; } /** {@collect.stats} * {@description.open} * Compares this <code>Calendar</code> to the specified * <code>Object</code>. The result is <code>true</code> if and only if * the argument is a <code>Calendar</code> object of the same calendar * system that represents the same time value (millisecond offset from the * <a href="#Epoch">Epoch</a>) under the same * <code>Calendar</code> parameters as this object. * * <p>The <code>Calendar</code> parameters are the values represented * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>, * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code> * methods. If there is any difference in those parameters * between the two <code>Calendar</code>s, this method returns * <code>false</code>. * * <p>Use the {@link #compareTo(Calendar) compareTo} method to * compare only the time values. * {@description.close} * * @param obj the object to compare with. * @return <code>true</code> if this object is equal to <code>obj</code>; * <code>false</code> otherwise. */ public boolean equals(Object obj) { if (this == obj) return true; try { Calendar that = (Calendar)obj; return compareTo(getMillisOf(that)) == 0 && lenient == that.lenient && firstDayOfWeek == that.firstDayOfWeek && minimalDaysInFirstWeek == that.minimalDaysInFirstWeek && zone.equals(that.zone); } catch (Exception e) { // Note: GregorianCalendar.computeTime throws // IllegalArgumentException if the ERA value is invalid // even it's in lenient mode. } return false; } /** {@collect.stats} * {@description.open} * Returns a hash code for this calendar. * {@description.close} * * @return a hash code value for this object. * @since 1.2 */ public int hashCode() { // 'otheritems' represents the hash code for the previous versions. int otheritems = (lenient ? 1 : 0) | (firstDayOfWeek << 1) | (minimalDaysInFirstWeek << 4) | (zone.hashCode() << 7); long t = getMillisOf(this); return (int) t ^ (int)(t >> 32) ^ otheritems; } /** {@collect.stats} * {@description.open} * Returns whether this <code>Calendar</code> represents a time * before the time represented by the specified * <code>Object</code>. This method is equivalent to: * <pre><blockquote> * compareTo(when) < 0 * </blockquote></pre> * if and only if <code>when</code> is a <code>Calendar</code> * instance. Otherwise, the method returns <code>false</code>. * {@description.close} * * @param when the <code>Object</code> to be compared * @return <code>true</code> if the time of this * <code>Calendar</code> is before the time represented by * <code>when</code>; <code>false</code> otherwise. * @see #compareTo(Calendar) */ public boolean before(Object when) { return when instanceof Calendar && compareTo((Calendar)when) < 0; } /** {@collect.stats} * {@description.open} * Returns whether this <code>Calendar</code> represents a time * after the time represented by the specified * <code>Object</code>. This method is equivalent to: * <pre><blockquote> * compareTo(when) > 0 * </blockquote></pre> * if and only if <code>when</code> is a <code>Calendar</code> * instance. Otherwise, the method returns <code>false</code>. * {@description.close} * * @param when the <code>Object</code> to be compared * @return <code>true</code> if the time of this <code>Calendar</code> is * after the time represented by <code>when</code>; <code>false</code> * otherwise. * @see #compareTo(Calendar) */ public boolean after(Object when) { return when instanceof Calendar && compareTo((Calendar)when) > 0; } /** {@collect.stats} * {@description.open} * Compares the time values (millisecond offsets from the <a * href="#Epoch">Epoch</a>) represented by two * <code>Calendar</code> objects. * {@description.close} * * @param anotherCalendar the <code>Calendar</code> to be compared. * @return the value <code>0</code> if the time represented by the argument * is equal to the time represented by this <code>Calendar</code>; a value * less than <code>0</code> if the time of this <code>Calendar</code> is * before the time represented by the argument; and a value greater than * <code>0</code> if the time of this <code>Calendar</code> is after the * time represented by the argument. * @exception NullPointerException if the specified <code>Calendar</code> is * <code>null</code>. * @exception IllegalArgumentException if the time value of the * specified <code>Calendar</code> object can't be obtained due to * any invalid calendar values. * @since 1.5 */ public int compareTo(Calendar anotherCalendar) { return compareTo(getMillisOf(anotherCalendar)); } /** {@collect.stats} * {@description.open} * Adds or subtracts the specified amount of time to the given calendar field, * based on the calendar's rules. For example, to subtract 5 days from * the current time of the calendar, you can achieve it by calling: * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>. * {@description.close} * * @param field the calendar field. * @param amount the amount of date or time to be added to the field. * @see #roll(int,int) * @see #set(int,int) */ abstract public void add(int field, int amount); /** {@collect.stats} * {@description.open} * Adds or subtracts (up/down) a single unit of time on the given time * field without changing larger fields. For example, to roll the current * date up by one day, you can achieve it by calling: * <p>roll(Calendar.DATE, true). * When rolling on the year or Calendar.YEAR field, it will roll the year * value in the range between 1 and the value returned by calling * <code>getMaximum(Calendar.YEAR)</code>. * When rolling on the month or Calendar.MONTH field, other fields like * date might conflict and, need to be changed. For instance, * rolling the month on the date 01/31/96 will result in 02/29/96. * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will * roll the hour value in the range between 0 and 23, which is zero-based. * {@description.close} * * @param field the time field. * @param up indicates if the value of the specified time field is to be * rolled up or rolled down. Use true if rolling up, false otherwise. * @see Calendar#add(int,int) * @see Calendar#set(int,int) */ abstract public void roll(int field, boolean up); /** {@collect.stats} * {@description.open} * Adds the specified (signed) amount to the specified calendar field * without changing larger fields. A negative amount means to roll * down. * * <p>NOTE: This default implementation on <code>Calendar</code> just repeatedly calls the * version of {@link #roll(int,boolean) roll()} that rolls by one unit. This may not * always do the right thing. For example, if the <code>DAY_OF_MONTH</code> field is 31, * rolling through February will leave it set to 28. The <code>GregorianCalendar</code> * version of this function takes care of this problem. Other subclasses * should also provide overrides of this function that do the right thing. * {@description.close} * * @param field the calendar field. * @param amount the signed amount to add to the calendar <code>field</code>. * @since 1.2 * @see #roll(int,boolean) * @see #add(int,int) * @see #set(int,int) */ public void roll(int field, int amount) { while (amount > 0) { roll(field, true); amount--; } while (amount < 0) { roll(field, false); amount++; } } /** {@collect.stats} * {@description.open} * Sets the time zone with the given time zone value. * {@description.close} * * @param value the given time zone. */ public void setTimeZone(TimeZone value) { zone = value; sharedZone = false; /* Recompute the fields from the time using the new zone. This also * works if isTimeSet is false (after a call to set()). In that case * the time will be computed from the fields using the new zone, then * the fields will get recomputed from that. Consider the sequence of * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST). * Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More * generally, a call to setTimeZone() affects calls to set() BEFORE AND * AFTER it up to the next call to complete(). */ areAllFieldsSet = areFieldsSet = false; } /** {@collect.stats} * {@description.open} * Gets the time zone. * {@description.close} * * @return the time zone object associated with this calendar. */ public TimeZone getTimeZone() { // If the TimeZone object is shared by other Calendar instances, then // create a clone. if (sharedZone) { zone = (TimeZone) zone.clone(); sharedZone = false; } return zone; } /** {@collect.stats} * {@description.open} * Returns the time zone (without cloning). * {@description.close} */ TimeZone getZone() { return zone; } /** {@collect.stats} * {@description.open} * Sets the sharedZone flag to <code>shared</code>. * {@description.close} */ void setZoneShared(boolean shared) { sharedZone = shared; } /** {@collect.stats} * {@description.open} * Specifies whether or not date/time interpretation is to be lenient. With * lenient interpretation, a date such as "February 942, 1996" will be * treated as being equivalent to the 941st day after February 1, 1996. * With strict (non-lenient) interpretation, such dates will cause an exception to be * thrown. The default is lenient. * {@description.close} * * @param lenient <code>true</code> if the lenient mode is to be turned * on; <code>false</code> if it is to be turned off. * @see #isLenient() * @see java.text.DateFormat#setLenient */ public void setLenient(boolean lenient) { this.lenient = lenient; } /** {@collect.stats} * {@description.open} * Tells whether date/time interpretation is to be lenient. * {@description.close} * * @return <code>true</code> if the interpretation mode of this calendar is lenient; * <code>false</code> otherwise. * @see #setLenient(boolean) */ public boolean isLenient() { return lenient; } /** {@collect.stats} * {@description.open} * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S., * <code>MONDAY</code> in France. * {@description.close} * * @param value the given first day of the week. * @see #getFirstDayOfWeek() * @see #getMinimalDaysInFirstWeek() */ public void setFirstDayOfWeek(int value) { if (firstDayOfWeek == value) { return; } firstDayOfWeek = value; invalidateWeekFields(); } /** {@collect.stats} * {@description.open} * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S., * <code>MONDAY</code> in France. * {@description.close} * * @return the first day of the week. * @see #setFirstDayOfWeek(int) * @see #getMinimalDaysInFirstWeek() */ public int getFirstDayOfWeek() { return firstDayOfWeek; } /** {@collect.stats} * {@description.open} * Sets what the minimal days required in the first week of the year are; * For example, if the first week is defined as one that contains the first * day of the first month of a year, call this method with value 1. If it * must be a full week, use value 7. * {@description.close} * * @param value the given minimal days required in the first week * of the year. * @see #getMinimalDaysInFirstWeek() */ public void setMinimalDaysInFirstWeek(int value) { if (minimalDaysInFirstWeek == value) { return; } minimalDaysInFirstWeek = value; invalidateWeekFields(); } /** {@collect.stats} * {@description.open} * Gets what the minimal days required in the first week of the year are; * e.g., if the first week is defined as one that contains the first day * of the first month of a year, this method returns 1. If * the minimal days required must be a full week, this method * returns 7. * {@description.close} * * @return the minimal days required in the first week of the year. * @see #setMinimalDaysInFirstWeek(int) */ public int getMinimalDaysInFirstWeek() { return minimalDaysInFirstWeek; } /** {@collect.stats} * {@description.open} * Returns the minimum value for the given calendar field of this * <code>Calendar</code> instance. The minimum value is defined as * the smallest value returned by the {@link #get(int) get} method * for any possible time value. The minimum value depends on * calendar system specific parameters of the instance. * {@description.close} * * @param field the calendar field. * @return the minimum value for the given calendar field. * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ abstract public int getMinimum(int field); /** {@collect.stats} * {@description.open} * Returns the maximum value for the given calendar field of this * <code>Calendar</code> instance. The maximum value is defined as * the largest value returned by the {@link #get(int) get} method * for any possible time value. The maximum value depends on * calendar system specific parameters of the instance. * {@description.close} * * @param field the calendar field. * @return the maximum value for the given calendar field. * @see #getMinimum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ abstract public int getMaximum(int field); /** {@collect.stats} * {@description.open} * Returns the highest minimum value for the given calendar field * of this <code>Calendar</code> instance. The highest minimum * value is defined as the largest value returned by {@link * #getActualMinimum(int)} for any possible time value. The * greatest minimum value depends on calendar system specific * parameters of the instance. * {@description.close} * * @param field the calendar field. * @return the highest minimum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ abstract public int getGreatestMinimum(int field); /** {@collect.stats} * {@description.open} * Returns the lowest maximum value for the given calendar field * of this <code>Calendar</code> instance. The lowest maximum * value is defined as the smallest value returned by {@link * #getActualMaximum(int)} for any possible time value. The least * maximum value depends on calendar system specific parameters of * the instance. For example, a <code>Calendar</code> for the * Gregorian calendar system returns 28 for the * <code>DAY_OF_MONTH</code> field, because the 28th is the last * day of the shortest month of this calendar, February in a * common year. * {@description.close} * * @param field the calendar field. * @return the lowest maximum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ abstract public int getLeastMaximum(int field); /** {@collect.stats} * {@description.open} * Returns the minimum value that the specified calendar field * could have, given the time value of this <code>Calendar</code>. * * <p>The default implementation of this method uses an iterative * algorithm to determine the actual minimum value for the * calendar field. Subclasses should, if possible, override this * with a more efficient implementation - in many cases, they can * simply return <code>getMinimum()</code>. * {@description.close} * * @param field the calendar field * @return the minimum of the given calendar field for the time * value of this <code>Calendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMaximum(int) * @since 1.2 */ public int getActualMinimum(int field) { int fieldValue = getGreatestMinimum(field); int endValue = getMinimum(field); // if we know that the minimum value is always the same, just return it if (fieldValue == endValue) { return fieldValue; } // clone the calendar so we don't mess with the real one, and set it to // accept anything for the field values Calendar work = (Calendar)this.clone(); work.setLenient(true); // now try each value from getLeastMaximum() to getMaximum() one by one until // we get a value that normalizes to another value. The last value that // normalizes to itself is the actual minimum for the current date int result = fieldValue; do { work.set(field, fieldValue); if (work.get(field) != fieldValue) { break; } else { result = fieldValue; fieldValue--; } } while (fieldValue >= endValue); return result; } /** {@collect.stats} * {@description.open} * Returns the maximum value that the specified calendar field * could have, given the time value of this * <code>Calendar</code>. For example, the actual maximum value of * the <code>MONTH</code> field is 12 in some years, and 13 in * other years in the Hebrew calendar system. * * <p>The default implementation of this method uses an iterative * algorithm to determine the actual maximum value for the * calendar field. Subclasses should, if possible, override this * with a more efficient implementation. * {@description.close} * * @param field the calendar field * @return the maximum of the given calendar field for the time * value of this <code>Calendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @since 1.2 */ public int getActualMaximum(int field) { int fieldValue = getLeastMaximum(field); int endValue = getMaximum(field); // if we know that the maximum value is always the same, just return it. if (fieldValue == endValue) { return fieldValue; } // clone the calendar so we don't mess with the real one, and set it to // accept anything for the field values. Calendar work = (Calendar)this.clone(); work.setLenient(true); // if we're counting weeks, set the day of the week to Sunday. We know the // last week of a month or year will contain the first day of the week. if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) work.set(DAY_OF_WEEK, firstDayOfWeek); // now try each value from getLeastMaximum() to getMaximum() one by one until // we get a value that normalizes to another value. The last value that // normalizes to itself is the actual maximum for the current date int result = fieldValue; do { work.set(field, fieldValue); if (work.get(field) != fieldValue) { break; } else { result = fieldValue; fieldValue++; } } while (fieldValue <= endValue); return result; } /** {@collect.stats} * {@description.open} * Creates and returns a copy of this object. * {@description.close} * * @return a copy of this object. */ public Object clone() { try { Calendar other = (Calendar) super.clone(); other.fields = new int[FIELD_COUNT]; other.isSet = new boolean[FIELD_COUNT]; other.stamp = new int[FIELD_COUNT]; for (int i = 0; i < FIELD_COUNT; i++) { other.fields[i] = fields[i]; other.stamp[i] = stamp[i]; other.isSet[i] = isSet[i]; } other.zone = (TimeZone) zone.clone(); return other; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } private static final String[] FIELD_NAME = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET", "DST_OFFSET" }; /** {@collect.stats} * {@description.open} * Returns the name of the specified calendar field. * {@description.close} * * @param field the calendar field * @return the calendar field name * @exception IndexOutOfBoundsException if <code>field</code> is negative, * equal to or greater then <code>FIELD_COUNT</code>. */ static final String getFieldName(int field) { return FIELD_NAME[field]; } /** {@collect.stats} * {@description.open} * Return a string representation of this calendar. This method * is intended to be used only for debugging purposes, and the * format of the returned string may vary between implementations. * The returned string may be empty but may not be <code>null</code>. * {@description.close} * * @return a string representation of this calendar. */ public String toString() { // NOTE: BuddhistCalendar.toString() interprets the string // produced by this method so that the Gregorian year number // is substituted by its B.E. year value. It relies on // "...,YEAR=<year>,..." or "...,YEAR=?,...". StringBuilder buffer = new StringBuilder(800); buffer.append(getClass().getName()).append('['); appendValue(buffer, "time", isTimeSet, time); buffer.append(",areFieldsSet=").append(areFieldsSet); buffer.append(",areAllFieldsSet=").append(areAllFieldsSet); buffer.append(",lenient=").append(lenient); buffer.append(",zone=").append(zone); appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek); appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek); for (int i = 0; i < FIELD_COUNT; ++i) { buffer.append(','); appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]); } buffer.append(']'); return buffer.toString(); } // =======================privates=============================== private static final void appendValue(StringBuilder sb, String item, boolean valid, long value) { sb.append(item).append('='); if (valid) { sb.append(value); } else { sb.append('?'); } } /** {@collect.stats} * {@description.open} * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. * They are used to figure out the week count for a specific date for * a given locale. These must be set when a Calendar is constructed. * {@description.close} * @param desiredLocale the given locale. */ private void setWeekCountData(Locale desiredLocale) { /* try to get the Locale data from the cache */ int[] data = cachedLocaleData.get(desiredLocale); if (data == null) { /* cache miss */ ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale); data = new int[2]; data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek")); data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek")); cachedLocaleData.put(desiredLocale, data); } firstDayOfWeek = data[0]; minimalDaysInFirstWeek = data[1]; } /** {@collect.stats} * {@description.open} * Recomputes the time and updates the status fields isTimeSet * and areFieldsSet. * {@description.close} * {@property.open internal} * Callers should check isTimeSet and only * call this method if isTimeSet is false. * {@property.close} */ private void updateTime() { computeTime(); // The areFieldsSet and areAllFieldsSet values are no longer // controlled here (as of 1.5). isTimeSet = true; } private int compareTo(long t) { long thisTime = getMillisOf(this); return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1; } private static final long getMillisOf(Calendar calendar) { if (calendar.isTimeSet) { return calendar.time; } Calendar cal = (Calendar) calendar.clone(); cal.setLenient(true); return cal.getTimeInMillis(); } /** {@collect.stats} * {@description.open} * Adjusts the stamp[] values before nextStamp overflow. nextStamp * is set to the next stamp value upon the return. * {@description.close} */ private final void adjustStamp() { int max = MINIMUM_USER_STAMP; int newStamp = MINIMUM_USER_STAMP; for (;;) { int min = Integer.MAX_VALUE; for (int i = 0; i < stamp.length; i++) { int v = stamp[i]; if (v >= newStamp && min > v) { min = v; } if (max < v) { max = v; } } if (max != min && min == Integer.MAX_VALUE) { break; } for (int i = 0; i < stamp.length; i++) { if (stamp[i] == min) { stamp[i] = newStamp; } } newStamp++; if (min == max) { break; } } nextStamp = newStamp; } /** {@collect.stats} * {@description.open} * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the * new parameter value if they have been calculated internally. * {@description.close} */ private void invalidateWeekFields() { if (stamp[WEEK_OF_MONTH] != COMPUTED && stamp[WEEK_OF_YEAR] != COMPUTED) { return; } // We have to check the new values of these fields after changing // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values // have been changed, then set the new values. (4822110) Calendar cal = (Calendar) clone(); cal.setLenient(true); cal.clear(WEEK_OF_MONTH); cal.clear(WEEK_OF_YEAR); if (stamp[WEEK_OF_MONTH] == COMPUTED) { int weekOfMonth = cal.get(WEEK_OF_MONTH); if (fields[WEEK_OF_MONTH] != weekOfMonth) { fields[WEEK_OF_MONTH] = weekOfMonth; } } if (stamp[WEEK_OF_YEAR] == COMPUTED) { int weekOfYear = cal.get(WEEK_OF_YEAR); if (fields[WEEK_OF_YEAR] != weekOfYear) { fields[WEEK_OF_YEAR] = weekOfYear; } } } /** {@collect.stats} * {@description.open} * Save the state of this object to a stream (i.e., serialize it). * * Ideally, <code>Calendar</code> would only write out its state data and * the current time, and not write any field data out, such as * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>, * and <code>isSet[]</code>. <code>nextStamp</code> also should not be part * of the persistent state. Unfortunately, this didn't happen before JDK 1.1 * shipped. To be compatible with JDK 1.1, we will always have to write out * the field values and state flags. However, <code>nextStamp</code> can be * removed from the serialization stream; this will probably happen in the * near future. * {@description.close} */ private void writeObject(ObjectOutputStream stream) throws IOException { // Try to compute the time correctly, for the future (stream // version 2) in which we don't write out fields[] or isSet[]. if (!isTimeSet) { try { updateTime(); } catch (IllegalArgumentException e) {} } // If this Calendar has a ZoneInfo, save it and set a // SimpleTimeZone equivalent (as a single DST schedule) for // backward compatibility. TimeZone savedZone = null; if (zone instanceof ZoneInfo) { SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance(); if (stz == null) { stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID()); } savedZone = zone; zone = stz; } // Write out the 1.1 FCS object. stream.defaultWriteObject(); // Write out the ZoneInfo object // 4802409: we write out even if it is null, a temporary workaround // the real fix for bug 4844924 in corba-iiop stream.writeObject(savedZone); if (savedZone != null) { zone = savedZone; } } private static class CalendarAccessControlContext { private static final AccessControlContext INSTANCE; static { RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar"); PermissionCollection perms = perm.newPermissionCollection(); perms.add(perm); INSTANCE = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) }); } } /** {@collect.stats} * {@description.open} * Reconstitutes this object from a stream (i.e., deserialize it). * {@description.close} */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { final ObjectInputStream input = stream; input.defaultReadObject(); stamp = new int[FIELD_COUNT]; // Starting with version 2 (not implemented yet), we expect that // fields[], isSet[], isTimeSet, and areFieldsSet may not be // streamed out anymore. We expect 'time' to be correct. if (serialVersionOnStream >= 2) { isTimeSet = true; if (fields == null) fields = new int[FIELD_COUNT]; if (isSet == null) isSet = new boolean[FIELD_COUNT]; } else if (serialVersionOnStream >= 0) { for (int i=0; i<FIELD_COUNT; ++i) stamp[i] = isSet[i] ? COMPUTED : UNSET; } serialVersionOnStream = currentSerialVersion; // If there's a ZoneInfo object, use it for zone. ZoneInfo zi = null; try { zi = AccessController.doPrivileged( new PrivilegedExceptionAction<ZoneInfo>() { public ZoneInfo run() throws Exception { return (ZoneInfo) input.readObject(); } }, CalendarAccessControlContext.INSTANCE); } catch (PrivilegedActionException pae) { Exception e = pae.getException(); if (!(e instanceof OptionalDataException)) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof ClassNotFoundException) { throw (ClassNotFoundException) e; } throw new RuntimeException(e); } } if (zi != null) { zone = zi; } // If the deserialized object has a SimpleTimeZone, try to // replace it with a ZoneInfo equivalent (as of 1.4) in order // to be compatible with the SimpleTimeZone-based // implementation as much as possible. if (zone instanceof SimpleTimeZone) { String id = zone.getID(); TimeZone tz = TimeZone.getTimeZone(id); if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) { zone = tz; } } } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * <p> * The root class from which all event state objects shall be derived. * <p> * All Events are constructed with a reference to the object, the "source", * that is logically deemed to be the object upon which the Event in question * initially occurred upon. * {@description.close} * * @since JDK1.1 */ public class EventObject implements java.io.Serializable { private static final long serialVersionUID = 5516075349620653480L; /** {@collect.stats} * {@description.open} * The object on which the Event initially occurred. * {@description.close} */ protected transient Object source; /** {@collect.stats} * {@description.open} * Constructs a prototypical Event. * {@description.close} * * @param source The object on which the Event initially occurred. * @exception IllegalArgumentException if source is null. */ public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; } /** {@collect.stats} * {@description.open} * The object on which the Event initially occurred. * {@description.close} * * @return The object on which the Event initially occurred. */ public Object getSource() { return source; } /** {@collect.stats} * {@description.open} * Returns a String representation of this EventObject. * {@description.close} * * @return A a String representation of this EventObject. */ public String toString() { return getClass().getName() + "[source=" + source + "]"; } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; /** {@collect.stats} * {@description.open} * This class implements the <tt>Map</tt> interface with a hash table, using * reference-equality in place of object-equality when comparing keys (and * values). In other words, in an <tt>IdentityHashMap</tt>, two keys * <tt>k1</tt> and <tt>k2</tt> are considered equal if and only if * <tt>(k1==k2)</tt>. (In normal <tt>Map</tt> implementations (like * <tt>HashMap</tt>) two keys <tt>k1</tt> and <tt>k2</tt> are considered equal * if and only if <tt>(k1==null ? k2==null : k1.equals(k2))</tt>.) * * <p><b>This class is <i>not</i> a general-purpose <tt>Map</tt> * implementation! While this class implements the <tt>Map</tt> interface, it * intentionally violates <tt>Map's</tt> general contract, which mandates the * use of the <tt>equals</tt> method when comparing objects. This class is * designed for use only in the rare cases wherein reference-equality * semantics are required.</b> * * <p>A typical use of this class is <i>topology-preserving object graph * transformations</i>, such as serialization or deep-copying. To perform such * a transformation, a program must maintain a "node table" that keeps track * of all the object references that have already been processed. The node * table must not equate distinct objects even if they happen to be equal. * Another typical use of this class is to maintain <i>proxy objects</i>. For * example, a debugging facility might wish to maintain a proxy object for * each object in the program being debugged. * * <p>This class provides all of the optional map operations, and permits * <tt>null</tt> values and the <tt>null</tt> key. This class makes no * guarantees as to the order of the map; in particular, it does not guarantee * that the order will remain constant over time. * * <p>This class provides constant-time performance for the basic * operations (<tt>get</tt> and <tt>put</tt>), assuming the system * identity hash function ({@link System#identityHashCode(Object)}) * disperses elements properly among the buckets. * * <p>This class has one tuning parameter (which affects performance but not * semantics): <i>expected maximum size</i>. This parameter is the maximum * number of key-value mappings that the map is expected to hold. Internally, * this parameter is used to determine the number of buckets initially * comprising the hash table. The precise relationship between the expected * maximum size and the number of buckets is unspecified. * * <p>If the size of the map (the number of key-value mappings) sufficiently * exceeds the expected maximum size, the number of buckets is increased * Increasing the number of buckets ("rehashing") may be fairly expensive, so * it pays to create identity hash maps with a sufficiently large expected * maximum size. On the other hand, iteration over collection views requires * time proportional to the number of buckets in the hash table, so it * pays not to set the expected maximum size too high if you are especially * concerned with iteration performance or memory usage. * {@description.close} * * {@description.open synchronized} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access an identity hash map concurrently, and at * least one of the threads modifies the map structurally, it <i>must</i> * be synchronized externally. (A structural modification is any operation * that adds or deletes one or more mappings; merely changing the value * associated with a key that an instance already contains is not a * structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the map. * * If no such object exists, the map should be "wrapped" using the * {@link Collections#synchronizedMap Collections.synchronizedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map:<pre> * Map m = Collections.synchronizedMap(new IdentityHashMap(...));</pre> * {@description.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by the <tt>iterator</tt> method of the * collections returned by all of this class's "collection view * methods" are <i>fail-fast</i>: if the map is structurally modified * at any time after the iterator is created, in any way except * through the iterator's own <tt>remove</tt> method, the iterator * will throw a {@link ConcurrentModificationException}. Thus, in the * face of concurrent modification, the iterator fails quickly and * cleanly, rather than risking arbitrary, non-deterministic behavior * at an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>fail-fast iterators should be used only * to detect bugs.</i> * {@property.close} * * {@description.open} * <p>Implementation note: This is a simple <i>linear-probe</i> hash table, * as described for example in texts by Sedgewick and Knuth. The array * alternates holding keys and values. (This has better locality for large * tables than does using separate arrays.) For many JRE implementations * and operation mixes, this class will yield better performance than * {@link HashMap} (which uses <i>chaining</i> rather than linear-probing). * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @see System#identityHashCode(Object) * @see Object#hashCode() * @see Collection * @see Map * @see HashMap * @see TreeMap * @author Doug Lea and Josh Bloch * @since 1.4 */ public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, java.io.Serializable, Cloneable { /** {@collect.stats} * {@description.open} * The initial capacity used by the no-args constructor. * MUST be a power of two. The value 32 corresponds to the * (specified) expected maximum size of 21, given a load factor * of 2/3. * {@description.close} */ private static final int DEFAULT_CAPACITY = 32; /** {@collect.stats} * {@description.open} * The minimum capacity, used if a lower value is implicitly specified * by either of the constructors with arguments. The value 4 corresponds * to an expected maximum size of 2, given a load factor of 2/3. * MUST be a power of two. * {@description.close} */ private static final int MINIMUM_CAPACITY = 4; /** {@collect.stats} * {@description.open} * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<29. * {@description.close} */ private static final int MAXIMUM_CAPACITY = 1 << 29; /** {@collect.stats} * {@description.open} * The table, resized as necessary. Length MUST always be a power of two. * {@description.close} */ private transient Object[] table; /** {@collect.stats} * {@description.open} * The number of key-value mappings contained in this identity hash map. * {@description.close} * * @serial */ private int size; /** {@collect.stats} * {@description.open} * The number of modifications, to support fast-fail iterators * {@description.close} */ private transient volatile int modCount; /** {@collect.stats} * {@description.open} * The next size value at which to resize (capacity * load factor). * {@description.close} */ private transient int threshold; /** {@collect.stats} * {@description.open} * Value representing null keys inside tables. * {@description.close} */ private static final Object NULL_KEY = new Object(); /** {@collect.stats} * {@description.open} * Use NULL_KEY for key if it is null. * {@description.close} */ private static Object maskNull(Object key) { return (key == null ? NULL_KEY : key); } /** {@collect.stats} * {@description.open} * Returns internal representation of null key back to caller as null. * {@description.close} */ private static Object unmaskNull(Object key) { return (key == NULL_KEY ? null : key); } /** {@collect.stats} * {@description.open} * Constructs a new, empty identity hash map with a default expected * maximum size (21). * {@description.close} */ public IdentityHashMap() { init(DEFAULT_CAPACITY); } /** {@collect.stats} * {@description.open} * Constructs a new, empty map with the specified expected maximum size. * Putting more than the expected number of key-value mappings into * the map may cause the internal data structure to grow, which may be * somewhat time-consuming. * {@description.close} * * @param expectedMaxSize the expected maximum size of the map * @throws IllegalArgumentException if <tt>expectedMaxSize</tt> is negative */ public IdentityHashMap(int expectedMaxSize) { if (expectedMaxSize < 0) throw new IllegalArgumentException("expectedMaxSize is negative: " + expectedMaxSize); init(capacity(expectedMaxSize)); } /** {@collect.stats} * {@description.open} * Returns the appropriate capacity for the specified expected maximum * size. Returns the smallest power of two between MINIMUM_CAPACITY * and MAXIMUM_CAPACITY, inclusive, that is greater than * (3 * expectedMaxSize)/2, if such a number exists. Otherwise * returns MAXIMUM_CAPACITY. If (3 * expectedMaxSize)/2 is negative, it * is assumed that overflow has occurred, and MAXIMUM_CAPACITY is returned. * {@description.close} */ private int capacity(int expectedMaxSize) { // Compute min capacity for expectedMaxSize given a load factor of 2/3 int minCapacity = (3 * expectedMaxSize)/2; // Compute the appropriate capacity int result; if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) { result = MAXIMUM_CAPACITY; } else { result = MINIMUM_CAPACITY; while (result < minCapacity) result <<= 1; } return result; } /** {@collect.stats} * {@description.open} * Initializes object to be an empty map with the specified initial * capacity, which is assumed to be a power of two between * MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive. * {@description.close} */ private void init(int initCapacity) { // assert (initCapacity & -initCapacity) == initCapacity; // power of 2 // assert initCapacity >= MINIMUM_CAPACITY; // assert initCapacity <= MAXIMUM_CAPACITY; threshold = (initCapacity * 2)/3; table = new Object[2 * initCapacity]; } /** {@collect.stats} * {@description.open} * Constructs a new identity hash map containing the keys-value mappings * in the specified map. * {@description.close} * * @param m the map whose mappings are to be placed into this map * @throws NullPointerException if the specified map is null */ public IdentityHashMap(Map<? extends K, ? extends V> m) { // Allow for a bit of growth this((int) ((1 + m.size()) * 1.1)); putAll(m); } /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this identity hash map. * {@description.close} * * @return the number of key-value mappings in this map */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this identity hash map contains no key-value * mappings. * {@description.close} * * @return <tt>true</tt> if this identity hash map contains no key-value * mappings */ public boolean isEmpty() { return size == 0; } /** {@collect.stats} * {@description.open} * Returns index for Object x. * {@description.close} */ private static int hash(Object x, int length) { int h = System.identityHashCode(x); // Multiply by -127, and left-shift to use least bit as part of hash return ((h << 1) - (h << 8)) & (length - 1); } /** {@collect.stats} * {@description.open} * Circularly traverses table of size len. * {@description.close} */ private static int nextKeyIndex(int i, int len) { return (i + 2 < len ? i + 2 : 0); } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key == k)}, * then this method returns {@code v}; otherwise it returns * {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} * * @see #put(Object, Object) */ public V get(Object key) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); while (true) { Object item = tab[i]; if (item == k) return (V) tab[i + 1]; if (item == null) return null; i = nextKeyIndex(i, len); } } /** {@collect.stats} * {@description.open} * Tests whether the specified object reference is a key in this identity * hash map. * {@description.close} * * @param key possible key * @return <code>true</code> if the specified object reference is a key * in this map * @see #containsValue(Object) */ public boolean containsKey(Object key) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); while (true) { Object item = tab[i]; if (item == k) return true; if (item == null) return false; i = nextKeyIndex(i, len); } } /** {@collect.stats} * {@description.open} * Tests whether the specified object reference is a value in this identity * hash map. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified object reference * @see #containsKey(Object) */ public boolean containsValue(Object value) { Object[] tab = table; for (int i = 1; i < tab.length; i += 2) if (tab[i] == value && tab[i - 1] != null) return true; return false; } /** {@collect.stats} * {@description.open} * Tests if the specified key-value mapping is in the map. * {@description.close} * * @param key possible key * @param value possible value * @return <code>true</code> if and only if the specified key-value * mapping is in the map */ private boolean containsMapping(Object key, Object value) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); while (true) { Object item = tab[i]; if (item == k) return tab[i + 1] == value; if (item == null) return false; i = nextKeyIndex(i, len); } } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this identity * hash map. If the map previously contained a mapping for the key, the * old value is replaced. * {@description.close} * * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) * @see Object#equals(Object) * @see #get(Object) * @see #containsKey(Object) */ public V put(K key, V value) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); Object item; while ( (item = tab[i]) != null) { if (item == k) { V oldValue = (V) tab[i + 1]; tab[i + 1] = value; return oldValue; } i = nextKeyIndex(i, len); } modCount++; tab[i] = k; tab[i + 1] = value; if (++size >= threshold) resize(len); // len == 2 * current capacity. return null; } /** {@collect.stats} * {@description.open} * Resize the table to hold given capacity. * {@description.close} * * @param newCapacity the new capacity, must be a power of two. */ private void resize(int newCapacity) { // assert (newCapacity & -newCapacity) == newCapacity; // power of 2 int newLength = newCapacity * 2; Object[] oldTable = table; int oldLength = oldTable.length; if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further if (threshold == MAXIMUM_CAPACITY-1) throw new IllegalStateException("Capacity exhausted."); threshold = MAXIMUM_CAPACITY-1; // Gigantic map! return; } if (oldLength >= newLength) return; Object[] newTable = new Object[newLength]; threshold = newLength / 3; for (int j = 0; j < oldLength; j += 2) { Object key = oldTable[j]; if (key != null) { Object value = oldTable[j+1]; oldTable[j] = null; oldTable[j+1] = null; int i = hash(key, newLength); while (newTable[i] != null) i = nextKeyIndex(i, newLength); newTable[i] = key; newTable[i + 1] = value; } } table = newTable; } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for * any of the keys currently in the specified map. * {@description.close} * * @param m mappings to be stored in this map * @throws NullPointerException if the specified map is null */ public void putAll(Map<? extends K, ? extends V> m) { int n = m.size(); if (n == 0) return; if (n > threshold) // conservatively pre-expand resize(capacity(n)); for (Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** {@collect.stats} * {@description.open} * Removes the mapping for this key from this map if present. * {@description.close} * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V remove(Object key) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); while (true) { Object item = tab[i]; if (item == k) { modCount++; size--; V oldValue = (V) tab[i + 1]; tab[i + 1] = null; tab[i] = null; closeDeletion(i); return oldValue; } if (item == null) return null; i = nextKeyIndex(i, len); } } /** {@collect.stats} * {@description.open} * Removes the specified key-value mapping from the map if it is present. * {@description.close} * * @param key possible key * @param value possible value * @return <code>true</code> if and only if the specified key-value * mapping was in the map */ private boolean removeMapping(Object key, Object value) { Object k = maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); while (true) { Object item = tab[i]; if (item == k) { if (tab[i + 1] != value) return false; modCount++; size--; tab[i] = null; tab[i + 1] = null; closeDeletion(i); return true; } if (item == null) return false; i = nextKeyIndex(i, len); } } /** {@collect.stats} * {@description.open} * Rehash all possibly-colliding entries following a * deletion. This preserves the linear-probe * collision properties required by get, put, etc. * {@description.close} * * @param d the index of a newly empty deleted slot */ private void closeDeletion(int d) { // Adapted from Knuth Section 6.4 Algorithm R Object[] tab = table; int len = tab.length; // Look for items to swap into newly vacated slot // starting at index immediately following deletion, // and continuing until a null slot is seen, indicating // the end of a run of possibly-colliding keys. Object item; for (int i = nextKeyIndex(d, len); (item = tab[i]) != null; i = nextKeyIndex(i, len) ) { // The following test triggers if the item at slot i (which // hashes to be at slot r) should take the spot vacated by d. // If so, we swap it in, and then continue with d now at the // newly vacated i. This process will terminate when we hit // the null slot at the end of this run. // The test is messy because we are using a circular table. int r = hash(item, len); if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) { tab[d] = item; tab[d + 1] = tab[i + 1]; tab[i] = null; tab[i + 1] = null; d = i; } } } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * The map will be empty after this call returns. * {@description.close} */ public void clear() { modCount++; Object[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } /** {@collect.stats} * {@description.open} * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent identical object-reference mappings. More formally, this * map is equal to another map <tt>m</tt> if and only if * <tt>this.entrySet().equals(m.entrySet())</tt>. * {@description.close} * * {@description.open} * <p><b>Owing to the reference-equality-based semantics of this map it is * possible that the symmetry and transitivity requirements of the * <tt>Object.equals</tt> contract may be violated if this map is compared * to a normal map. However, the <tt>Object.equals</tt> contract is * guaranteed to hold among <tt>IdentityHashMap</tt> instances.</b> * {@description.close} * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map * @see Object#equals(Object) */ public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof IdentityHashMap) { IdentityHashMap m = (IdentityHashMap) o; if (m.size() != size) return false; Object[] tab = m.table; for (int i = 0; i < tab.length; i+=2) { Object k = tab[i]; if (k != null && !containsMapping(k, tab[i + 1])) return false; } return true; } else if (o instanceof Map) { Map m = (Map)o; return entrySet().equals(m.entrySet()); } else { return false; // o is not a Map } } /** {@collect.stats} * {@description.open} * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two * <tt>IdentityHashMap</tt> instances <tt>m1</tt> and <tt>m2</tt>, as * required by the general contract of {@link Object#hashCode}. * * <p><b>Owing to the reference-equality-based semantics of the * <tt>Map.Entry</tt> instances in the set returned by this map's * <tt>entrySet</tt> method, it is possible that the contractual * requirement of <tt>Object.hashCode</tt> mentioned in the previous * paragraph will be violated if one of the two objects being compared is * an <tt>IdentityHashMap</tt> instance and the other is a normal map.</b> * {@description.close} * * @return the hash code value for this map * @see Object#equals(Object) * @see #equals(Object) */ public int hashCode() { int result = 0; Object[] tab = table; for (int i = 0; i < tab.length; i +=2) { Object key = tab[i]; if (key != null) { Object k = unmaskNull(key); result += System.identityHashCode(k) ^ System.identityHashCode(tab[i + 1]); } } return result; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this identity hash map: the keys and values * themselves are not cloned. * {@description.close} * * @return a shallow copy of this map */ public Object clone() { try { IdentityHashMap<K,V> m = (IdentityHashMap<K,V>) super.clone(); m.entrySet = null; m.table = (Object[])table.clone(); return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } private abstract class IdentityHashMapIterator<T> implements Iterator<T> { int index = (size != 0 ? 0 : table.length); // current slot. int expectedModCount = modCount; // to support fast-fail int lastReturnedIndex = -1; // to allow remove() boolean indexValid; // To avoid unnecessary next computation Object[] traversalTable = table; // reference to main table or copy public boolean hasNext() { Object[] tab = traversalTable; for (int i = index; i < tab.length; i+=2) { Object key = tab[i]; if (key != null) { index = i; return indexValid = true; } } index = tab.length; return false; } protected int nextIndex() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (!indexValid && !hasNext()) throw new NoSuchElementException(); indexValid = false; lastReturnedIndex = index; index += 2; return lastReturnedIndex; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); expectedModCount = ++modCount; int deletedSlot = lastReturnedIndex; lastReturnedIndex = -1; size--; // back up index to revisit new contents after deletion index = deletedSlot; indexValid = false; // Removal code proceeds as in closeDeletion except that // it must catch the rare case where an element already // seen is swapped into a vacant slot that will be later // traversed by this iterator. We cannot allow future // next() calls to return it again. The likelihood of // this occurring under 2/3 load factor is very slim, but // when it does happen, we must make a copy of the rest of // the table to use for the rest of the traversal. Since // this can only happen when we are near the end of the table, // even in these rare cases, this is not very expensive in // time or space. Object[] tab = traversalTable; int len = tab.length; int d = deletedSlot; K key = (K) tab[d]; tab[d] = null; // vacate the slot tab[d + 1] = null; // If traversing a copy, remove in real table. // We can skip gap-closure on copy. if (tab != IdentityHashMap.this.table) { IdentityHashMap.this.remove(key); expectedModCount = modCount; return; } Object item; for (int i = nextKeyIndex(d, len); (item = tab[i]) != null; i = nextKeyIndex(i, len)) { int r = hash(item, len); // See closeDeletion for explanation of this conditional if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) { // If we are about to swap an already-seen element // into a slot that may later be returned by next(), // then clone the rest of table for use in future // next() calls. It is OK that our copy will have // a gap in the "wrong" place, since it will never // be used for searching anyway. if (i < deletedSlot && d >= deletedSlot && traversalTable == IdentityHashMap.this.table) { int remaining = len - deletedSlot; Object[] newTable = new Object[remaining]; System.arraycopy(tab, deletedSlot, newTable, 0, remaining); traversalTable = newTable; index = 0; } tab[d] = item; tab[d + 1] = tab[i + 1]; tab[i] = null; tab[i + 1] = null; d = i; } } } } private class KeyIterator extends IdentityHashMapIterator<K> { public K next() { return (K) unmaskNull(traversalTable[nextIndex()]); } } private class ValueIterator extends IdentityHashMapIterator<V> { public V next() { return (V) traversalTable[nextIndex() + 1]; } } /** {@collect.stats} * {@description.open} * Since we don't use Entry objects, we use the Iterator * itself as an entry. * {@description.close} */ private class EntryIterator extends IdentityHashMapIterator<Map.Entry<K,V>> implements Map.Entry<K,V> { public Map.Entry<K,V> next() { nextIndex(); return this; } public K getKey() { // Provide a better exception than out of bounds index if (lastReturnedIndex < 0) throw new IllegalStateException("Entry was removed"); return (K) unmaskNull(traversalTable[lastReturnedIndex]); } public V getValue() { // Provide a better exception than out of bounds index if (lastReturnedIndex < 0) throw new IllegalStateException("Entry was removed"); return (V) traversalTable[lastReturnedIndex+1]; } public V setValue(V value) { // It would be mean-spirited to proceed here if remove() called if (lastReturnedIndex < 0) throw new IllegalStateException("Entry was removed"); V oldValue = (V) traversalTable[lastReturnedIndex+1]; traversalTable[lastReturnedIndex+1] = value; // if shadowing, force into main table if (traversalTable != IdentityHashMap.this.table) put((K) traversalTable[lastReturnedIndex], value); return oldValue; } public boolean equals(Object o) { if (lastReturnedIndex < 0) return super.equals(o); if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return e.getKey() == getKey() && e.getValue() == getValue(); } public int hashCode() { if (lastReturnedIndex < 0) return super.hashCode(); return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); } public String toString() { if (lastReturnedIndex < 0) return super.toString(); return getKey() + "=" + getValue(); } } // Views /** {@collect.stats} * {@description.open} * This field is initialized to contain an instance of the entry set * view the first time this view is requested. The view is stateless, * so there's no reason to create more than one. * {@description.close} */ private transient Set<Map.Entry<K,V>> entrySet = null; /** {@collect.stats} * {@description.open} * Returns an identity-based set view of the keys contained in this map. * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified while an iteration * over the set is in progress, the results of the iteration are * undefined. * The set supports element removal, which removes the * corresponding mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and * <tt>clear</tt> methods. It does not support the <tt>add</tt> or * <tt>addAll</tt> methods. * {@property.close} * * {@description.open} * <p><b>While the object returned by this method implements the * <tt>Set</tt> interface, it does <i>not</i> obey <tt>Set's</tt> general * contract. Like its backing map, the set returned by this method * defines element equality as reference-equality rather than * object-equality. This affects the behavior of its <tt>contains</tt>, * <tt>remove</tt>, <tt>containsAll</tt>, <tt>equals</tt>, and * <tt>hashCode</tt> methods.</b> * * <p><b>The <tt>equals</tt> method of the returned set returns <tt>true</tt> * only if the specified object is a set containing exactly the same * object references as the returned set. The symmetry and transitivity * requirements of the <tt>Object.equals</tt> contract may be violated if * the set returned by this method is compared to a normal set. However, * the <tt>Object.equals</tt> contract is guaranteed to hold among sets * returned by this method.</b> * * <p>The <tt>hashCode</tt> method of the returned set returns the sum of * the <i>identity hashcodes</i> of the elements in the set, rather than * the sum of their hashcodes. This is mandated by the change in the * semantics of the <tt>equals</tt> method, in order to enforce the * general contract of the <tt>Object.hashCode</tt> method among sets * returned by this method. * {@description.close} * * @return an identity-based set view of the keys contained in this map * @see Object#equals(Object) * @see System#identityHashCode(Object) */ public Set<K> keySet() { Set<K> ks = keySet; if (ks != null) return ks; else return keySet = new KeySet(); } private class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return new KeyIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldSize = size; IdentityHashMap.this.remove(o); return size != oldSize; } /* * Must revert from AbstractSet's impl to AbstractCollection's, as * the former contains an optimization that results in incorrect * behavior when c is a smaller "normal" (non-identity-based) Set. */ public boolean removeAll(Collection<?> c) { boolean modified = false; for (Iterator i = iterator(); i.hasNext(); ) { if (c.contains(i.next())) { i.remove(); modified = true; } } return modified; } public void clear() { IdentityHashMap.this.clear(); } public int hashCode() { int result = 0; for (K key : this) result += System.identityHashCode(key); return result; } } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress, * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> methods. It does not * support the <tt>add</tt> or <tt>addAll</tt> methods. * {@property.close} * * {@description.open} * <p><b>While the object returned by this method implements the * <tt>Collection</tt> interface, it does <i>not</i> obey * <tt>Collection's</tt> general contract. Like its backing map, * the collection returned by this method defines element equality as * reference-equality rather than object-equality. This affects the * behavior of its <tt>contains</tt>, <tt>remove</tt> and * <tt>containsAll</tt> methods.</b> * {@description.close} */ public Collection<V> values() { Collection<V> vs = values; if (vs != null) return vs; else return values = new Values(); } private class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsValue(o); } public boolean remove(Object o) { for (Iterator i = iterator(); i.hasNext(); ) { if (i.next() == o) { i.remove(); return true; } } return false; } public void clear() { IdentityHashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * Each element in the returned set is a reference-equality-based * <tt>Map.Entry</tt>. The set is backed by the map, so changes * to the map are reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the * map is modified while an iteration over the set is in progress, * the results of the iteration are undefined. The set supports * element removal, which removes the corresponding mapping from * the map, via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> * methods. It does not support the <tt>add</tt> or * <tt>addAll</tt> methods. * {@property.close} * * {@description.open} * <p>Like the backing map, the <tt>Map.Entry</tt> objects in the set * returned by this method define key and value equality as * reference-equality rather than object-equality. This affects the * behavior of the <tt>equals</tt> and <tt>hashCode</tt> methods of these * <tt>Map.Entry</tt> objects. A reference-equality based <tt>Map.Entry * e</tt> is equal to an object <tt>o</tt> if and only if <tt>o</tt> is a * <tt>Map.Entry</tt> and <tt>e.getKey()==o.getKey() &amp;&amp; * e.getValue()==o.getValue()</tt>. To accommodate these equals * semantics, the <tt>hashCode</tt> method returns * <tt>System.identityHashCode(e.getKey()) ^ * System.identityHashCode(e.getValue())</tt>. * * <p><b>Owing to the reference-equality-based semantics of the * <tt>Map.Entry</tt> instances in the set returned by this method, * it is possible that the symmetry and transitivity requirements of * the {@link Object#equals(Object)} contract may be violated if any of * the entries in the set is compared to a normal map entry, or if * the set returned by this method is compared to a set of normal map * entries (such as would be returned by a call to this method on a normal * map). However, the <tt>Object.equals</tt> contract is guaranteed to * hold among identity-based map entries, and among sets of such entries. * </b> * {@description.close} * * @return a set view of the identity-mappings contained in this map */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySet; if (es != null) return es; else return entrySet = new EntrySet(); } private class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; return containsMapping(entry.getKey(), entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; return removeMapping(entry.getKey(), entry.getValue()); } public int size() { return size; } public void clear() { IdentityHashMap.this.clear(); } /* * Must revert from AbstractSet's impl to AbstractCollection's, as * the former contains an optimization that results in incorrect * behavior when c is a smaller "normal" (non-identity-based) Set. */ public boolean removeAll(Collection<?> c) { boolean modified = false; for (Iterator i = iterator(); i.hasNext(); ) { if (c.contains(i.next())) { i.remove(); modified = true; } } return modified; } public Object[] toArray() { int size = size(); Object[] result = new Object[size]; Iterator<Map.Entry<K,V>> it = iterator(); for (int i = 0; i < size; i++) result[i] = new AbstractMap.SimpleEntry<K,V>(it.next()); return result; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) a = (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); Iterator<Map.Entry<K,V>> it = iterator(); for (int i = 0; i < size; i++) a[i] = (T) new AbstractMap.SimpleEntry<K,V>(it.next()); if (a.length > size) a[size] = null; return a; } } private static final long serialVersionUID = 8188218128353913216L; /** {@collect.stats} * {@description.open} * Save the state of the <tt>IdentityHashMap</tt> instance to a stream * (i.e., serialize it). * {@description.close} * * @serialData The <i>size</i> of the HashMap (the number of key-value * mappings) (<tt>int</tt>), followed by the key (Object) and * value (Object) for each key-value mapping represented by the * IdentityHashMap. The key-value mappings are emitted in no * particular order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size); // Write out keys and values (alternating) Object[] tab = table; for (int i = 0; i < tab.length; i += 2) { Object key = tab[i]; if (key != null) { s.writeObject(unmaskNull(key)); s.writeObject(tab[i + 1]); } } } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>IdentityHashMap</tt> instance from a stream (i.e., * deserialize it). * {@description.close} */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden stuff s.defaultReadObject(); // Read in size (number of Mappings) int size = s.readInt(); // Allow for 33% growth (i.e., capacity is >= 2* size()). init(capacity((size*4)/3)); // Read the keys and values, and put the mappings in the table for (int i=0; i<size; i++) { K key = (K) s.readObject(); V value = (V) s.readObject(); putForCreate(key, value); } } /** {@collect.stats} * {@description.open} * The put method for readObject. It does not resize the table, * update modCount, etc. * {@description.close} */ private void putForCreate(K key, V value) throws IOException { K k = (K)maskNull(key); Object[] tab = table; int len = tab.length; int i = hash(k, len); Object item; while ( (item = tab[i]) != null) { if (item == k) throw new java.io.StreamCorruptedException(); i = nextKeyIndex(i, len); } tab[i] = k; tab[i + 1] = value; } }
Java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.BufferedWriter; import java.io.Closeable; import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.Flushable; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.nio.charset.Charset; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import sun.misc.FpUtils; import sun.misc.DoubleConsts; import sun.misc.FormattedFloatingDecimal; /** {@collect.stats} * {@description.open} * An interpreter for printf-style format strings. This class provides support * for layout justification and alignment, common formats for numeric, string, * and date/time data, and locale-specific output. Common Java types such as * <tt>byte</tt>, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar} * are supported. Limited formatting customization for arbitrary user types is * provided through the {@link Formattable} interface. * * <p> Formatters are not necessarily safe for multithreaded access. Thread * safety is optional and is the responsibility of users of methods in this * class. * * <p> Formatted printing for the Java language is heavily inspired by C's * <tt>printf</tt>. Although the format strings are similar to C, some * customizations have been made to accommodate the Java language and exploit * some of its features. Also, Java formatting is more strict than C's; for * example, if a conversion is incompatible with a flag, an exception will be * thrown. In C inapplicable flags are silently ignored. The format strings * are thus intended to be recognizable to C programmers but not necessarily * completely compatible with those in C. * * <p> Examples of expected usage: * * <blockquote><pre> * StringBuilder sb = new StringBuilder(); * // Send all output to the Appendable object sb * Formatter formatter = new Formatter(sb, Locale.US); * * // Explicit argument indices may be used to re-order output. * formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") * // -&gt; " d c b a" * * // Optional locale as the first argument can be used to get * // locale-specific formatting of numbers. The precision and width can be * // given to round and align the value. * formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); * // -&gt; "e = +2,7183" * * // The '(' numeric flag may be used to format negative numbers with * // parentheses rather than a minus sign. Group separators are * // automatically inserted. * formatter.format("Amount gained or lost since last statement: $ %(,.2f", * balanceDelta); * // -&gt; "Amount gained or lost since last statement: $ (6,217.58)" * </pre></blockquote> * * <p> Convenience methods for common formatting requests exist as illustrated * by the following invocations: * * <blockquote><pre> * // Writes a formatted string to System.out. * System.out.format("Local time: %tT", Calendar.getInstance()); * // -&gt; "Local time: 13:34:18" * * // Writes formatted output to System.err. * System.err.printf("Unable to open file '%1$s': %2$s", * fileName, exception.getMessage()); * // -&gt; "Unable to open file 'food': No such file or directory" * </pre></blockquote> * * <p> Like C's <tt>sprintf(3)</tt>, Strings may be formatted using the static * method {@link String#format(String,Object...) String.format}: * * <blockquote><pre> * // Format a string containing a date. * import java.util.Calendar; * import java.util.GregorianCalendar; * import static java.util.Calendar.*; * * Calendar c = new GregorianCalendar(1995, MAY, 23); * String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); * // -&gt; s == "Duke's Birthday: May 23, 1995" * </pre></blockquote> * * <h3><a name="org">Organization</a></h3> * * <p> This specification is divided into two sections. The first section, <a * href="#summary">Summary</a>, covers the basic formatting concepts. This * section is intended for users who want to get started quickly and are * familiar with formatted printing in other programming languages. The second * section, <a href="#detail">Details</a>, covers the specific implementation * details. It is intended for users who want more precise specification of * formatting behavior. * * <h3><a name="summary">Summary</a></h3> * * <p> This section is intended to provide a brief overview of formatting * concepts. For precise behavioral details, refer to the <a * href="#detail">Details</a> section. * * <h4><a name="syntax">Format String Syntax</a></h4> * * <p> Every method which produces formatted output requires a <i>format * string</i> and an <i>argument list</i>. The format string is a {@link * String} which may contain fixed text and one or more embedded <i>format * specifiers</i>. Consider the following example: * * <blockquote><pre> * Calendar c = ...; * String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); * </pre></blockquote> * * This format string is the first argument to the <tt>format</tt> method. It * contains three format specifiers "<tt>%1$tm</tt>", "<tt>%1$te</tt>", and * "<tt>%1$tY</tt>" which indicate how the arguments should be processed and * where they should be inserted in the text. The remaining portions of the * format string are fixed text including <tt>"Dukes Birthday: "</tt> and any * other spaces or punctuation. * * The argument list consists of all arguments passed to the method after the * format string. In the above example, the argument list is of size one and * consists of the {@link java.util.Calendar Calendar} object <tt>c</tt>. * * <ul> * * <li> The format specifiers for general, character, and numeric types have * the following syntax: * * <blockquote><pre> * %[argument_index$][flags][width][.precision]conversion * </pre></blockquote> * * <p> The optional <i>argument_index</i> is a decimal integer indicating the * position of the argument in the argument list. The first argument is * referenced by "<tt>1$</tt>", the second by "<tt>2$</tt>", etc. * * <p> The optional <i>flags</i> is a set of characters that modify the output * format. The set of valid flags depends on the conversion. * * <p> The optional <i>width</i> is a non-negative decimal integer indicating * the minimum number of characters to be written to the output. * * <p> The optional <i>precision</i> is a non-negative decimal integer usually * used to restrict the number of characters. The specific behavior depends on * the conversion. * * <p> The required <i>conversion</i> is a character indicating how the * argument should be formatted. The set of valid conversions for a given * argument depends on the argument's data type. * * <li> The format specifiers for types which are used to represents dates and * times have the following syntax: * * <blockquote><pre> * %[argument_index$][flags][width]conversion * </pre></blockquote> * * <p> The optional <i>argument_index</i>, <i>flags</i> and <i>width</i> are * defined as above. * * <p> The required <i>conversion</i> is a two character sequence. The first * character is <tt>'t'</tt> or <tt>'T'</tt>. The second character indicates * the format to be used. These characters are similar to but not completely * identical to those defined by GNU <tt>date</tt> and POSIX * <tt>strftime(3c)</tt>. * * <li> The format specifiers which do not correspond to arguments have the * following syntax: * * <blockquote><pre> * %[flags][width]conversion * </pre></blockquote> * * <p> The optional <i>flags</i> and <i>width</i> is defined as above. * * <p> The required <i>conversion</i> is a character indicating content to be * inserted in the output. * * </ul> * * <h4> Conversions </h4> * * <p> Conversions are divided into the following categories: * * <ol> * * <li> <b>General</b> - may be applied to any argument * type * * <li> <b>Character</b> - may be applied to basic types which represent * Unicode characters: <tt>char</tt>, {@link Character}, <tt>byte</tt>, {@link * Byte}, <tt>short</tt>, and {@link Short}. This conversion may also be * applied to the types <tt>int</tt> and {@link Integer} when {@link * Character#isValidCodePoint} returns <tt>true</tt> * * <li> <b>Numeric</b> * * <ol> * * <li> <b>Integral</b> - may be applied to Java integral types: <tt>byte</tt>, * {@link Byte}, <tt>short</tt>, {@link Short}, <tt>int</tt> and {@link * Integer}, <tt>long</tt>, {@link Long}, and {@link java.math.BigInteger * BigInteger} * * <li><b>Floating Point</b> - may be applied to Java floating-point types: * <tt>float</tt>, {@link Float}, <tt>double</tt>, {@link Double}, and {@link * java.math.BigDecimal BigDecimal} * * </ol> * * <li> <b>Date/Time</b> - may be applied to Java types which are capable of * encoding a date or time: <tt>long</tt>, {@link Long}, {@link Calendar}, and * {@link Date}. * * <li> <b>Percent</b> - produces a literal <tt>'%'</tt> * (<tt>'&#92;u0025'</tt>) * * <li> <b>Line Separator</b> - produces the platform-specific line separator * * </ol> * * <p> The following table summarizes the supported conversions. Conversions * denoted by an upper-case character (i.e. <tt>'B'</tt>, <tt>'H'</tt>, * <tt>'S'</tt>, <tt>'C'</tt>, <tt>'X'</tt>, <tt>'E'</tt>, <tt>'G'</tt>, * <tt>'A'</tt>, and <tt>'T'</tt>) are the same as those for the corresponding * lower-case conversion characters except that the result is converted to * upper case according to the rules of the prevailing {@link java.util.Locale * Locale}. The result is equivalent to the following invocation of {@link * String#toUpperCase()} * * <pre> * out.toUpperCase() </pre> * * <table cellpadding=5 summary="genConv"> * * <tr><th valign="bottom"> Conversion * <th valign="bottom"> Argument Category * <th valign="bottom"> Description * * <tr><td valign="top"> <tt>'b'</tt>, <tt>'B'</tt> * <td valign="top"> general * <td> If the argument <i>arg</i> is <tt>null</tt>, then the result is * "<tt>false</tt>". If <i>arg</i> is a <tt>boolean</tt> or {@link * Boolean}, then the result is the string returned by {@link * String#valueOf(boolean) String.valueOf(arg)}. Otherwise, the result is * "true". * * <tr><td valign="top"> <tt>'h'</tt>, <tt>'H'</tt> * <td valign="top"> general * <td> If the argument <i>arg</i> is <tt>null</tt>, then the result is * "<tt>null</tt>". Otherwise, the result is obtained by invoking * <tt>Integer.toHexString(arg.hashCode())</tt>. * * <tr><td valign="top"> <tt>'s'</tt>, <tt>'S'</tt> * <td valign="top"> general * <td> If the argument <i>arg</i> is <tt>null</tt>, then the result is * "<tt>null</tt>". If <i>arg</i> implements {@link Formattable}, then * {@link Formattable#formatTo arg.formatTo} is invoked. Otherwise, the * result is obtained by invoking <tt>arg.toString()</tt>. * * <tr><td valign="top"><tt>'c'</tt>, <tt>'C'</tt> * <td valign="top"> character * <td> The result is a Unicode character * * <tr><td valign="top"><tt>'d'</tt> * <td valign="top"> integral * <td> The result is formatted as a decimal integer * * <tr><td valign="top"><tt>'o'</tt> * <td valign="top"> integral * <td> The result is formatted as an octal integer * * <tr><td valign="top"><tt>'x'</tt>, <tt>'X'</tt> * <td valign="top"> integral * <td> The result is formatted as a hexadecimal integer * * <tr><td valign="top"><tt>'e'</tt>, <tt>'E'</tt> * <td valign="top"> floating point * <td> The result is formatted as a decimal number in computerized * scientific notation * * <tr><td valign="top"><tt>'f'</tt> * <td valign="top"> floating point * <td> The result is formatted as a decimal number * * <tr><td valign="top"><tt>'g'</tt>, <tt>'G'</tt> * <td valign="top"> floating point * <td> The result is formatted using computerized scientific notation or * decimal format, depending on the precision and the value after rounding. * * <tr><td valign="top"><tt>'a'</tt>, <tt>'A'</tt> * <td valign="top"> floating point * <td> The result is formatted as a hexadecimal floating-point number with * a significand and an exponent * * <tr><td valign="top"><tt>'t'</tt>, <tt>'T'</tt> * <td valign="top"> date/time * <td> Prefix for date and time conversion characters. See <a * href="#dt">Date/Time Conversions</a>. * * <tr><td valign="top"><tt>'%'</tt> * <td valign="top"> percent * <td> The result is a literal <tt>'%'</tt> (<tt>'&#92;u0025'</tt>) * * <tr><td valign="top"><tt>'n'</tt> * <td valign="top"> line separator * <td> The result is the platform-specific line separator * * </table> * * <p> Any characters not explicitly defined as conversions are illegal and are * reserved for future extensions. * * <h4><a name="dt">Date/Time Conversions</a></h4> * * <p> The following date and time conversion suffix characters are defined for * the <tt>'t'</tt> and <tt>'T'</tt> conversions. The types are similar to but * not completely identical to those defined by GNU <tt>date</tt> and POSIX * <tt>strftime(3c)</tt>. Additional conversion types are provided to access * Java-specific functionality (e.g. <tt>'L'</tt> for milliseconds within the * second). * * <p> The following conversion characters are used for formatting times: * * <table cellpadding=5 summary="time"> * * <tr><td valign="top"> <tt>'H'</tt> * <td> Hour of the day for the 24-hour clock, formatted as two digits with * a leading zero as necessary i.e. <tt>00 - 23</tt>. * * <tr><td valign="top"><tt>'I'</tt> * <td> Hour for the 12-hour clock, formatted as two digits with a leading * zero as necessary, i.e. <tt>01 - 12</tt>. * * <tr><td valign="top"><tt>'k'</tt> * <td> Hour of the day for the 24-hour clock, i.e. <tt>0 - 23</tt>. * * <tr><td valign="top"><tt>'l'</tt> * <td> Hour for the 12-hour clock, i.e. <tt>1 - 12</tt>. * * <tr><td valign="top"><tt>'M'</tt> * <td> Minute within the hour formatted as two digits with a leading zero * as necessary, i.e. <tt>00 - 59</tt>. * * <tr><td valign="top"><tt>'S'</tt> * <td> Seconds within the minute, formatted as two digits with a leading * zero as necessary, i.e. <tt>00 - 60</tt> ("<tt>60</tt>" is a special * value required to support leap seconds). * * <tr><td valign="top"><tt>'L'</tt> * <td> Millisecond within the second formatted as three digits with * leading zeros as necessary, i.e. <tt>000 - 999</tt>. * * <tr><td valign="top"><tt>'N'</tt> * <td> Nanosecond within the second, formatted as nine digits with leading * zeros as necessary, i.e. <tt>000000000 - 999999999</tt>. * * <tr><td valign="top"><tt>'p'</tt> * <td> Locale-specific {@linkplain * java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker * in lower case, e.g."<tt>am</tt>" or "<tt>pm</tt>". Use of the conversion * prefix <tt>'T'</tt> forces this output to upper case. * * <tr><td valign="top"><tt>'z'</tt> * <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC&nbsp;822</a> * style numeric time zone offset from GMT, e.g. <tt>-0800</tt>. * * <tr><td valign="top"><tt>'Z'</tt> * <td> A string representing the abbreviation for the time zone. The * Formatter's locale will supersede the locale of the argument (if any). * * <tr><td valign="top"><tt>'s'</tt> * <td> Seconds since the beginning of the epoch starting at 1 January 1970 * <tt>00:00:00</tt> UTC, i.e. <tt>Long.MIN_VALUE/1000</tt> to * <tt>Long.MAX_VALUE/1000</tt>. * * <tr><td valign="top"><tt>'Q'</tt> * <td> Milliseconds since the beginning of the epoch starting at 1 January * 1970 <tt>00:00:00</tt> UTC, i.e. <tt>Long.MIN_VALUE</tt> to * <tt>Long.MAX_VALUE</tt>. * * </table> * * <p> The following conversion characters are used for formatting dates: * * <table cellpadding=5 summary="date"> * * <tr><td valign="top"><tt>'B'</tt> * <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths * full month name}, e.g. <tt>"January"</tt>, <tt>"February"</tt>. * * <tr><td valign="top"><tt>'b'</tt> * <td> Locale-specific {@linkplain * java.text.DateFormatSymbols#getShortMonths abbreviated month name}, * e.g. <tt>"Jan"</tt>, <tt>"Feb"</tt>. * * <tr><td valign="top"><tt>'h'</tt> * <td> Same as <tt>'b'</tt>. * * <tr><td valign="top"><tt>'A'</tt> * <td> Locale-specific full name of the {@linkplain * java.text.DateFormatSymbols#getWeekdays day of the week}, * e.g. <tt>"Sunday"</tt>, <tt>"Monday"</tt> * * <tr><td valign="top"><tt>'a'</tt> * <td> Locale-specific short name of the {@linkplain * java.text.DateFormatSymbols#getShortWeekdays day of the week}, * e.g. <tt>"Sun"</tt>, <tt>"Mon"</tt> * * <tr><td valign="top"><tt>'C'</tt> * <td> Four-digit year divided by <tt>100</tt>, formatted as two digits * with leading zero as necessary, i.e. <tt>00 - 99</tt> * * <tr><td valign="top"><tt>'Y'</tt> * <td> Year, formatted as at least four digits with leading zeros as * necessary, e.g. <tt>0092</tt> equals <tt>92</tt> CE for the Gregorian * calendar. * * <tr><td valign="top"><tt>'y'</tt> * <td> Last two digits of the year, formatted with leading zeros as * necessary, i.e. <tt>00 - 99</tt>. * * <tr><td valign="top"><tt>'j'</tt> * <td> Day of year, formatted as three digits with leading zeros as * necessary, e.g. <tt>001 - 366</tt> for the Gregorian calendar. * * <tr><td valign="top"><tt>'m'</tt> * <td> Month, formatted as two digits with leading zeros as necessary, * i.e. <tt>01 - 13</tt>. * * <tr><td valign="top"><tt>'d'</tt> * <td> Day of month, formatted as two digits with leading zeros as * necessary, i.e. <tt>01 - 31</tt> * * <tr><td valign="top"><tt>'e'</tt> * <td> Day of month, formatted as two digits, i.e. <tt>1 - 31</tt>. * * </table> * * <p> The following conversion characters are used for formatting common * date/time compositions. * * <table cellpadding=5 summary="composites"> * * <tr><td valign="top"><tt>'R'</tt> * <td> Time formatted for the 24-hour clock as <tt>"%tH:%tM"</tt> * * <tr><td valign="top"><tt>'T'</tt> * <td> Time formatted for the 24-hour clock as <tt>"%tH:%tM:%tS"</tt>. * * <tr><td valign="top"><tt>'r'</tt> * <td> Time formatted for the 12-hour clock as <tt>"%tI:%tM:%tS %Tp"</tt>. * The location of the morning or afternoon marker (<tt>'%Tp'</tt>) may be * locale-dependent. * * <tr><td valign="top"><tt>'D'</tt> * <td> Date formatted as <tt>"%tm/%td/%ty"</tt>. * * <tr><td valign="top"><tt>'F'</tt> * <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO&nbsp;8601</a> * complete date formatted as <tt>"%tY-%tm-%td"</tt>. * * <tr><td valign="top"><tt>'c'</tt> * <td> Date and time formatted as <tt>"%ta %tb %td %tT %tZ %tY"</tt>, * e.g. <tt>"Sun Jul 20 16:17:00 EDT 1969"</tt>. * * </table> * * <p> Any characters not explicitly defined as date/time conversion suffixes * are illegal and are reserved for future extensions. * * <h4> Flags </h4> * * <p> The following table summarizes the supported flags. <i>y</i> means the * flag is supported for the indicated argument types. * * <table cellpadding=5 summary="genConv"> * * <tr><th valign="bottom"> Flag <th valign="bottom"> General * <th valign="bottom"> Character <th valign="bottom"> Integral * <th valign="bottom"> Floating Point * <th valign="bottom"> Date/Time * <th valign="bottom"> Description * * <tr><td> '-' <td align="center" valign="top"> y * <td align="center" valign="top"> y * <td align="center" valign="top"> y * <td align="center" valign="top"> y * <td align="center" valign="top"> y * <td> The result will be left-justified. * * <tr><td> '#' <td align="center" valign="top"> y<sup>1</sup> * <td align="center" valign="top"> - * <td align="center" valign="top"> y<sup>3</sup> * <td align="center" valign="top"> y * <td align="center" valign="top"> - * <td> The result should use a conversion-dependent alternate form * * <tr><td> '+' <td align="center" valign="top"> - * <td align="center" valign="top"> - * <td align="center" valign="top"> y<sup>4</sup> * <td align="center" valign="top"> y * <td align="center" valign="top"> - * <td> The result will always include a sign * * <tr><td> '&nbsp;&nbsp;' <td align="center" valign="top"> - * <td align="center" valign="top"> - * <td align="center" valign="top"> y<sup>4</sup> * <td align="center" valign="top"> y * <td align="center" valign="top"> - * <td> The result will include a leading space for positive values * * <tr><td> '0' <td align="center" valign="top"> - * <td align="center" valign="top"> - * <td align="center" valign="top"> y * <td align="center" valign="top"> y * <td align="center" valign="top"> - * <td> The result will be zero-padded * * <tr><td> ',' <td align="center" valign="top"> - * <td align="center" valign="top"> - * <td align="center" valign="top"> y<sup>2</sup> * <td align="center" valign="top"> y<sup>5</sup> * <td align="center" valign="top"> - * <td> The result will include locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separators} * * <tr><td> '(' <td align="center" valign="top"> - * <td align="center" valign="top"> - * <td align="center" valign="top"> y<sup>4</sup> * <td align="center" valign="top"> y<sup>5</sup> * <td align="center"> - * <td> The result will enclose negative numbers in parentheses * * </table> * * <p> <sup>1</sup> Depends on the definition of {@link Formattable}. * * <p> <sup>2</sup> For <tt>'d'</tt> conversion only. * * <p> <sup>3</sup> For <tt>'o'</tt>, <tt>'x'</tt>, and <tt>'X'</tt> * conversions only. * * <p> <sup>4</sup> For <tt>'d'</tt>, <tt>'o'</tt>, <tt>'x'</tt>, and * <tt>'X'</tt> conversions applied to {@link java.math.BigInteger BigInteger} * or <tt>'d'</tt> applied to <tt>byte</tt>, {@link Byte}, <tt>short</tt>, {@link * Short}, <tt>int</tt> and {@link Integer}, <tt>long</tt>, and {@link Long}. * * <p> <sup>5</sup> For <tt>'e'</tt>, <tt>'E'</tt>, <tt>'f'</tt>, * <tt>'g'</tt>, and <tt>'G'</tt> conversions only. * * <p> Any characters not explicitly defined as flags are illegal and are * reserved for future extensions. * * <h4> Width </h4> * * <p> The width is the minimum number of characters to be written to the * output. For the line separator conversion, width is not applicable; if it * is provided, an exception will be thrown. * * <h4> Precision </h4> * * <p> For general argument types, the precision is the maximum number of * characters to be written to the output. * * <p> For the floating-point conversions <tt>'e'</tt>, <tt>'E'</tt>, and * <tt>'f'</tt> the precision is the number of digits after the decimal * separator. If the conversion is <tt>'g'</tt> or <tt>'G'</tt>, then the * precision is the total number of digits in the resulting magnitude after * rounding. If the conversion is <tt>'a'</tt> or <tt>'A'</tt>, then the * precision must not be specified. * * <p> For character, integral, and date/time argument types and the percent * and line separator conversions, the precision is not applicable; if a * precision is provided, an exception will be thrown. * * <h4> Argument Index </h4> * * <p> The argument index is a decimal integer indicating the position of the * argument in the argument list. The first argument is referenced by * "<tt>1$</tt>", the second by "<tt>2$</tt>", etc. * * <p> Another way to reference arguments by position is to use the * <tt>'&lt;'</tt> (<tt>'&#92;u003c'</tt>) flag, which causes the argument for * the previous format specifier to be re-used. For example, the following two * statements would produce identical strings: * * <blockquote><pre> * Calendar c = ...; * String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); * * String s2 = String.format("Duke's Birthday: %1$tm %&lt;te,%&lt;tY", c); * </pre></blockquote> * * <hr> * <h3><a name="detail">Details</a></h3> * * <p> This section is intended to provide behavioral details for formatting, * including conditions and exceptions, supported data types, localization, and * interactions between flags, conversions, and data types. For an overview of * formatting concepts, refer to the <a href="#summary">Summary</a> * * <p> Any characters not explicitly defined as conversions, date/time * conversion suffixes, or flags are illegal and are reserved for * future extensions. Use of such a character in a format string will * cause an {@link UnknownFormatConversionException} or {@link * UnknownFormatFlagsException} to be thrown. * * <p> If the format specifier contains a width or precision with an invalid * value or which is otherwise unsupported, then a {@link * IllegalFormatWidthException} or {@link IllegalFormatPrecisionException} * respectively will be thrown. * * <p> If a format specifier contains a conversion character that is not * applicable to the corresponding argument, then an {@link * IllegalFormatConversionException} will be thrown. * * <p> All specified exceptions may be thrown by any of the <tt>format</tt> * methods of <tt>Formatter</tt> as well as by any <tt>format</tt> convenience * methods such as {@link String#format(String,Object...) String.format} and * {@link java.io.PrintStream#printf(String,Object...) PrintStream.printf}. * * <p> Conversions denoted by an upper-case character (i.e. <tt>'B'</tt>, * <tt>'H'</tt>, <tt>'S'</tt>, <tt>'C'</tt>, <tt>'X'</tt>, <tt>'E'</tt>, * <tt>'G'</tt>, <tt>'A'</tt>, and <tt>'T'</tt>) are the same as those for the * corresponding lower-case conversion characters except that the result is * converted to upper case according to the rules of the prevailing {@link * java.util.Locale Locale}. The result is equivalent to the following * invocation of {@link String#toUpperCase()} * * <pre> * out.toUpperCase() </pre> * * <h4><a name="dgen">General</a></h4> * * <p> The following general conversions may be applied to any argument type: * * <table cellpadding=5 summary="dgConv"> * * <tr><td valign="top"> <tt>'b'</tt> * <td valign="top"> <tt>'&#92;u0062'</tt> * <td> Produces either "<tt>true</tt>" or "<tt>false</tt>" as returned by * {@link Boolean#toString(boolean)}. * * <p> If the argument is <tt>null</tt>, then the result is * "<tt>false</tt>". If the argument is a <tt>boolean</tt> or {@link * Boolean}, then the result is the string returned by {@link * String#valueOf(boolean) String.valueOf()}. Otherwise, the result is * "<tt>true</tt>". * * <p> If the <tt>'#'</tt> flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'B'</tt> * <td valign="top"> <tt>'&#92;u0042'</tt> * <td> The upper-case variant of <tt>'b'</tt>. * * <tr><td valign="top"> <tt>'h'</tt> * <td valign="top"> <tt>'&#92;u0068'</tt> * <td> Produces a string representing the hash code value of the object. * * <p> If the argument, <i>arg</i> is <tt>null</tt>, then the * result is "<tt>null</tt>". Otherwise, the result is obtained * by invoking <tt>Integer.toHexString(arg.hashCode())</tt>. * * <p> If the <tt>'#'</tt> flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'H'</tt> * <td valign="top"> <tt>'&#92;u0048'</tt> * <td> The upper-case variant of <tt>'h'</tt>. * * <tr><td valign="top"> <tt>'s'</tt> * <td valign="top"> <tt>'&#92;u0073'</tt> * <td> Produces a string. * * <p> If the argument is <tt>null</tt>, then the result is * "<tt>null</tt>". If the argument implements {@link Formattable}, then * its {@link Formattable#formatTo formatTo} method is invoked. * Otherwise, the result is obtained by invoking the argument's * <tt>toString()</tt> method. * * <p> If the <tt>'#'</tt> flag is given and the argument is not a {@link * Formattable} , then a {@link FormatFlagsConversionMismatchException} * will be thrown. * * <tr><td valign="top"> <tt>'S'</tt> * <td valign="top"> <tt>'&#92;u0053'</tt> * <td> The upper-case variant of <tt>'s'</tt>. * * </table> * * <p> The following <a name="dFlags">flags</a> apply to general conversions: * * <table cellpadding=5 summary="dFlags"> * * <tr><td valign="top"> <tt>'-'</tt> * <td valign="top"> <tt>'&#92;u002d'</tt> * <td> Left justifies the output. Spaces (<tt>'&#92;u0020'</tt>) will be * added at the end of the converted value as required to fill the minimum * width of the field. If the width is not provided, then a {@link * MissingFormatWidthException} will be thrown. If this flag is not given * then the output will be right-justified. * * <tr><td valign="top"> <tt>'#'</tt> * <td valign="top"> <tt>'&#92;u0023'</tt> * <td> Requires the output use an alternate form. The definition of the * form is specified by the conversion. * * </table> * * <p> The <a name="genWidth">width</a> is the minimum number of characters to * be written to the * output. If the length of the converted value is less than the width then * the output will be padded by <tt>'&nbsp;&nbsp;'</tt> (<tt>&#92;u0020'</tt>) * until the total number of characters equals the width. The padding is on * the left by default. If the <tt>'-'</tt> flag is given, then the padding * will be on the right. If the width is not specified then there is no * minimum. * * <p> The precision is the maximum number of characters to be written to the * output. The precision is applied before the width, thus the output will be * truncated to <tt>precision</tt> characters even if the width is greater than * the precision. If the precision is not specified then there is no explicit * limit on the number of characters. * * <h4><a name="dchar">Character</a></h4> * * This conversion may be applied to <tt>char</tt> and {@link Character}. It * may also be applied to the types <tt>byte</tt>, {@link Byte}, * <tt>short</tt>, and {@link Short}, <tt>int</tt> and {@link Integer} when * {@link Character#isValidCodePoint} returns <tt>true</tt>. If it returns * <tt>false</tt> then an {@link IllegalFormatCodePointException} will be * thrown. * * <table cellpadding=5 summary="charConv"> * * <tr><td valign="top"> <tt>'c'</tt> * <td valign="top"> <tt>'&#92;u0063'</tt> * <td> Formats the argument as a Unicode character as described in <a * href="../lang/Character.html#unicode">Unicode Character * Representation</a>. This may be more than one 16-bit <tt>char</tt> in * the case where the argument represents a supplementary character. * * <p> If the <tt>'#'</tt> flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'C'</tt> * <td valign="top"> <tt>'&#92;u0043'</tt> * <td> The upper-case variant of <tt>'c'</tt>. * * </table> * * <p> The <tt>'-'</tt> flag defined for <a href="#dFlags">General * conversions</a> applies. If the <tt>'#'</tt> flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <p> The width is defined as for <a href="#genWidth">General conversions</a>. * * <p> The precision is not applicable. If the precision is specified then an * {@link IllegalFormatPrecisionException} will be thrown. * * <h4><a name="dnum">Numeric</a></h4> * * <p> Numeric conversions are divided into the following categories: * * <ol> * * <li> <a href="#dnint"><b>Byte, Short, Integer, and Long</b></a> * * <li> <a href="#dnbint"><b>BigInteger</b></a> * * <li> <a href="#dndec"><b>Float and Double</b></a> * * <li> <a href="#dndec"><b>BigDecimal</b></a> * * </ol> * * <p> Numeric types will be formatted according to the following algorithm: * * <p><b><a name="l10n algorithm"> Number Localization Algorithm</a></b> * * <p> After digits are obtained for the integer part, fractional part, and * exponent (as appropriate for the data type), the following transformation * is applied: * * <ol> * * <li> Each digit character <i>d</i> in the string is replaced by a * locale-specific digit computed relative to the current locale's * {@linkplain java.text.DecimalFormatSymbols#getZeroDigit() zero digit} * <i>z</i>; that is <i>d&nbsp;-&nbsp;</i> <tt>'0'</tt> * <i>&nbsp;+&nbsp;z</i>. * * <li> If a decimal separator is present, a locale-specific {@linkplain * java.text.DecimalFormatSymbols#getDecimalSeparator decimal separator} is * substituted. * * <li> If the <tt>','</tt> (<tt>'&#92;u002c'</tt>) * <a name="l10n group">flag</a> is given, then the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is * inserted by scanning the integer part of the string from least significant * to most significant digits and inserting a separator at intervals defined by * the locale's {@linkplain java.text.DecimalFormat#getGroupingSize() grouping * size}. * * <li> If the <tt>'0'</tt> flag is given, then the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getZeroDigit() zero digits} are inserted * after the sign character, if any, and before the first non-zero digit, until * the length of the string is equal to the requested field width. * * <li> If the value is negative and the <tt>'('</tt> flag is given, then a * <tt>'('</tt> (<tt>'&#92;u0028'</tt>) is prepended and a <tt>')'</tt> * (<tt>'&#92;u0029'</tt>) is appended. * * <li> If the value is negative (or floating-point negative zero) and * <tt>'('</tt> flag is not given, then a <tt>'-'</tt> (<tt>'&#92;u002d'</tt>) * is prepended. * * <li> If the <tt>'+'</tt> flag is given and the value is positive or zero (or * floating-point positive zero), then a <tt>'+'</tt> (<tt>'&#92;u002b'</tt>) * will be prepended. * * </ol> * * <p> If the value is NaN or positive infinity the literal strings "NaN" or * "Infinity" respectively, will be output. If the value is negative infinity, * then the output will be "(Infinity)" if the <tt>'('</tt> flag is given * otherwise the output will be "-Infinity". These values are not localized. * * <p><a name="dnint"><b> Byte, Short, Integer, and Long </b></a> * * <p> The following conversions may be applied to <tt>byte</tt>, {@link Byte}, * <tt>short</tt>, {@link Short}, <tt>int</tt> and {@link Integer}, * <tt>long</tt>, and {@link Long}. * * <table cellpadding=5 summary="IntConv"> * * <tr><td valign="top"> <tt>'d'</tt> * <td valign="top"> <tt>'&#92;u0054'</tt> * <td> Formats the argument as a decimal integer. The <a * href="#l10n algorithm">localization algorithm</a> is applied. * * <p> If the <tt>'0'</tt> flag is given and the value is negative, then * the zero padding will occur after the sign. * * <p> If the <tt>'#'</tt> flag is given then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'o'</tt> * <td valign="top"> <tt>'&#92;u006f'</tt> * <td> Formats the argument as an integer in base eight. No localization * is applied. * * <p> If <i>x</i> is negative then the result will be an unsigned value * generated by adding 2<sup>n</sup> to the value where <tt>n</tt> is the * number of bits in the type as returned by the static <tt>SIZE</tt> field * in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short}, * {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long} * classes as appropriate. * * <p> If the <tt>'#'</tt> flag is given then the output will always begin * with the radix indicator <tt>'0'</tt>. * * <p> If the <tt>'0'</tt> flag is given then the output will be padded * with leading zeros to the field width following any indication of sign. * * <p> If <tt>'('</tt>, <tt>'+'</tt>, '&nbsp&nbsp;', or <tt>','</tt> flags * are given then a {@link FormatFlagsConversionMismatchException} will be * thrown. * * <tr><td valign="top"> <tt>'x'</tt> * <td valign="top"> <tt>'&#92;u0078'</tt> * <td> Formats the argument as an integer in base sixteen. No * localization is applied. * * <p> If <i>x</i> is negative then the result will be an unsigned value * generated by adding 2<sup>n</sup> to the value where <tt>n</tt> is the * number of bits in the type as returned by the static <tt>SIZE</tt> field * in the {@linkplain Byte#SIZE Byte}, {@linkplain Short#SIZE Short}, * {@linkplain Integer#SIZE Integer}, or {@linkplain Long#SIZE Long} * classes as appropriate. * * <p> If the <tt>'#'</tt> flag is given then the output will always begin * with the radix indicator <tt>"0x"</tt>. * * <p> If the <tt>'0'</tt> flag is given then the output will be padded to * the field width with leading zeros after the radix indicator or sign (if * present). * * <p> If <tt>'('</tt>, <tt>'&nbsp;&nbsp;'</tt>, <tt>'+'</tt>, or * <tt>','</tt> flags are given then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'X'</tt> * <td valign="top"> <tt>'&#92;u0058'</tt> * <td> The upper-case variant of <tt>'x'</tt>. The entire string * representing the number will be converted to {@linkplain * String#toUpperCase upper case} including the <tt>'x'</tt> (if any) and * all hexadecimal digits <tt>'a'</tt> - <tt>'f'</tt> * (<tt>'&#92;u0061'</tt> - <tt>'&#92;u0066'</tt>). * * </table> * * <p> If the conversion is <tt>'o'</tt>, <tt>'x'</tt>, or <tt>'X'</tt> and * both the <tt>'#'</tt> and the <tt>'0'</tt> flags are given, then result will * contain the radix indicator (<tt>'0'</tt> for octal and <tt>"0x"</tt> or * <tt>"0X"</tt> for hexadecimal), some number of zeros (based on the width), * and the value. * * <p> If the <tt>'-'</tt> flag is not given, then the space padding will occur * before the sign. * * <p> The following <a name="intFlags">flags</a> apply to numeric integral * conversions: * * <table cellpadding=5 summary="intFlags"> * * <tr><td valign="top"> <tt>'+'</tt> * <td valign="top"> <tt>'&#92;u002b'</tt> * <td> Requires the output to include a positive sign for all positive * numbers. If this flag is not given then only negative values will * include a sign. * * <p> If both the <tt>'+'</tt> and <tt>'&nbsp;&nbsp;'</tt> flags are given * then an {@link IllegalFormatFlagsException} will be thrown. * * <tr><td valign="top"> <tt>'&nbsp;&nbsp;'</tt> * <td valign="top"> <tt>'&#92;u0020'</tt> * <td> Requires the output to include a single extra space * (<tt>'&#92;u0020'</tt>) for non-negative values. * * <p> If both the <tt>'+'</tt> and <tt>'&nbsp;&nbsp;'</tt> flags are given * then an {@link IllegalFormatFlagsException} will be thrown. * * <tr><td valign="top"> <tt>'0'</tt> * <td valign="top"> <tt>'&#92;u0030'</tt> * <td> Requires the output to be padded with leading {@linkplain * java.text.DecimalFormatSymbols#getZeroDigit zeros} to the minimum field * width following any sign or radix indicator except when converting NaN * or infinity. If the width is not provided, then a {@link * MissingFormatWidthException} will be thrown. * * <p> If both the <tt>'-'</tt> and <tt>'0'</tt> flags are given then an * {@link IllegalFormatFlagsException} will be thrown. * * <tr><td valign="top"> <tt>','</tt> * <td valign="top"> <tt>'&#92;u002c'</tt> * <td> Requires the output to include the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as * described in the <a href="#l10n group">"group" section</a> of the * localization algorithm. * * <tr><td valign="top"> <tt>'('</tt> * <td valign="top"> <tt>'&#92;u0028'</tt> * <td> Requires the output to prepend a <tt>'('</tt> * (<tt>'&#92;u0028'</tt>) and append a <tt>')'</tt> * (<tt>'&#92;u0029'</tt>) to negative values. * * </table> * * <p> If no <a name="intdFlags">flags</a> are given the default formatting is * as follows: * * <ul> * * <li> The output is right-justified within the <tt>width</tt> * * <li> Negative numbers begin with a <tt>'-'</tt> (<tt>'&#92;u002d'</tt>) * * <li> Positive numbers and zero do not include a sign or extra leading * space * * <li> No grouping separators are included * * </ul> * * <p> The <a name="intWidth">width</a> is the minimum number of characters to * be written to the output. This includes any signs, digits, grouping * separators, radix indicator, and parentheses. If the length of the * converted value is less than the width then the output will be padded by * spaces (<tt>'&#92;u0020'</tt>) until the total number of characters equals * width. The padding is on the left by default. If <tt>'-'</tt> flag is * given then the padding will be on the right. If width is not specified then * there is no minimum. * * <p> The precision is not applicable. If precision is specified then an * {@link IllegalFormatPrecisionException} will be thrown. * * <p><a name="dnbint"><b> BigInteger </b></a> * * <p> The following conversions may be applied to {@link * java.math.BigInteger}. * * <table cellpadding=5 summary="BIntConv"> * * <tr><td valign="top"> <tt>'d'</tt> * <td valign="top"> <tt>'&#92;u0054'</tt> * <td> Requires the output to be formatted as a decimal integer. The <a * href="#l10n algorithm">localization algorithm</a> is applied. * * <p> If the <tt>'#'</tt> flag is given {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'o'</tt> * <td valign="top"> <tt>'&#92;u006f'</tt> * <td> Requires the output to be formatted as an integer in base eight. * No localization is applied. * * <p> If <i>x</i> is negative then the result will be a signed value * beginning with <tt>'-'</tt> (<tt>'&#92;u002d'</tt>). Signed output is * allowed for this type because unlike the primitive types it is not * possible to create an unsigned equivalent without assuming an explicit * data-type size. * * <p> If <i>x</i> is positive or zero and the <tt>'+'</tt> flag is given * then the result will begin with <tt>'+'</tt> (<tt>'&#92;u002b'</tt>). * * <p> If the <tt>'#'</tt> flag is given then the output will always begin * with <tt>'0'</tt> prefix. * * <p> If the <tt>'0'</tt> flag is given then the output will be padded * with leading zeros to the field width following any indication of sign. * * <p> If the <tt>','</tt> flag is given then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'x'</tt> * <td valign="top"> <tt>'&#92;u0078'</tt> * <td> Requires the output to be formatted as an integer in base * sixteen. No localization is applied. * * <p> If <i>x</i> is negative then the result will be a signed value * beginning with <tt>'-'</tt> (<tt>'&#92;u002d'</tt>). Signed output is * allowed for this type because unlike the primitive types it is not * possible to create an unsigned equivalent without assuming an explicit * data-type size. * * <p> If <i>x</i> is positive or zero and the <tt>'+'</tt> flag is given * then the result will begin with <tt>'+'</tt> (<tt>'&#92;u002b'</tt>). * * <p> If the <tt>'#'</tt> flag is given then the output will always begin * with the radix indicator <tt>"0x"</tt>. * * <p> If the <tt>'0'</tt> flag is given then the output will be padded to * the field width with leading zeros after the radix indicator or sign (if * present). * * <p> If the <tt>','</tt> flag is given then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'X'</tt> * <td valign="top"> <tt>'&#92;u0058'</tt> * <td> The upper-case variant of <tt>'x'</tt>. The entire string * representing the number will be converted to {@linkplain * String#toUpperCase upper case} including the <tt>'x'</tt> (if any) and * all hexadecimal digits <tt>'a'</tt> - <tt>'f'</tt> * (<tt>'&#92;u0061'</tt> - <tt>'&#92;u0066'</tt>). * * </table> * * <p> If the conversion is <tt>'o'</tt>, <tt>'x'</tt>, or <tt>'X'</tt> and * both the <tt>'#'</tt> and the <tt>'0'</tt> flags are given, then result will * contain the base indicator (<tt>'0'</tt> for octal and <tt>"0x"</tt> or * <tt>"0X"</tt> for hexadecimal), some number of zeros (based on the width), * and the value. * * <p> If the <tt>'0'</tt> flag is given and the value is negative, then the * zero padding will occur after the sign. * * <p> If the <tt>'-'</tt> flag is not given, then the space padding will occur * before the sign. * * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and * Long apply. The <a href="#intdFlags">default behavior</a> when no flags are * given is the same as for Byte, Short, Integer, and Long. * * <p> The specification of <a href="#intWidth">width</a> is the same as * defined for Byte, Short, Integer, and Long. * * <p> The precision is not applicable. If precision is specified then an * {@link IllegalFormatPrecisionException} will be thrown. * * <p><a name="dndec"><b> Float and Double</b></a> * * <p> The following conversions may be applied to <tt>float</tt>, {@link * Float}, <tt>double</tt> and {@link Double}. * * <table cellpadding=5 summary="floatConv"> * * <tr><td valign="top"> <tt>'e'</tt> * <td valign="top"> <tt>'&#92;u0065'</tt> * <td> Requires the output to be formatted using <a * name="scientific">computerized scientific notation</a>. The <a * href="#l10n algorithm">localization algorithm</a> is applied. * * <p> The formatting of the magnitude <i>m</i> depends upon its value. * * <p> If <i>m</i> is NaN or infinite, the literal strings "NaN" or * "Infinity", respectively, will be output. These values are not * localized. * * <p> If <i>m</i> is positive-zero or negative-zero, then the exponent * will be <tt>"+00"</tt>. * * <p> Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign * is described in the <a href="#l10n algorithm">localization * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its * value. * * <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup> * &lt;= <i>m</i> &lt; 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the * mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so * that 1 &lt;= <i>a</i> &lt; 10. The magnitude is then represented as the * integer part of <i>a</i>, as a single decimal digit, followed by the * decimal separator followed by decimal digits representing the fractional * part of <i>a</i>, followed by the exponent symbol <tt>'e'</tt> * (<tt>'&#92;u0065'</tt>), followed by the sign of the exponent, followed * by a representation of <i>n</i> as a decimal integer, as produced by the * method {@link Long#toString(long, int)}, and zero-padded to include at * least two digits. * * <p> The number of digits in the result for the fractional part of * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not * specified then the default value is <tt>6</tt>. If the precision is less * than the number of digits which would appear after the decimal point in * the string returned by {@link Float#toString(float)} or {@link * Double#toString(double)} respectively, then the value will be rounded * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up * algorithm}. Otherwise, zeros may be appended to reach the precision. * For a canonical representation of the value, use {@link * Float#toString(float)} or {@link Double#toString(double)} as * appropriate. * * <p>If the <tt>','</tt> flag is given, then an {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'E'</tt> * <td valign="top"> <tt>'&#92;u0045'</tt> * <td> The upper-case variant of <tt>'e'</tt>. The exponent symbol * will be <tt>'E'</tt> (<tt>'&#92;u0045'</tt>). * * <tr><td valign="top"> <tt>'g'</tt> * <td valign="top"> <tt>'&#92;u0067'</tt> * <td> Requires the output to be formatted in general scientific notation * as described below. The <a href="#l10n algorithm">localization * algorithm</a> is applied. * * <p> After rounding for the precision, the formatting of the resulting * magnitude <i>m</i> depends on its value. * * <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less * than 10<sup>precision</sup> then it is represented in <i><a * href="#decimal">decimal format</a></i>. * * <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to * 10<sup>precision</sup>, then it is represented in <i><a * href="#scientific">computerized scientific notation</a></i>. * * <p> The total number of significant digits in <i>m</i> is equal to the * precision. If the precision is not specified, then the default value is * <tt>6</tt>. If the precision is <tt>0</tt>, then it is taken to be * <tt>1</tt>. * * <p> If the <tt>'#'</tt> flag is given then an {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'G'</tt> * <td valign="top"> <tt>'&#92;u0047'</tt> * <td> The upper-case variant of <tt>'g'</tt>. * * <tr><td valign="top"> <tt>'f'</tt> * <td valign="top"> <tt>'&#92;u0066'</tt> * <td> Requires the output to be formatted using <a name="decimal">decimal * format</a>. The <a href="#l10n algorithm">localization algorithm</a> is * applied. * * <p> The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is * described in the <a href="#l10n algorithm">localization * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its * value. * * <p> If <i>m</i> NaN or infinite, the literal strings "NaN" or * "Infinity", respectively, will be output. These values are not * localized. * * <p> The magnitude is formatted as the integer part of <i>m</i>, with no * leading zeroes, followed by the decimal separator followed by one or * more decimal digits representing the fractional part of <i>m</i>. * * <p> The number of digits in the result for the fractional part of * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not * specified then the default value is <tt>6</tt>. If the precision is less * than the number of digits which would appear after the decimal point in * the string returned by {@link Float#toString(float)} or {@link * Double#toString(double)} respectively, then the value will be rounded * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up * algorithm}. Otherwise, zeros may be appended to reach the precision. * For a canonical representation of the value,use {@link * Float#toString(float)} or {@link Double#toString(double)} as * appropriate. * * <tr><td valign="top"> <tt>'a'</tt> * <td valign="top"> <tt>'&#92;u0061'</tt> * <td> Requires the output to be formatted in hexadecimal exponential * form. No localization is applied. * * <p> The result is a string that represents the sign and magnitude * (absolute value) of the argument <i>x</i>. * * <p> If <i>x</i> is negative or a negative-zero value then the result * will begin with <tt>'-'</tt> (<tt>'&#92;u002d'</tt>). * * <p> If <i>x</i> is positive or a positive-zero value and the * <tt>'+'</tt> flag is given then the result will begin with <tt>'+'</tt> * (<tt>'&#92;u002b'</tt>). * * <p> The formatting of the magnitude <i>m</i> depends upon its value. * * <ul> * * <li> If the value is NaN or infinite, the literal strings "NaN" or * "Infinity", respectively, will be output. * * <li> If <i>m</i> is zero then it is represented by the string * <tt>"0x0.0p0"</tt>. * * <li> If <i>m</i> is a <tt>double</tt> value with a normalized * representation then substrings are used to represent the significand and * exponent fields. The significand is represented by the characters * <tt>"0x1."</tt> followed by the hexadecimal representation of the rest * of the significand as a fraction. The exponent is represented by * <tt>'p'</tt> (<tt>'&#92;u0070'</tt>) followed by a decimal string of the * unbiased exponent as if produced by invoking {@link * Integer#toString(int) Integer.toString} on the exponent value. * * <li> If <i>m</i> is a <tt>double</tt> value with a subnormal * representation then the significand is represented by the characters * <tt>'0x0.'</tt> followed by the hexadecimal representation of the rest * of the significand as a fraction. The exponent is represented by * <tt>'p-1022'</tt>. Note that there must be at least one nonzero digit * in a subnormal significand. * * </ul> * * <p> If the <tt>'('</tt> or <tt>','</tt> flags are given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'A'</tt> * <td valign="top"> <tt>'&#92;u0041'</tt> * <td> The upper-case variant of <tt>'a'</tt>. The entire string * representing the number will be converted to upper case including the * <tt>'x'</tt> (<tt>'&#92;u0078'</tt>) and <tt>'p'</tt> * (<tt>'&#92;u0070'</tt> and all hexadecimal digits <tt>'a'</tt> - * <tt>'f'</tt> (<tt>'&#92;u0061'</tt> - <tt>'&#92;u0066'</tt>). * * </table> * * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and * Long apply. * * <p> If the <tt>'#'</tt> flag is given, then the decimal separator will * always be present. * * <p> If no <a name="floatdFlags">flags</a> are given the default formatting * is as follows: * * <ul> * * <li> The output is right-justified within the <tt>width</tt> * * <li> Negative numbers begin with a <tt>'-'</tt> * * <li> Positive numbers and positive zero do not include a sign or extra * leading space * * <li> No grouping separators are included * * <li> The decimal separator will only appear if a digit follows it * * </ul> * * <p> The <a name="floatDWidth">width</a> is the minimum number of characters * to be written to the output. This includes any signs, digits, grouping * separators, decimal separators, exponential symbol, radix indicator, * parentheses, and strings representing infinity and NaN as applicable. If * the length of the converted value is less than the width then the output * will be padded by spaces (<tt>'&#92;u0020'</tt>) until the total number of * characters equals width. The padding is on the left by default. If the * <tt>'-'</tt> flag is given then the padding will be on the right. If width * is not specified then there is no minimum. * * <p> If the <a name="floatDPrec">conversion</a> is <tt>'e'</tt>, * <tt>'E'</tt> or <tt>'f'</tt>, then the precision is the number of digits * after the decimal separator. If the precision is not specified, then it is * assumed to be <tt>6</tt>. * * <p> If the conversion is <tt>'g'</tt> or <tt>'G'</tt>, then the precision is * the total number of significant digits in the resulting magnitude after * rounding. If the precision is not specified, then the default value is * <tt>6</tt>. If the precision is <tt>0</tt>, then it is taken to be * <tt>1</tt>. * * <p> If the conversion is <tt>'a'</tt> or <tt>'A'</tt>, then the precision * is the number of hexadecimal digits after the decimal separator. If the * precision is not provided, then all of the digits as returned by {@link * Double#toHexString(double)} will be output. * * <p><a name="dndec"><b> BigDecimal </b></a> * * <p> The following conversions may be applied {@link java.math.BigDecimal * BigDecimal}. * * <table cellpadding=5 summary="floatConv"> * * <tr><td valign="top"> <tt>'e'</tt> * <td valign="top"> <tt>'&#92;u0065'</tt> * <td> Requires the output to be formatted using <a * name="scientific">computerized scientific notation</a>. The <a * href="#l10n algorithm">localization algorithm</a> is applied. * * <p> The formatting of the magnitude <i>m</i> depends upon its value. * * <p> If <i>m</i> is positive-zero or negative-zero, then the exponent * will be <tt>"+00"</tt>. * * <p> Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign * is described in the <a href="#l10n algorithm">localization * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its * value. * * <p> Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup> * &lt;= <i>m</i> &lt; 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the * mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so * that 1 &lt;= <i>a</i> &lt; 10. The magnitude is then represented as the * integer part of <i>a</i>, as a single decimal digit, followed by the * decimal separator followed by decimal digits representing the fractional * part of <i>a</i>, followed by the exponent symbol <tt>'e'</tt> * (<tt>'&#92;u0065'</tt>), followed by the sign of the exponent, followed * by a representation of <i>n</i> as a decimal integer, as produced by the * method {@link Long#toString(long, int)}, and zero-padded to include at * least two digits. * * <p> The number of digits in the result for the fractional part of * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not * specified then the default value is <tt>6</tt>. If the precision is * less than the number of digits which would appear after the decimal * point in the string returned by {@link Float#toString(float)} or {@link * Double#toString(double)} respectively, then the value will be rounded * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up * algorithm}. Otherwise, zeros may be appended to reach the precision. * For a canonical representation of the value, use {@link * BigDecimal#toString()}. * * <p> If the <tt>','</tt> flag is given, then an {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'E'</tt> * <td valign="top"> <tt>'&#92;u0045'</tt> * <td> The upper-case variant of <tt>'e'</tt>. The exponent symbol * will be <tt>'E'</tt> (<tt>'&#92;u0045'</tt>). * * <tr><td valign="top"> <tt>'g'</tt> * <td valign="top"> <tt>'&#92;u0067'</tt> * <td> Requires the output to be formatted in general scientific notation * as described below. The <a href="#l10n algorithm">localization * algorithm</a> is applied. * * <p> After rounding for the precision, the formatting of the resulting * magnitude <i>m</i> depends on its value. * * <p> If <i>m</i> is greater than or equal to 10<sup>-4</sup> but less * than 10<sup>precision</sup> then it is represented in <i><a * href="#decimal">decimal format</a></i>. * * <p> If <i>m</i> is less than 10<sup>-4</sup> or greater than or equal to * 10<sup>precision</sup>, then it is represented in <i><a * href="#scientific">computerized scientific notation</a></i>. * * <p> The total number of significant digits in <i>m</i> is equal to the * precision. If the precision is not specified, then the default value is * <tt>6</tt>. If the precision is <tt>0</tt>, then it is taken to be * <tt>1</tt>. * * <p> If the <tt>'#'</tt> flag is given then an {@link * FormatFlagsConversionMismatchException} will be thrown. * * <tr><td valign="top"> <tt>'G'</tt> * <td valign="top"> <tt>'&#92;u0047'</tt> * <td> The upper-case variant of <tt>'g'</tt>. * * <tr><td valign="top"> <tt>'f'</tt> * <td valign="top"> <tt>'&#92;u0066'</tt> * <td> Requires the output to be formatted using <a name="decimal">decimal * format</a>. The <a href="#l10n algorithm">localization algorithm</a> is * applied. * * <p> The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is * described in the <a href="#l10n algorithm">localization * algorithm</a>. The formatting of the magnitude <i>m</i> depends upon its * value. * * <p> The magnitude is formatted as the integer part of <i>m</i>, with no * leading zeroes, followed by the decimal separator followed by one or * more decimal digits representing the fractional part of <i>m</i>. * * <p> The number of digits in the result for the fractional part of * <i>m</i> or <i>a</i> is equal to the precision. If the precision is not * specified then the default value is <tt>6</tt>. If the precision is * less than the number of digits which would appear after the decimal * point in the string returned by {@link Float#toString(float)} or {@link * Double#toString(double)} respectively, then the value will be rounded * using the {@linkplain java.math.BigDecimal#ROUND_HALF_UP round half up * algorithm}. Otherwise, zeros may be appended to reach the precision. * For a canonical representation of the value, use {@link * BigDecimal#toString()}. * * </table> * * <p> All <a href="#intFlags">flags</a> defined for Byte, Short, Integer, and * Long apply. * * <p> If the <tt>'#'</tt> flag is given, then the decimal separator will * always be present. * * <p> The <a href="#floatdFlags">default behavior</a> when no flags are * given is the same as for Float and Double. * * <p> The specification of <a href="#floatDWidth">width</a> and <a * href="#floatDPrec">precision</a> is the same as defined for Float and * Double. * * <h4><a name="ddt">Date/Time</a></h4> * * <p> This conversion may be applied to <tt>long</tt>, {@link Long}, {@link * Calendar}, and {@link Date}. * * <table cellpadding=5 summary="DTConv"> * * <tr><td valign="top"> <tt>'t'</tt> * <td valign="top"> <tt>'&#92;u0074'</tt> * <td> Prefix for date and time conversion characters. * <tr><td valign="top"> <tt>'T'</tt> * <td valign="top"> <tt>'&#92;u0054'</tt> * <td> The upper-case variant of <tt>'t'</tt>. * * </table> * * <p> The following date and time conversion character suffixes are defined * for the <tt>'t'</tt> and <tt>'T'</tt> conversions. The types are similar to * but not completely identical to those defined by GNU <tt>date</tt> and * POSIX <tt>strftime(3c)</tt>. Additional conversion types are provided to * access Java-specific functionality (e.g. <tt>'L'</tt> for milliseconds * within the second). * * <p> The following conversion characters are used for formatting times: * * <table cellpadding=5 summary="time"> * * <tr><td valign="top"> <tt>'H'</tt> * <td valign="top"> <tt>'&#92;u0048'</tt> * <td> Hour of the day for the 24-hour clock, formatted as two digits with * a leading zero as necessary i.e. <tt>00 - 23</tt>. <tt>00</tt> * corresponds to midnight. * * <tr><td valign="top"><tt>'I'</tt> * <td valign="top"> <tt>'&#92;u0049'</tt> * <td> Hour for the 12-hour clock, formatted as two digits with a leading * zero as necessary, i.e. <tt>01 - 12</tt>. <tt>01</tt> corresponds to * one o'clock (either morning or afternoon). * * <tr><td valign="top"><tt>'k'</tt> * <td valign="top"> <tt>'&#92;u006b'</tt> * <td> Hour of the day for the 24-hour clock, i.e. <tt>0 - 23</tt>. * <tt>0</tt> corresponds to midnight. * * <tr><td valign="top"><tt>'l'</tt> * <td valign="top"> <tt>'&#92;u006c'</tt> * <td> Hour for the 12-hour clock, i.e. <tt>1 - 12</tt>. <tt>1</tt> * corresponds to one o'clock (either morning or afternoon). * * <tr><td valign="top"><tt>'M'</tt> * <td valign="top"> <tt>'&#92;u004d'</tt> * <td> Minute within the hour formatted as two digits with a leading zero * as necessary, i.e. <tt>00 - 59</tt>. * * <tr><td valign="top"><tt>'S'</tt> * <td valign="top"> <tt>'&#92;u0053'</tt> * <td> Seconds within the minute, formatted as two digits with a leading * zero as necessary, i.e. <tt>00 - 60</tt> ("<tt>60</tt>" is a special * value required to support leap seconds). * * <tr><td valign="top"><tt>'L'</tt> * <td valign="top"> <tt>'&#92;u004c'</tt> * <td> Millisecond within the second formatted as three digits with * leading zeros as necessary, i.e. <tt>000 - 999</tt>. * * <tr><td valign="top"><tt>'N'</tt> * <td valign="top"> <tt>'&#92;u004e'</tt> * <td> Nanosecond within the second, formatted as nine digits with leading * zeros as necessary, i.e. <tt>000000000 - 999999999</tt>. The precision * of this value is limited by the resolution of the underlying operating * system or hardware. * * <tr><td valign="top"><tt>'p'</tt> * <td valign="top"> <tt>'&#92;u0070'</tt> * <td> Locale-specific {@linkplain * java.text.DateFormatSymbols#getAmPmStrings morning or afternoon} marker * in lower case, e.g."<tt>am</tt>" or "<tt>pm</tt>". Use of the * conversion prefix <tt>'T'</tt> forces this output to upper case. (Note * that <tt>'p'</tt> produces lower-case output. This is different from * GNU <tt>date</tt> and POSIX <tt>strftime(3c)</tt> which produce * upper-case output.) * * <tr><td valign="top"><tt>'z'</tt> * <td valign="top"> <tt>'&#92;u007a'</tt> * <td> <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC&nbsp;822</a> * style numeric time zone offset from GMT, e.g. <tt>-0800</tt>. * * <tr><td valign="top"><tt>'Z'</tt> * <td valign="top"> <tt>'&#92;u005a'</tt> * <td> A string representing the abbreviation for the time zone. * * <tr><td valign="top"><tt>'s'</tt> * <td valign="top"> <tt>'&#92;u0073'</tt> * <td> Seconds since the beginning of the epoch starting at 1 January 1970 * <tt>00:00:00</tt> UTC, i.e. <tt>Long.MIN_VALUE/1000</tt> to * <tt>Long.MAX_VALUE/1000</tt>. * * <tr><td valign="top"><tt>'Q'</tt> * <td valign="top"> <tt>'&#92;u004f'</tt> * <td> Milliseconds since the beginning of the epoch starting at 1 January * 1970 <tt>00:00:00</tt> UTC, i.e. <tt>Long.MIN_VALUE</tt> to * <tt>Long.MAX_VALUE</tt>. The precision of this value is limited by * the resolution of the underlying operating system or hardware. * * </table> * * <p> The following conversion characters are used for formatting dates: * * <table cellpadding=5 summary="date"> * * <tr><td valign="top"><tt>'B'</tt> * <td valign="top"> <tt>'&#92;u0042'</tt> * <td> Locale-specific {@linkplain java.text.DateFormatSymbols#getMonths * full month name}, e.g. <tt>"January"</tt>, <tt>"February"</tt>. * * <tr><td valign="top"><tt>'b'</tt> * <td valign="top"> <tt>'&#92;u0062'</tt> * <td> Locale-specific {@linkplain * java.text.DateFormatSymbols#getShortMonths abbreviated month name}, * e.g. <tt>"Jan"</tt>, <tt>"Feb"</tt>. * * <tr><td valign="top"><tt>'h'</tt> * <td valign="top"> <tt>'&#92;u0068'</tt> * <td> Same as <tt>'b'</tt>. * * <tr><td valign="top"><tt>'A'</tt> * <td valign="top"> <tt>'&#92;u0041'</tt> * <td> Locale-specific full name of the {@linkplain * java.text.DateFormatSymbols#getWeekdays day of the week}, * e.g. <tt>"Sunday"</tt>, <tt>"Monday"</tt> * * <tr><td valign="top"><tt>'a'</tt> * <td valign="top"> <tt>'&#92;u0061'</tt> * <td> Locale-specific short name of the {@linkplain * java.text.DateFormatSymbols#getShortWeekdays day of the week}, * e.g. <tt>"Sun"</tt>, <tt>"Mon"</tt> * * <tr><td valign="top"><tt>'C'</tt> * <td valign="top"> <tt>'&#92;u0043'</tt> * <td> Four-digit year divided by <tt>100</tt>, formatted as two digits * with leading zero as necessary, i.e. <tt>00 - 99</tt> * * <tr><td valign="top"><tt>'Y'</tt> * <td valign="top"> <tt>'&#92;u0059'</tt> <td> Year, formatted to at least * four digits with leading zeros as necessary, e.g. <tt>0092</tt> equals * <tt>92</tt> CE for the Gregorian calendar. * * <tr><td valign="top"><tt>'y'</tt> * <td valign="top"> <tt>'&#92;u0079'</tt> * <td> Last two digits of the year, formatted with leading zeros as * necessary, i.e. <tt>00 - 99</tt>. * * <tr><td valign="top"><tt>'j'</tt> * <td valign="top"> <tt>'&#92;u006a'</tt> * <td> Day of year, formatted as three digits with leading zeros as * necessary, e.g. <tt>001 - 366</tt> for the Gregorian calendar. * <tt>001</tt> corresponds to the first day of the year. * * <tr><td valign="top"><tt>'m'</tt> * <td valign="top"> <tt>'&#92;u006d'</tt> * <td> Month, formatted as two digits with leading zeros as necessary, * i.e. <tt>01 - 13</tt>, where "<tt>01</tt>" is the first month of the * year and ("<tt>13</tt>" is a special value required to support lunar * calendars). * * <tr><td valign="top"><tt>'d'</tt> * <td valign="top"> <tt>'&#92;u0064'</tt> * <td> Day of month, formatted as two digits with leading zeros as * necessary, i.e. <tt>01 - 31</tt>, where "<tt>01</tt>" is the first day * of the month. * * <tr><td valign="top"><tt>'e'</tt> * <td valign="top"> <tt>'&#92;u0065'</tt> * <td> Day of month, formatted as two digits, i.e. <tt>1 - 31</tt> where * "<tt>1</tt>" is the first day of the month. * * </table> * * <p> The following conversion characters are used for formatting common * date/time compositions. * * <table cellpadding=5 summary="composites"> * * <tr><td valign="top"><tt>'R'</tt> * <td valign="top"> <tt>'&#92;u0052'</tt> * <td> Time formatted for the 24-hour clock as <tt>"%tH:%tM"</tt> * * <tr><td valign="top"><tt>'T'</tt> * <td valign="top"> <tt>'&#92;u0054'</tt> * <td> Time formatted for the 24-hour clock as <tt>"%tH:%tM:%tS"</tt>. * * <tr><td valign="top"><tt>'r'</tt> * <td valign="top"> <tt>'&#92;u0072'</tt> * <td> Time formatted for the 12-hour clock as <tt>"%tI:%tM:%tS * %Tp"</tt>. The location of the morning or afternoon marker * (<tt>'%Tp'</tt>) may be locale-dependent. * * <tr><td valign="top"><tt>'D'</tt> * <td valign="top"> <tt>'&#92;u0044'</tt> * <td> Date formatted as <tt>"%tm/%td/%ty"</tt>. * * <tr><td valign="top"><tt>'F'</tt> * <td valign="top"> <tt>'&#92;u0046'</tt> * <td> <a href="http://www.w3.org/TR/NOTE-datetime">ISO&nbsp;8601</a> * complete date formatted as <tt>"%tY-%tm-%td"</tt>. * * <tr><td valign="top"><tt>'c'</tt> * <td valign="top"> <tt>'&#92;u0063'</tt> * <td> Date and time formatted as <tt>"%ta %tb %td %tT %tZ %tY"</tt>, * e.g. <tt>"Sun Jul 20 16:17:00 EDT 1969"</tt>. * * </table> * * <p> The <tt>'-'</tt> flag defined for <a href="#dFlags">General * conversions</a> applies. If the <tt>'#'</tt> flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * * <p> The <a name="dtWidth">width</a> is the minimum number of characters to * be written to the output. If the length of the converted value is less than * the <tt>width</tt> then the output will be padded by spaces * (<tt>'&#92;u0020'</tt>) until the total number of characters equals width. * The padding is on the left by default. If the <tt>'-'</tt> flag is given * then the padding will be on the right. If width is not specified then there * is no minimum. * * <p> The precision is not applicable. If the precision is specified then an * {@link IllegalFormatPrecisionException} will be thrown. * * <h4><a name="dper">Percent</a></h4> * * <p> The conversion does not correspond to any argument. * * <table cellpadding=5 summary="DTConv"> * * <tr><td valign="top"><tt>'%'</tt> * <td> The result is a literal <tt>'%'</tt> (<tt>'&#92;u0025'</tt>) * * <p> The <a name="dtWidth">width</a> is the minimum number of characters to * be written to the output including the <tt>'%'</tt>. If the length of the * converted value is less than the <tt>width</tt> then the output will be * padded by spaces (<tt>'&#92;u0020'</tt>) until the total number of * characters equals width. The padding is on the left. If width is not * specified then just the <tt>'%'</tt> is output. * * <p> The <tt>'-'</tt> flag defined for <a href="#dFlags">General * conversions</a> applies. If any other flags are provided, then a * {@link FormatFlagsConversionMismatchException} will be thrown. * * <p> The precision is not applicable. If the precision is specified an * {@link IllegalFormatPrecisionException} will be thrown. * * </table> * * <h4><a name="dls">Line Separator</a></h4> * * <p> The conversion does not correspond to any argument. * * <table cellpadding=5 summary="DTConv"> * * <tr><td valign="top"><tt>'n'</tt> * <td> the platform-specific line separator as returned by {@link * System#getProperty System.getProperty("line.separator")}. * * </table> * * <p> Flags, width, and precision are not applicable. If any are provided an * {@link IllegalFormatFlagsException}, {@link IllegalFormatWidthException}, * and {@link IllegalFormatPrecisionException}, respectively will be thrown. * * <h4><a name="dpos">Argument Index</a></h4> * * <p> Format specifiers can reference arguments in three ways: * * <ul> * * <li> <i>Explicit indexing</i> is used when the format specifier contains an * argument index. The argument index is a decimal integer indicating the * position of the argument in the argument list. The first argument is * referenced by "<tt>1$</tt>", the second by "<tt>2$</tt>", etc. An argument * may be referenced more than once. * * <p> For example: * * <blockquote><pre> * formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s", * "a", "b", "c", "d") * // -&gt; "d c b a d c b a" * </pre></blockquote> * * <li> <i>Relative indexing</i> is used when the format specifier contains a * <tt>'&lt;'</tt> (<tt>'&#92;u003c'</tt>) flag which causes the argument for * the previous format specifier to be re-used. If there is no previous * argument, then a {@link MissingFormatArgumentException} is thrown. * * <blockquote><pre> * formatter.format("%s %s %&lt;s %&lt;s", "a", "b", "c", "d") * // -&gt; "a b b b" * // "c" and "d" are ignored because they are not referenced * </pre></blockquote> * * <li> <i>Ordinary indexing</i> is used when the format specifier contains * neither an argument index nor a <tt>'&lt;'</tt> flag. Each format specifier * which uses ordinary indexing is assigned a sequential implicit index into * argument list which is independent of the indices used by explicit or * relative indexing. * * <blockquote><pre> * formatter.format("%s %s %s %s", "a", "b", "c", "d") * // -&gt; "a b c d" * </pre></blockquote> * * </ul> * * <p> It is possible to have a format string which uses all forms of indexing, * for example: * * <blockquote><pre> * formatter.format("%2$s %s %&lt;s %s", "a", "b", "c", "d") * // -&gt; "b a a b" * // "c" and "d" are ignored because they are not referenced * </pre></blockquote> * * <p> The maximum number of arguments is limited by the maximum dimension of a * Java array as defined by the <a * href="http://java.sun.com/docs/books/vmspec/">Java Virtual Machine * Specification</a>. If the argument index is does not correspond to an * available argument, then a {@link MissingFormatArgumentException} is thrown. * * <p> If there are more arguments than format specifiers, the extra arguments * are ignored. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @author Iris Clark * @since 1.5 */ public final class Formatter implements Closeable, Flushable { private Appendable a; private Locale l; private IOException lastException; private char zero = '0'; private static double scaleUp; // 1 (sign) + 19 (max # sig digits) + 1 ('.') + 1 ('e') + 1 (sign) // + 3 (max # exp digits) + 4 (error) = 30 private static final int MAX_FD_CHARS = 30; // Initialize internal data. private void init(Appendable a, Locale l) { this.a = a; this.l = l; setZero(); } /** {@collect.stats} * {@description.open} * Constructs a new formatter. * * <p> The destination of the formatted output is a {@link StringBuilder} * which may be retrieved by invoking {@link #out out()} and whose * current content may be converted into a string by invoking {@link * #toString toString()}. The locale used is the {@linkplain * Locale#getDefault() default locale} for this instance of the Java * virtual machine. * {@description.close} */ public Formatter() { init(new StringBuilder(), Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified destination. * * <p> The locale used is the {@linkplain Locale#getDefault() default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param a * Destination for the formatted output. If <tt>a</tt> is * <tt>null</tt> then a {@link StringBuilder} will be created. */ public Formatter(Appendable a) { if (a == null) a = new StringBuilder(); init(a, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified locale. * * <p> The destination of the formatted output is a {@link StringBuilder} * which may be retrieved by invoking {@link #out out()} and whose current * content may be converted into a string by invoking {@link #toString * toString()}. * {@description.close} * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. */ public Formatter(Locale l) { init(new StringBuilder(), l); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified destination and locale. * {@description.close} * * @param a * Destination for the formatted output. If <tt>a</tt> is * <tt>null</tt> then a {@link StringBuilder} will be created. * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. */ public Formatter(Appendable a, Locale l) { if (a == null) a = new StringBuilder(); init(a, l); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file name. * * <p> The charset used is the {@linkplain * java.nio.charset.Charset#defaultCharset() default charset} for this * instance of the Java virtual machine. * * <p> The locale used is the {@linkplain Locale#getDefault() default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param fileName * The name of the file to use as the destination of this * formatter. If the file exists then it will be truncated to * zero size; otherwise, a new file will be created. The output * will be written to the file and is buffered. * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(fileName)} denies write * access to the file * * @throws FileNotFoundException * If the given file name does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file */ public Formatter(String fileName) throws FileNotFoundException { init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))), Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file name and charset. * * <p> The locale used is the {@linkplain Locale#getDefault default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param fileName * The name of the file to use as the destination of this * formatter. If the file exists then it will be truncated to * zero size; otherwise, a new file will be created. The output * will be written to the file and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws FileNotFoundException * If the given file name does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(fileName)} denies write * access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { this(fileName, csn, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file name, charset, and * locale. * {@description.close} * * @param fileName * The name of the file to use as the destination of this * formatter. If the file exists then it will be truncated to * zero size; otherwise, a new file will be created. The output * will be written to the file and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. * * @throws FileNotFoundException * If the given file name does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(fileName)} denies write * access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(String fileName, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException { init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), csn)), l); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file. * * <p> The charset used is the {@linkplain * java.nio.charset.Charset#defaultCharset() default charset} for this * instance of the Java virtual machine. * * <p> The locale used is the {@linkplain Locale#getDefault() default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param file * The file to use as the destination of this formatter. If the * file exists then it will be truncated to zero size; otherwise, * a new file will be created. The output will be written to the * file and is buffered. * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(file.getPath())} denies * write access to the file * * @throws FileNotFoundException * If the given file object does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file */ public Formatter(File file) throws FileNotFoundException { init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))), Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file and charset. * * <p> The locale used is the {@linkplain Locale#getDefault default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param file * The file to use as the destination of this formatter. If the * file exists then it will be truncated to zero size; otherwise, * a new file will be created. The output will be written to the * file and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws FileNotFoundException * If the given file object does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(file.getPath())} denies * write access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { this(file, csn, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified file, charset, and * locale. * {@description.close} * * @param file * The file to use as the destination of this formatter. If the * file exists then it will be truncated to zero size; otherwise, * a new file will be created. The output will be written to the * file and is buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. * * @throws FileNotFoundException * If the given file object does not denote an existing, writable * regular file and a new regular file of that name cannot be * created, or if some other error occurs while opening or * creating the file * * @throws SecurityException * If a security manager is present and {@link * SecurityManager#checkWrite checkWrite(file.getPath())} denies * write access to the file * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(File file, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException { init(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), csn)), l); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified print stream. * * <p> The locale used is the {@linkplain Locale#getDefault() default * locale} for this instance of the Java virtual machine. * * <p> Characters are written to the given {@link java.io.PrintStream * PrintStream} object and are therefore encoded using that object's * charset. * {@description.close} * * @param ps * The stream to use as the destination of this formatter. */ public Formatter(PrintStream ps) { if (ps == null) throw new NullPointerException(); init((Appendable)ps, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified output stream. * * <p> The charset used is the {@linkplain * java.nio.charset.Charset#defaultCharset() default charset} for this * instance of the Java virtual machine. * * <p> The locale used is the {@linkplain Locale#getDefault() default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param os * The output stream to use as the destination of this formatter. * The output will be buffered. */ public Formatter(OutputStream os) { init(new BufferedWriter(new OutputStreamWriter(os)), Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified output stream and * charset. * * <p> The locale used is the {@linkplain Locale#getDefault default * locale} for this instance of the Java virtual machine. * {@description.close} * * @param os * The output stream to use as the destination of this formatter. * The output will be buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException { this(os, csn, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new formatter with the specified output stream, charset, * and locale. * {@description.close} * * @param os * The output stream to use as the destination of this formatter. * The output will be buffered. * * @param csn * The name of a supported {@linkplain java.nio.charset.Charset * charset} * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. * * @throws UnsupportedEncodingException * If the named charset is not supported */ public Formatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException { init(new BufferedWriter(new OutputStreamWriter(os, csn)), l); } private void setZero() { if ((l != null) && !l.equals(Locale.US)) { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); zero = dfs.getZeroDigit(); } } /** {@collect.stats} * {@description.open} * Returns the locale set by the construction of this formatter. * * <p> The {@link #format(java.util.Locale,String,Object...) format} method * for this object which has a locale argument does not change this value. * {@description.close} * * @return <tt>null</tt> if no localization is applied, otherwise a * locale * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method */ public Locale locale() { ensureOpen(); return l; } /** {@collect.stats} * {@description.open} * Returns the destination for the output. * {@description.close} * * @return The destination for the output * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method */ public Appendable out() { ensureOpen(); return a; } /** {@collect.stats} * {@description.open} * Returns the result of invoking <tt>toString()</tt> on the destination * for the output. For example, the following code formats text into a * {@link StringBuilder} then retrieves the resultant string: * * <blockquote><pre> * Formatter f = new Formatter(); * f.format("Last reboot at %tc", lastRebootDate); * String s = f.toString(); * // -&gt; s == "Last reboot at Sat Jan 01 00:00:00 PST 2000" * </pre></blockquote> * * <p> An invocation of this method behaves in exactly the same way as the * invocation * * <pre> * out().toString() </pre> * * <p> Depending on the specification of <tt>toString</tt> for the {@link * Appendable}, the returned string may or may not contain the characters * written to the destination. For instance, buffers typically return * their contents in <tt>toString()</tt>, but streams cannot since the * data is discarded. * {@description.close} * * @return The result of invoking <tt>toString()</tt> on the destination * for the output * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method */ public String toString() { ensureOpen(); return a.toString(); } /** {@collect.stats} * {@description.open} * Flushes this formatter. If the destination implements the {@link * java.io.Flushable} interface, its <tt>flush</tt> method will be invoked. * * <p> Flushing a formatter writes any buffered output in the destination * to the underlying stream. * {@description.close} * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method */ public void flush() { ensureOpen(); if (a instanceof Flushable) { try { ((Flushable)a).flush(); } catch (IOException ioe) { lastException = ioe; } } } /** {@collect.stats} * {@description.open} * Closes this formatter. If the destination implements the {@link * java.io.Closeable} interface, its <tt>close</tt> method will be invoked. * * <p> Closing a formatter allows it to release resources it may be holding * (such as open files). If the formatter is already closed, then invoking * this method has no effect. * * <p> Attempting to invoke any methods except {@link #ioException()} in * this formatter after it has been closed will result in a {@link * FormatterClosedException}. * {@description.close} */ public void close() { if (a == null) return; try { if (a instanceof Closeable) ((Closeable)a).close(); } catch (IOException ioe) { lastException = ioe; } finally { a = null; } } private void ensureOpen() { if (a == null) throw new FormatterClosedException(); } /** {@collect.stats} * {@description.open} * Returns the <tt>IOException</tt> last thrown by this formatter's {@link * Appendable}. * * <p> If the destination's <tt>append()</tt> method never throws * <tt>IOException</tt>, then this method will always return <tt>null</tt>. * {@description.close} * * @return The last exception thrown by the Appendable or <tt>null</tt> if * no such exception exists. */ public IOException ioException() { return lastException; } /** {@collect.stats} * {@description.open} * Writes a formatted string to this object's destination using the * specified format string and arguments. The locale used is the one * defined during the construction of this formatter. * {@description.close} * * @param format * A format string as described in <a href="#syntax">Format string * syntax</a>. * * @param args * Arguments referenced by the format specifiers in the format * string. If there are more arguments than format specifiers, the * extra arguments are ignored. The maximum number of arguments is * limited by the maximum dimension of a Java array as defined by * the <a href="http://java.sun.com/docs/books/vmspec/">Java * Virtual Machine Specification</a>. * * @throws IllegalFormatException * If a format string contains an illegal syntax, a format * specifier that is incompatible with the given arguments, * insufficient arguments given the format string, or other * illegal conditions. For specification of all possible * formatting errors, see the <a href="#detail">Details</a> * section of the formatter class specification. * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method * * @return This formatter */ public Formatter format(String format, Object ... args) { return format(l, format, args); } /** {@collect.stats} * {@description.open} * Writes a formatted string to this object's destination using the * specified locale, format string, and arguments. * {@description.close} * * @param l * The {@linkplain java.util.Locale locale} to apply during * formatting. If <tt>l</tt> is <tt>null</tt> then no localization * is applied. This does not change this object's locale that was * set during construction. * * @param format * A format string as described in <a href="#syntax">Format string * syntax</a> * * @param args * Arguments referenced by the format specifiers in the format * string. If there are more arguments than format specifiers, the * extra arguments are ignored. The maximum number of arguments is * limited by the maximum dimension of a Java array as defined by * the <a href="http://java.sun.com/docs/books/vmspec/">Java * Virtual Machine Specification</a> * * @throws IllegalFormatException * If a format string contains an illegal syntax, a format * specifier that is incompatible with the given arguments, * insufficient arguments given the format string, or other * illegal conditions. For specification of all possible * formatting errors, see the <a href="#detail">Details</a> * section of the formatter class specification. * * @throws FormatterClosedException * If this formatter has been closed by invoking its {@link * #close()} method * * @return This formatter */ public Formatter format(Locale l, String format, Object ... args) { ensureOpen(); // index of last argument referenced int last = -1; // last ordinary index int lasto = -1; FormatString[] fsa = parse(format); for (int i = 0; i < fsa.length; i++) { FormatString fs = fsa[i]; int index = fs.index(); try { switch (index) { case -2: // fixed string, "%n", or "%%" fs.print(null, l); break; case -1: // relative index if (last < 0 || (args != null && last > args.length - 1)) throw new MissingFormatArgumentException(fs.toString()); fs.print((args == null ? null : args[last]), l); break; case 0: // ordinary index lasto++; last = lasto; if (args != null && lasto > args.length - 1) throw new MissingFormatArgumentException(fs.toString()); fs.print((args == null ? null : args[lasto]), l); break; default: // explicit index last = index - 1; if (args != null && last > args.length - 1) throw new MissingFormatArgumentException(fs.toString()); fs.print((args == null ? null : args[last]), l); break; } } catch (IOException x) { lastException = x; } } return this; } // %[argument_index$][flags][width][.precision][t]conversion private static final String formatSpecifier = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"; private static Pattern fsPattern = Pattern.compile(formatSpecifier); // Look for format specifiers in the format string. private FormatString[] parse(String s) { ArrayList al = new ArrayList(); Matcher m = fsPattern.matcher(s); int i = 0; while (i < s.length()) { if (m.find(i)) { // Anything between the start of the string and the beginning // of the format specifier is either fixed text or contains // an invalid format string. if (m.start() != i) { // Make sure we didn't miss any invalid format specifiers checkText(s.substring(i, m.start())); // Assume previous characters were fixed text al.add(new FixedString(s.substring(i, m.start()))); } // Expect 6 groups in regular expression String[] sa = new String[6]; for (int j = 0; j < m.groupCount(); j++) { sa[j] = m.group(j + 1); // System.out.print(sa[j] + " "); } // System.out.println(); al.add(new FormatSpecifier(this, sa)); i = m.end(); } else { // No more valid format specifiers. Check for possible invalid // format specifiers. checkText(s.substring(i)); // The rest of the string is fixed text al.add(new FixedString(s.substring(i))); break; } } // FormatString[] fs = new FormatString[al.size()]; // for (int j = 0; j < al.size(); j++) // System.out.println(((FormatString) al.get(j)).toString()); return (FormatString[]) al.toArray(new FormatString[0]); } private void checkText(String s) { int idx; // If there are any '%' in the given string, we got a bad format // specifier. if ((idx = s.indexOf('%')) != -1) { char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1)); throw new UnknownFormatConversionException(String.valueOf(c)); } } private interface FormatString { int index(); void print(Object arg, Locale l) throws IOException; String toString(); } private class FixedString implements FormatString { private String s; FixedString(String s) { this.s = s; } public int index() { return -2; } public void print(Object arg, Locale l) throws IOException { a.append(s); } public String toString() { return s; } } public enum BigDecimalLayoutForm { SCIENTIFIC, DECIMAL_FLOAT }; private class FormatSpecifier implements FormatString { private int index = -1; private Flags f = Flags.NONE; private int width; private int precision; private boolean dt = false; private char c; private Formatter formatter; // cache the line separator private String ls; private int index(String s) { if (s != null) { try { index = Integer.parseInt(s.substring(0, s.length() - 1)); } catch (NumberFormatException x) { assert(false); } } else { index = 0; } return index; } public int index() { return index; } private Flags flags(String s) { f = Flags.parse(s); if (f.contains(Flags.PREVIOUS)) index = -1; return f; } Flags flags() { return f; } private int width(String s) { width = -1; if (s != null) { try { width = Integer.parseInt(s); if (width < 0) throw new IllegalFormatWidthException(width); } catch (NumberFormatException x) { assert(false); } } return width; } int width() { return width; } private int precision(String s) { precision = -1; if (s != null) { try { // remove the '.' precision = Integer.parseInt(s.substring(1)); if (precision < 0) throw new IllegalFormatPrecisionException(precision); } catch (NumberFormatException x) { assert(false); } } return precision; } int precision() { return precision; } private char conversion(String s) { c = s.charAt(0); if (!dt) { if (!Conversion.isValid(c)) throw new UnknownFormatConversionException(String.valueOf(c)); if (Character.isUpperCase(c)) f.add(Flags.UPPERCASE); c = Character.toLowerCase(c); if (Conversion.isText(c)) index = -2; } return c; } private char conversion() { return c; } FormatSpecifier(Formatter formatter, String[] sa) { this.formatter = formatter; int idx = 0; index(sa[idx++]); flags(sa[idx++]); width(sa[idx++]); precision(sa[idx++]); if (sa[idx] != null) { dt = true; if (sa[idx].equals("T")) f.add(Flags.UPPERCASE); } conversion(sa[++idx]); if (dt) checkDateTime(); else if (Conversion.isGeneral(c)) checkGeneral(); else if (Conversion.isCharacter(c)) checkCharacter(); else if (Conversion.isInteger(c)) checkInteger(); else if (Conversion.isFloat(c)) checkFloat(); else if (Conversion.isText(c)) checkText(); else throw new UnknownFormatConversionException(String.valueOf(c)); } public void print(Object arg, Locale l) throws IOException { if (dt) { printDateTime(arg, l); return; } switch(c) { case Conversion.DECIMAL_INTEGER: case Conversion.OCTAL_INTEGER: case Conversion.HEXADECIMAL_INTEGER: printInteger(arg, l); break; case Conversion.SCIENTIFIC: case Conversion.GENERAL: case Conversion.DECIMAL_FLOAT: case Conversion.HEXADECIMAL_FLOAT: printFloat(arg, l); break; case Conversion.CHARACTER: case Conversion.CHARACTER_UPPER: printCharacter(arg); break; case Conversion.BOOLEAN: printBoolean(arg); break; case Conversion.STRING: printString(arg, l); break; case Conversion.HASHCODE: printHashCode(arg); break; case Conversion.LINE_SEPARATOR: if (ls == null) ls = System.getProperty("line.separator"); a.append(ls); break; case Conversion.PERCENT_SIGN: a.append('%'); break; default: assert false; } } private void printInteger(Object arg, Locale l) throws IOException { if (arg == null) print("null"); else if (arg instanceof Byte) print(((Byte)arg).byteValue(), l); else if (arg instanceof Short) print(((Short)arg).shortValue(), l); else if (arg instanceof Integer) print(((Integer)arg).intValue(), l); else if (arg instanceof Long) print(((Long)arg).longValue(), l); else if (arg instanceof BigInteger) print(((BigInteger)arg), l); else failConversion(c, arg); } private void printFloat(Object arg, Locale l) throws IOException { if (arg == null) print("null"); else if (arg instanceof Float) print(((Float)arg).floatValue(), l); else if (arg instanceof Double) print(((Double)arg).doubleValue(), l); else if (arg instanceof BigDecimal) print(((BigDecimal)arg), l); else failConversion(c, arg); } private void printDateTime(Object arg, Locale l) throws IOException { if (arg == null) { print("null"); return; } Calendar cal = null; // Instead of Calendar.setLenient(true), perhaps we should // wrap the IllegalArgumentException that might be thrown? if (arg instanceof Long) { // Note that the following method uses an instance of the // default time zone (TimeZone.getDefaultRef(). cal = Calendar.getInstance(l == null ? Locale.US : l); cal.setTimeInMillis((Long)arg); } else if (arg instanceof Date) { // Note that the following method uses an instance of the // default time zone (TimeZone.getDefaultRef(). cal = Calendar.getInstance(l == null ? Locale.US : l); cal.setTime((Date)arg); } else if (arg instanceof Calendar) { cal = (Calendar) ((Calendar)arg).clone(); cal.setLenient(true); } else { failConversion(c, arg); } // Use the provided locale so that invocations of // localizedMagnitude() use optimizations for null. print(cal, c, l); } private void printCharacter(Object arg) throws IOException { if (arg == null) { print("null"); return; } String s = null; if (arg instanceof Character) { s = ((Character)arg).toString(); } else if (arg instanceof Byte) { byte i = ((Byte)arg).byteValue(); if (Character.isValidCodePoint(i)) s = new String(Character.toChars(i)); else throw new IllegalFormatCodePointException(i); } else if (arg instanceof Short) { short i = ((Short)arg).shortValue(); if (Character.isValidCodePoint(i)) s = new String(Character.toChars(i)); else throw new IllegalFormatCodePointException(i); } else if (arg instanceof Integer) { int i = ((Integer)arg).intValue(); if (Character.isValidCodePoint(i)) s = new String(Character.toChars(i)); else throw new IllegalFormatCodePointException(i); } else { failConversion(c, arg); } print(s); } private void printString(Object arg, Locale l) throws IOException { if (arg == null) { print("null"); } else if (arg instanceof Formattable) { Formatter fmt = formatter; if (formatter.locale() != l) fmt = new Formatter(formatter.out(), l); ((Formattable)arg).formatTo(fmt, f.valueOf(), width, precision); } else { print(arg.toString()); } } private void printBoolean(Object arg) throws IOException { String s; if (arg != null) s = ((arg instanceof Boolean) ? ((Boolean)arg).toString() : Boolean.toString(true)); else s = Boolean.toString(false); print(s); } private void printHashCode(Object arg) throws IOException { String s = (arg == null ? "null" : Integer.toHexString(arg.hashCode())); print(s); } private void print(String s) throws IOException { if (precision != -1 && precision < s.length()) s = s.substring(0, precision); if (f.contains(Flags.UPPERCASE)) s = s.toUpperCase(); a.append(justify(s)); } private String justify(String s) { if (width == -1) return s; StringBuilder sb = new StringBuilder(); boolean pad = f.contains(Flags.LEFT_JUSTIFY); int sp = width - s.length(); if (!pad) for (int i = 0; i < sp; i++) sb.append(' '); sb.append(s); if (pad) for (int i = 0; i < sp; i++) sb.append(' '); return sb.toString(); } public String toString() { StringBuilder sb = new StringBuilder('%'); // Flags.UPPERCASE is set internally for legal conversions. Flags dupf = f.dup().remove(Flags.UPPERCASE); sb.append(dupf.toString()); if (index > 0) sb.append(index).append('$'); if (width != -1) sb.append(width); if (precision != -1) sb.append('.').append(precision); if (dt) sb.append(f.contains(Flags.UPPERCASE) ? 'T' : 't'); sb.append(f.contains(Flags.UPPERCASE) ? Character.toUpperCase(c) : c); return sb.toString(); } private void checkGeneral() { if ((c == Conversion.BOOLEAN || c == Conversion.HASHCODE) && f.contains(Flags.ALTERNATE)) failMismatch(Flags.ALTERNATE, c); // '-' requires a width if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) throw new MissingFormatWidthException(toString()); checkBadFlags(Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES); } private void checkDateTime() { if (precision != -1) throw new IllegalFormatPrecisionException(precision); if (!DateTime.isValid(c)) throw new UnknownFormatConversionException("t" + c); checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES); // '-' requires a width if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) throw new MissingFormatWidthException(toString()); } private void checkCharacter() { if (precision != -1) throw new IllegalFormatPrecisionException(precision); checkBadFlags(Flags.ALTERNATE, Flags.PLUS, Flags.LEADING_SPACE, Flags.ZERO_PAD, Flags.GROUP, Flags.PARENTHESES); // '-' requires a width if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) throw new MissingFormatWidthException(toString()); } private void checkInteger() { checkNumeric(); if (precision != -1) throw new IllegalFormatPrecisionException(precision); if (c == Conversion.DECIMAL_INTEGER) checkBadFlags(Flags.ALTERNATE); else if (c == Conversion.OCTAL_INTEGER) checkBadFlags(Flags.GROUP); else checkBadFlags(Flags.GROUP); } private void checkBadFlags(Flags ... badFlags) { for (int i = 0; i < badFlags.length; i++) if (f.contains(badFlags[i])) failMismatch(badFlags[i], c); } private void checkFloat() { checkNumeric(); if (c == Conversion.DECIMAL_FLOAT) { } else if (c == Conversion.HEXADECIMAL_FLOAT) { checkBadFlags(Flags.PARENTHESES, Flags.GROUP); } else if (c == Conversion.SCIENTIFIC) { checkBadFlags(Flags.GROUP); } else if (c == Conversion.GENERAL) { checkBadFlags(Flags.ALTERNATE); } } private void checkNumeric() { if (width != -1 && width < 0) throw new IllegalFormatWidthException(width); if (precision != -1 && precision < 0) throw new IllegalFormatPrecisionException(precision); // '-' and '0' require a width if (width == -1 && (f.contains(Flags.LEFT_JUSTIFY) || f.contains(Flags.ZERO_PAD))) throw new MissingFormatWidthException(toString()); // bad combination if ((f.contains(Flags.PLUS) && f.contains(Flags.LEADING_SPACE)) || (f.contains(Flags.LEFT_JUSTIFY) && f.contains(Flags.ZERO_PAD))) throw new IllegalFormatFlagsException(f.toString()); } private void checkText() { if (precision != -1) throw new IllegalFormatPrecisionException(precision); switch (c) { case Conversion.PERCENT_SIGN: if (f.valueOf() != Flags.LEFT_JUSTIFY.valueOf() && f.valueOf() != Flags.NONE.valueOf()) throw new IllegalFormatFlagsException(f.toString()); // '-' requires a width if (width == -1 && f.contains(Flags.LEFT_JUSTIFY)) throw new MissingFormatWidthException(toString()); break; case Conversion.LINE_SEPARATOR: if (width != -1) throw new IllegalFormatWidthException(width); if (f.valueOf() != Flags.NONE.valueOf()) throw new IllegalFormatFlagsException(f.toString()); break; default: assert false; } } private void print(byte value, Locale l) throws IOException { long v = value; if (value < 0 && (c == Conversion.OCTAL_INTEGER || c == Conversion.HEXADECIMAL_INTEGER)) { v += (1L << 8); assert v >= 0 : v; } print(v, l); } private void print(short value, Locale l) throws IOException { long v = value; if (value < 0 && (c == Conversion.OCTAL_INTEGER || c == Conversion.HEXADECIMAL_INTEGER)) { v += (1L << 16); assert v >= 0 : v; } print(v, l); } private void print(int value, Locale l) throws IOException { long v = value; if (value < 0 && (c == Conversion.OCTAL_INTEGER || c == Conversion.HEXADECIMAL_INTEGER)) { v += (1L << 32); assert v >= 0 : v; } print(v, l); } private void print(long value, Locale l) throws IOException { StringBuilder sb = new StringBuilder(); if (c == Conversion.DECIMAL_INTEGER) { boolean neg = value < 0; char[] va; if (value < 0) va = Long.toString(value, 10).substring(1).toCharArray(); else va = Long.toString(value, 10).toCharArray(); // leading sign indicator leadingSign(sb, neg); // the value localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l); // trailing sign indicator trailingSign(sb, neg); } else if (c == Conversion.OCTAL_INTEGER) { checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE, Flags.PLUS); String s = Long.toOctalString(value); int len = (f.contains(Flags.ALTERNATE) ? s.length() + 1 : s.length()); // apply ALTERNATE (radix indicator for octal) before ZERO_PAD if (f.contains(Flags.ALTERNATE)) sb.append('0'); if (f.contains(Flags.ZERO_PAD)) for (int i = 0; i < width - len; i++) sb.append('0'); sb.append(s); } else if (c == Conversion.HEXADECIMAL_INTEGER) { checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE, Flags.PLUS); String s = Long.toHexString(value); int len = (f.contains(Flags.ALTERNATE) ? s.length() + 2 : s.length()); // apply ALTERNATE (radix indicator for hex) before ZERO_PAD if (f.contains(Flags.ALTERNATE)) sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x"); if (f.contains(Flags.ZERO_PAD)) for (int i = 0; i < width - len; i++) sb.append('0'); if (f.contains(Flags.UPPERCASE)) s = s.toUpperCase(); sb.append(s); } // justify based on width a.append(justify(sb.toString())); } // neg := val < 0 private StringBuilder leadingSign(StringBuilder sb, boolean neg) { if (!neg) { if (f.contains(Flags.PLUS)) { sb.append('+'); } else if (f.contains(Flags.LEADING_SPACE)) { sb.append(' '); } } else { if (f.contains(Flags.PARENTHESES)) sb.append('('); else sb.append('-'); } return sb; } // neg := val < 0 private StringBuilder trailingSign(StringBuilder sb, boolean neg) { if (neg && f.contains(Flags.PARENTHESES)) sb.append(')'); return sb; } private void print(BigInteger value, Locale l) throws IOException { StringBuilder sb = new StringBuilder(); boolean neg = value.signum() == -1; BigInteger v = value.abs(); // leading sign indicator leadingSign(sb, neg); // the value if (c == Conversion.DECIMAL_INTEGER) { char[] va = v.toString().toCharArray(); localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l); } else if (c == Conversion.OCTAL_INTEGER) { String s = v.toString(8); int len = s.length() + sb.length(); if (neg && f.contains(Flags.PARENTHESES)) len++; // apply ALTERNATE (radix indicator for octal) before ZERO_PAD if (f.contains(Flags.ALTERNATE)) { len++; sb.append('0'); } if (f.contains(Flags.ZERO_PAD)) { for (int i = 0; i < width - len; i++) sb.append('0'); } sb.append(s); } else if (c == Conversion.HEXADECIMAL_INTEGER) { String s = v.toString(16); int len = s.length() + sb.length(); if (neg && f.contains(Flags.PARENTHESES)) len++; // apply ALTERNATE (radix indicator for hex) before ZERO_PAD if (f.contains(Flags.ALTERNATE)) { len += 2; sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x"); } if (f.contains(Flags.ZERO_PAD)) for (int i = 0; i < width - len; i++) sb.append('0'); if (f.contains(Flags.UPPERCASE)) s = s.toUpperCase(); sb.append(s); } // trailing sign indicator trailingSign(sb, (value.signum() == -1)); // justify based on width a.append(justify(sb.toString())); } private void print(float value, Locale l) throws IOException { print((double) value, l); } private void print(double value, Locale l) throws IOException { StringBuilder sb = new StringBuilder(); boolean neg = Double.compare(value, 0.0) == -1; if (!Double.isNaN(value)) { double v = Math.abs(value); // leading sign indicator leadingSign(sb, neg); // the value if (!Double.isInfinite(v)) print(sb, v, l, f, c, precision, neg); else sb.append(f.contains(Flags.UPPERCASE) ? "INFINITY" : "Infinity"); // trailing sign indicator trailingSign(sb, neg); } else { sb.append(f.contains(Flags.UPPERCASE) ? "NAN" : "NaN"); } // justify based on width a.append(justify(sb.toString())); } // !Double.isInfinite(value) && !Double.isNaN(value) private void print(StringBuilder sb, double value, Locale l, Flags f, char c, int precision, boolean neg) throws IOException { if (c == Conversion.SCIENTIFIC) { // Create a new FormattedFloatingDecimal with the desired // precision. int prec = (precision == -1 ? 6 : precision); FormattedFloatingDecimal fd = new FormattedFloatingDecimal(value, prec, FormattedFloatingDecimal.Form.SCIENTIFIC); char[] v = new char[MAX_FD_CHARS]; int len = fd.getChars(v); char[] mant = addZeros(mantissa(v, len), prec); // If the precision is zero and the '#' flag is set, add the // requested decimal point. if (f.contains(Flags.ALTERNATE) && (prec == 0)) mant = addDot(mant); char[] exp = (value == 0.0) ? new char[] {'+','0','0'} : exponent(v, len); int newW = width; if (width != -1) newW = adjustWidth(width - exp.length - 1, f, neg); localizedMagnitude(sb, mant, f, newW, l); sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e'); Flags flags = f.dup().remove(Flags.GROUP); char sign = exp[0]; assert(sign == '+' || sign == '-'); sb.append(sign); char[] tmp = new char[exp.length - 1]; System.arraycopy(exp, 1, tmp, 0, exp.length - 1); sb.append(localizedMagnitude(null, tmp, flags, -1, l)); } else if (c == Conversion.DECIMAL_FLOAT) { // Create a new FormattedFloatingDecimal with the desired // precision. int prec = (precision == -1 ? 6 : precision); FormattedFloatingDecimal fd = new FormattedFloatingDecimal(value, prec, FormattedFloatingDecimal.Form.DECIMAL_FLOAT); // MAX_FD_CHARS + 1 (round?) char[] v = new char[MAX_FD_CHARS + 1 + Math.abs(fd.getExponent())]; int len = fd.getChars(v); char[] mant = addZeros(mantissa(v, len), prec); // If the precision is zero and the '#' flag is set, add the // requested decimal point. if (f.contains(Flags.ALTERNATE) && (prec == 0)) mant = addDot(mant); int newW = width; if (width != -1) newW = adjustWidth(width, f, neg); localizedMagnitude(sb, mant, f, newW, l); } else if (c == Conversion.GENERAL) { int prec = precision; if (precision == -1) prec = 6; else if (precision == 0) prec = 1; FormattedFloatingDecimal fd = new FormattedFloatingDecimal(value, prec, FormattedFloatingDecimal.Form.GENERAL); // MAX_FD_CHARS + 1 (round?) char[] v = new char[MAX_FD_CHARS + 1 + Math.abs(fd.getExponent())]; int len = fd.getChars(v); char[] exp = exponent(v, len); if (exp != null) { prec -= 1; } else { prec = prec - (value == 0 ? 0 : fd.getExponentRounded()) - 1; } char[] mant = addZeros(mantissa(v, len), prec); // If the precision is zero and the '#' flag is set, add the // requested decimal point. if (f.contains(Flags.ALTERNATE) && (prec == 0)) mant = addDot(mant); int newW = width; if (width != -1) { if (exp != null) newW = adjustWidth(width - exp.length - 1, f, neg); else newW = adjustWidth(width, f, neg); } localizedMagnitude(sb, mant, f, newW, l); if (exp != null) { sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e'); Flags flags = f.dup().remove(Flags.GROUP); char sign = exp[0]; assert(sign == '+' || sign == '-'); sb.append(sign); char[] tmp = new char[exp.length - 1]; System.arraycopy(exp, 1, tmp, 0, exp.length - 1); sb.append(localizedMagnitude(null, tmp, flags, -1, l)); } } else if (c == Conversion.HEXADECIMAL_FLOAT) { int prec = precision; if (precision == -1) // assume that we want all of the digits prec = 0; else if (precision == 0) prec = 1; String s = hexDouble(value, prec); char[] va; boolean upper = f.contains(Flags.UPPERCASE); sb.append(upper ? "0X" : "0x"); if (f.contains(Flags.ZERO_PAD)) for (int i = 0; i < width - s.length() - 2; i++) sb.append('0'); int idx = s.indexOf('p'); va = s.substring(0, idx).toCharArray(); if (upper) { String tmp = new String(va); // don't localize hex tmp = tmp.toUpperCase(Locale.US); va = tmp.toCharArray(); } sb.append(prec != 0 ? addZeros(va, prec) : va); sb.append(upper ? 'P' : 'p'); sb.append(s.substring(idx+1)); } } private char[] mantissa(char[] v, int len) { int i; for (i = 0; i < len; i++) { if (v[i] == 'e') break; } char[] tmp = new char[i]; System.arraycopy(v, 0, tmp, 0, i); return tmp; } private char[] exponent(char[] v, int len) { int i; for (i = len - 1; i >= 0; i--) { if (v[i] == 'e') break; } if (i == -1) return null; char[] tmp = new char[len - i - 1]; System.arraycopy(v, i + 1, tmp, 0, len - i - 1); return tmp; } // Add zeros to the requested precision. private char[] addZeros(char[] v, int prec) { // Look for the dot. If we don't find one, the we'll need to add // it before we add the zeros. int i; for (i = 0; i < v.length; i++) { if (v[i] == '.') break; } boolean needDot = false; if (i == v.length) { needDot = true; } // Determine existing precision. int outPrec = v.length - i - (needDot ? 0 : 1); assert (outPrec <= prec); if (outPrec == prec) return v; // Create new array with existing contents. char[] tmp = new char[v.length + prec - outPrec + (needDot ? 1 : 0)]; System.arraycopy(v, 0, tmp, 0, v.length); // Add dot if previously determined to be necessary. int start = v.length; if (needDot) { tmp[v.length] = '.'; start++; } // Add zeros. for (int j = start; j < tmp.length; j++) tmp[j] = '0'; return tmp; } // Method assumes that d > 0. private String hexDouble(double d, int prec) { // Let Double.toHexString handle simple cases if(!FpUtils.isFinite(d) || d == 0.0 || prec == 0 || prec >= 13) // remove "0x" return Double.toHexString(d).substring(2); else { assert(prec >= 1 && prec <= 12); int exponent = FpUtils.getExponent(d); boolean subnormal = (exponent == DoubleConsts.MIN_EXPONENT - 1); // If this is subnormal input so normalize (could be faster to // do as integer operation). if (subnormal) { scaleUp = FpUtils.scalb(1.0, 54); d *= scaleUp; // Calculate the exponent. This is not just exponent + 54 // since the former is not the normalized exponent. exponent = FpUtils.getExponent(d); assert exponent >= DoubleConsts.MIN_EXPONENT && exponent <= DoubleConsts.MAX_EXPONENT: exponent; } int precision = 1 + prec*4; int shiftDistance = DoubleConsts.SIGNIFICAND_WIDTH - precision; assert(shiftDistance >= 1 && shiftDistance < DoubleConsts.SIGNIFICAND_WIDTH); long doppel = Double.doubleToLongBits(d); // Deterime the number of bits to keep. long newSignif = (doppel & (DoubleConsts.EXP_BIT_MASK | DoubleConsts.SIGNIF_BIT_MASK)) >> shiftDistance; // Bits to round away. long roundingBits = doppel & ~(~0L << shiftDistance); // To decide how to round, look at the low-order bit of the // working significand, the highest order discarded bit (the // round bit) and whether any of the lower order discarded bits // are nonzero (the sticky bit). boolean leastZero = (newSignif & 0x1L) == 0L; boolean round = ((1L << (shiftDistance - 1) ) & roundingBits) != 0L; boolean sticky = shiftDistance > 1 && (~(1L<< (shiftDistance - 1)) & roundingBits) != 0; if((leastZero && round && sticky) || (!leastZero && round)) { newSignif++; } long signBit = doppel & DoubleConsts.SIGN_BIT_MASK; newSignif = signBit | (newSignif << shiftDistance); double result = Double.longBitsToDouble(newSignif); if (Double.isInfinite(result) ) { // Infinite result generated by rounding return "1.0p1024"; } else { String res = Double.toHexString(result).substring(2); if (!subnormal) return res; else { // Create a normalized subnormal string. int idx = res.indexOf('p'); if (idx == -1) { // No 'p' character in hex string. assert false; return null; } else { // Get exponent and append at the end. String exp = res.substring(idx + 1); int iexp = Integer.parseInt(exp) -54; return res.substring(0, idx) + "p" + Integer.toString(iexp); } } } } } private void print(BigDecimal value, Locale l) throws IOException { if (c == Conversion.HEXADECIMAL_FLOAT) failConversion(c, value); StringBuilder sb = new StringBuilder(); boolean neg = value.signum() == -1; BigDecimal v = value.abs(); // leading sign indicator leadingSign(sb, neg); // the value print(sb, v, l, f, c, precision, neg); // trailing sign indicator trailingSign(sb, neg); // justify based on width a.append(justify(sb.toString())); } // value > 0 private void print(StringBuilder sb, BigDecimal value, Locale l, Flags f, char c, int precision, boolean neg) throws IOException { if (c == Conversion.SCIENTIFIC) { // Create a new BigDecimal with the desired precision. int prec = (precision == -1 ? 6 : precision); int scale = value.scale(); int origPrec = value.precision(); int nzeros = 0; int compPrec; if (prec > origPrec - 1) { compPrec = origPrec; nzeros = prec - (origPrec - 1); } else { compPrec = prec + 1; } MathContext mc = new MathContext(compPrec); BigDecimal v = new BigDecimal(value.unscaledValue(), scale, mc); BigDecimalLayout bdl = new BigDecimalLayout(v.unscaledValue(), v.scale(), BigDecimalLayoutForm.SCIENTIFIC); char[] mant = bdl.mantissa(); // Add a decimal point if necessary. The mantissa may not // contain a decimal point if the scale is zero (the internal // representation has no fractional part) or the original // precision is one. Append a decimal point if '#' is set or if // we require zero padding to get to the requested precision. if ((origPrec == 1 || !bdl.hasDot()) && (nzeros > 0 || (f.contains(Flags.ALTERNATE)))) mant = addDot(mant); // Add trailing zeros in the case precision is greater than // the number of available digits after the decimal separator. mant = trailingZeros(mant, nzeros); char[] exp = bdl.exponent(); int newW = width; if (width != -1) newW = adjustWidth(width - exp.length - 1, f, neg); localizedMagnitude(sb, mant, f, newW, l); sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e'); Flags flags = f.dup().remove(Flags.GROUP); char sign = exp[0]; assert(sign == '+' || sign == '-'); sb.append(exp[0]); char[] tmp = new char[exp.length - 1]; System.arraycopy(exp, 1, tmp, 0, exp.length - 1); sb.append(localizedMagnitude(null, tmp, flags, -1, l)); } else if (c == Conversion.DECIMAL_FLOAT) { // Create a new BigDecimal with the desired precision. int prec = (precision == -1 ? 6 : precision); int scale = value.scale(); int compPrec = value.precision(); if (scale > prec) compPrec -= (scale - prec); MathContext mc = new MathContext(compPrec); BigDecimal v = new BigDecimal(value.unscaledValue(), scale, mc); BigDecimalLayout bdl = new BigDecimalLayout(v.unscaledValue(), v.scale(), BigDecimalLayoutForm.DECIMAL_FLOAT); char mant[] = bdl.mantissa(); int nzeros = (bdl.scale() < prec ? prec - bdl.scale() : 0); // Add a decimal point if necessary. The mantissa may not // contain a decimal point if the scale is zero (the internal // representation has no fractional part). Append a decimal // point if '#' is set or we require zero padding to get to the // requested precision. if (bdl.scale() == 0 && (f.contains(Flags.ALTERNATE) || nzeros > 0)) mant = addDot(bdl.mantissa()); // Add trailing zeros if the precision is greater than the // number of available digits after the decimal separator. mant = trailingZeros(mant, nzeros); localizedMagnitude(sb, mant, f, adjustWidth(width, f, neg), l); } else if (c == Conversion.GENERAL) { int prec = precision; if (precision == -1) prec = 6; else if (precision == 0) prec = 1; BigDecimal tenToTheNegFour = BigDecimal.valueOf(1, 4); BigDecimal tenToThePrec = BigDecimal.valueOf(1, -prec); if ((value.equals(BigDecimal.ZERO)) || ((value.compareTo(tenToTheNegFour) != -1) && (value.compareTo(tenToThePrec) == -1))) { int e = - value.scale() + (value.unscaledValue().toString().length() - 1); // xxx.yyy // g precision (# sig digits) = #x + #y // f precision = #y // exponent = #x - 1 // => f precision = g precision - exponent - 1 // 0.000zzz // g precision (# sig digits) = #z // f precision = #0 (after '.') + #z // exponent = - #0 (after '.') - 1 // => f precision = g precision - exponent - 1 prec = prec - e - 1; print(sb, value, l, f, Conversion.DECIMAL_FLOAT, prec, neg); } else { print(sb, value, l, f, Conversion.SCIENTIFIC, prec - 1, neg); } } else if (c == Conversion.HEXADECIMAL_FLOAT) { // This conversion isn't supported. The error should be // reported earlier. assert false; } } private class BigDecimalLayout { private StringBuilder mant; private StringBuilder exp; private boolean dot = false; private int scale; public BigDecimalLayout(BigInteger intVal, int scale, BigDecimalLayoutForm form) { layout(intVal, scale, form); } public boolean hasDot() { return dot; } public int scale() { return scale; } // char[] with canonical string representation public char[] layoutChars() { StringBuilder sb = new StringBuilder(mant); if (exp != null) { sb.append('E'); sb.append(exp); } return toCharArray(sb); } public char[] mantissa() { return toCharArray(mant); } // The exponent will be formatted as a sign ('+' or '-') followed // by the exponent zero-padded to include at least two digits. public char[] exponent() { return toCharArray(exp); } private char[] toCharArray(StringBuilder sb) { if (sb == null) return null; char[] result = new char[sb.length()]; sb.getChars(0, result.length, result, 0); return result; } private void layout(BigInteger intVal, int scale, BigDecimalLayoutForm form) { char coeff[] = intVal.toString().toCharArray(); this.scale = scale; // Construct a buffer, with sufficient capacity for all cases. // If E-notation is needed, length will be: +1 if negative, +1 // if '.' needed, +2 for "E+", + up to 10 for adjusted // exponent. Otherwise it could have +1 if negative, plus // leading "0.00000" mant = new StringBuilder(coeff.length + 14); if (scale == 0) { int len = coeff.length; if (len > 1) { mant.append(coeff[0]); if (form == BigDecimalLayoutForm.SCIENTIFIC) { mant.append('.'); dot = true; mant.append(coeff, 1, len - 1); exp = new StringBuilder("+"); if (len < 10) exp.append("0").append(len - 1); else exp.append(len - 1); } else { mant.append(coeff, 1, len - 1); } } else { mant.append(coeff); if (form == BigDecimalLayoutForm.SCIENTIFIC) exp = new StringBuilder("+00"); } return; } long adjusted = -(long) scale + (coeff.length - 1); if (form == BigDecimalLayoutForm.DECIMAL_FLOAT) { // count of padding zeros int pad = scale - coeff.length; if (pad >= 0) { // 0.xxx form mant.append("0."); dot = true; for (; pad > 0 ; pad--) mant.append('0'); mant.append(coeff); } else { if (-pad < coeff.length) { // xx.xx form mant.append(coeff, 0, -pad); mant.append('.'); dot = true; mant.append(coeff, -pad, scale); } else { // xx form mant.append(coeff, 0, coeff.length); for (int i = 0; i < -scale; i++) mant.append('0'); this.scale = 0; } } } else { // x.xxx form mant.append(coeff[0]); if (coeff.length > 1) { mant.append('.'); dot = true; mant.append(coeff, 1, coeff.length-1); } exp = new StringBuilder(); if (adjusted != 0) { long abs = Math.abs(adjusted); // require sign exp.append(adjusted < 0 ? '-' : '+'); if (abs < 10) exp.append('0'); exp.append(abs); } else { exp.append("+00"); } } } } private int adjustWidth(int width, Flags f, boolean neg) { int newW = width; if (newW != -1 && neg && f.contains(Flags.PARENTHESES)) newW--; return newW; } // Add a '.' to th mantissa if required private char[] addDot(char[] mant) { char[] tmp = mant; tmp = new char[mant.length + 1]; System.arraycopy(mant, 0, tmp, 0, mant.length); tmp[tmp.length - 1] = '.'; return tmp; } // Add trailing zeros in the case precision is greater than the number // of available digits after the decimal separator. private char[] trailingZeros(char[] mant, int nzeros) { char[] tmp = mant; if (nzeros > 0) { tmp = new char[mant.length + nzeros]; System.arraycopy(mant, 0, tmp, 0, mant.length); for (int i = mant.length; i < tmp.length; i++) tmp[i] = '0'; } return tmp; } private void print(Calendar t, char c, Locale l) throws IOException { StringBuilder sb = new StringBuilder(); print(sb, t, c, l); // justify based on width String s = justify(sb.toString()); if (f.contains(Flags.UPPERCASE)) s = s.toUpperCase(); a.append(s); } private Appendable print(StringBuilder sb, Calendar t, char c, Locale l) throws IOException { assert(width == -1); if (sb == null) sb = new StringBuilder(); switch (c) { case DateTime.HOUR_OF_DAY_0: // 'H' (00 - 23) case DateTime.HOUR_0: // 'I' (01 - 12) case DateTime.HOUR_OF_DAY: // 'k' (0 - 23) -- like H case DateTime.HOUR: { // 'l' (1 - 12) -- like I int i = t.get(Calendar.HOUR_OF_DAY); if (c == DateTime.HOUR_0 || c == DateTime.HOUR) i = (i == 0 || i == 12 ? 12 : i % 12); Flags flags = (c == DateTime.HOUR_OF_DAY_0 || c == DateTime.HOUR_0 ? Flags.ZERO_PAD : Flags.NONE); sb.append(localizedMagnitude(null, i, flags, 2, l)); break; } case DateTime.MINUTE: { // 'M' (00 - 59) int i = t.get(Calendar.MINUTE); Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 2, l)); break; } case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999) int i = t.get(Calendar.MILLISECOND) * 1000000; Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 9, l)); break; } case DateTime.MILLISECOND: { // 'L' (000 - 999) int i = t.get(Calendar.MILLISECOND); Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 3, l)); break; } case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?) long i = t.getTimeInMillis(); Flags flags = Flags.NONE; sb.append(localizedMagnitude(null, i, flags, width, l)); break; } case DateTime.AM_PM: { // 'p' (am or pm) // Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper String[] ampm = { "AM", "PM" }; if (l != null && l != Locale.US) { DateFormatSymbols dfs = DateFormatSymbols.getInstance(l); ampm = dfs.getAmPmStrings(); } String s = ampm[t.get(Calendar.AM_PM)]; sb.append(s.toLowerCase(l != null ? l : Locale.US)); break; } case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?) long i = t.getTimeInMillis() / 1000; Flags flags = Flags.NONE; sb.append(localizedMagnitude(null, i, flags, width, l)); break; } case DateTime.SECOND: { // 'S' (00 - 60 - leap second) int i = t.get(Calendar.SECOND); Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 2, l)); break; } case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus? int i = t.get(Calendar.ZONE_OFFSET) + t.get(Calendar.DST_OFFSET); boolean neg = i < 0; sb.append(neg ? '-' : '+'); if (neg) i = -i; int min = i / 60000; // combine minute and hour into a single integer int offset = (min / 60) * 100 + (min % 60); Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, offset, flags, 4, l)); break; } case DateTime.ZONE: { // 'Z' (symbol) TimeZone tz = t.getTimeZone(); sb.append(tz.getDisplayName((t.get(Calendar.DST_OFFSET) != 0), TimeZone.SHORT, (l == null) ? Locale.US : l)); break; } // Date case DateTime.NAME_OF_DAY_ABBREV: // 'a' case DateTime.NAME_OF_DAY: { // 'A' int i = t.get(Calendar.DAY_OF_WEEK); Locale lt = ((l == null) ? Locale.US : l); DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt); if (c == DateTime.NAME_OF_DAY) sb.append(dfs.getWeekdays()[i]); else sb.append(dfs.getShortWeekdays()[i]); break; } case DateTime.NAME_OF_MONTH_ABBREV: // 'b' case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b case DateTime.NAME_OF_MONTH: { // 'B' int i = t.get(Calendar.MONTH); Locale lt = ((l == null) ? Locale.US : l); DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt); if (c == DateTime.NAME_OF_MONTH) sb.append(dfs.getMonths()[i]); else sb.append(dfs.getShortMonths()[i]); break; } case DateTime.CENTURY: // 'C' (00 - 99) case DateTime.YEAR_2: // 'y' (00 - 99) case DateTime.YEAR_4: { // 'Y' (0000 - 9999) int i = t.get(Calendar.YEAR); int size = 2; switch (c) { case DateTime.CENTURY: i /= 100; break; case DateTime.YEAR_2: i %= 100; break; case DateTime.YEAR_4: size = 4; break; } Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, size, l)); break; } case DateTime.DAY_OF_MONTH_0: // 'd' (01 - 31) case DateTime.DAY_OF_MONTH: { // 'e' (1 - 31) -- like d int i = t.get(Calendar.DATE); Flags flags = (c == DateTime.DAY_OF_MONTH_0 ? Flags.ZERO_PAD : Flags.NONE); sb.append(localizedMagnitude(null, i, flags, 2, l)); break; } case DateTime.DAY_OF_YEAR: { // 'j' (001 - 366) int i = t.get(Calendar.DAY_OF_YEAR); Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 3, l)); break; } case DateTime.MONTH: { // 'm' (01 - 12) int i = t.get(Calendar.MONTH) + 1; Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 2, l)); break; } // Composites case DateTime.TIME: // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS) case DateTime.TIME_24_HOUR: { // 'R' (hh:mm same as %H:%M) char sep = ':'; print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep); print(sb, t, DateTime.MINUTE, l); if (c == DateTime.TIME) { sb.append(sep); print(sb, t, DateTime.SECOND, l); } break; } case DateTime.TIME_12_HOUR: { // 'r' (hh:mm:ss [AP]M) char sep = ':'; print(sb, t, DateTime.HOUR_0, l).append(sep); print(sb, t, DateTime.MINUTE, l).append(sep); print(sb, t, DateTime.SECOND, l).append(' '); // this may be in wrong place for some locales StringBuilder tsb = new StringBuilder(); print(tsb, t, DateTime.AM_PM, l); sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US)); break; } case DateTime.DATE_TIME: { // 'c' (Sat Nov 04 12:02:33 EST 1999) char sep = ' '; print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep); print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep); print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep); print(sb, t, DateTime.TIME, l).append(sep); print(sb, t, DateTime.ZONE, l).append(sep); print(sb, t, DateTime.YEAR_4, l); break; } case DateTime.DATE: { // 'D' (mm/dd/yy) char sep = '/'; print(sb, t, DateTime.MONTH, l).append(sep); print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep); print(sb, t, DateTime.YEAR_2, l); break; } case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d) char sep = '-'; print(sb, t, DateTime.YEAR_4, l).append(sep); print(sb, t, DateTime.MONTH, l).append(sep); print(sb, t, DateTime.DAY_OF_MONTH_0, l); break; } default: assert false; } return sb; } // -- Methods to support throwing exceptions -- private void failMismatch(Flags f, char c) { String fs = f.toString(); throw new FormatFlagsConversionMismatchException(fs, c); } private void failConversion(char c, Object arg) { throw new IllegalFormatConversionException(c, arg.getClass()); } private char getZero(Locale l) { if ((l != null) && !l.equals(locale())) { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); return dfs.getZeroDigit(); } return zero; } private StringBuilder localizedMagnitude(StringBuilder sb, long value, Flags f, int width, Locale l) { char[] va = Long.toString(value, 10).toCharArray(); return localizedMagnitude(sb, va, f, width, l); } private StringBuilder localizedMagnitude(StringBuilder sb, char[] value, Flags f, int width, Locale l) { if (sb == null) sb = new StringBuilder(); int begin = sb.length(); char zero = getZero(l); // determine localized grouping separator and size char grpSep = '\0'; int grpSize = -1; char decSep = '\0'; int len = value.length; int dot = len; for (int j = 0; j < len; j++) { if (value[j] == '.') { dot = j; break; } } if (dot < len) { if (l == null || l.equals(Locale.US)) { decSep = '.'; } else { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); decSep = dfs.getDecimalSeparator(); } } if (f.contains(Flags.GROUP)) { if (l == null || l.equals(Locale.US)) { grpSep = ','; grpSize = 3; } else { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); grpSep = dfs.getGroupingSeparator(); DecimalFormat df = (DecimalFormat) NumberFormat.getIntegerInstance(l); grpSize = df.getGroupingSize(); } } // localize the digits inserting group separators as necessary for (int j = 0; j < len; j++) { if (j == dot) { sb.append(decSep); // no more group separators after the decimal separator grpSep = '\0'; continue; } char c = value[j]; sb.append((char) ((c - '0') + zero)); if (grpSep != '\0' && j != dot - 1 && ((dot - j) % grpSize == 1)) sb.append(grpSep); } // apply zero padding len = sb.length(); if (width != -1 && f.contains(Flags.ZERO_PAD)) for (int k = 0; k < width - len; k++) sb.insert(begin, zero); return sb; } } private static class Flags { private int flags; static final Flags NONE = new Flags(0); // '' // duplicate declarations from Formattable.java static final Flags LEFT_JUSTIFY = new Flags(1<<0); // '-' static final Flags UPPERCASE = new Flags(1<<1); // '^' static final Flags ALTERNATE = new Flags(1<<2); // '#' // numerics static final Flags PLUS = new Flags(1<<3); // '+' static final Flags LEADING_SPACE = new Flags(1<<4); // ' ' static final Flags ZERO_PAD = new Flags(1<<5); // '0' static final Flags GROUP = new Flags(1<<6); // ',' static final Flags PARENTHESES = new Flags(1<<7); // '(' // indexing static final Flags PREVIOUS = new Flags(1<<8); // '<' private Flags(int f) { flags = f; } public int valueOf() { return flags; } public boolean contains(Flags f) { return (flags & f.valueOf()) == f.valueOf(); } public Flags dup() { return new Flags(flags); } private Flags add(Flags f) { flags |= f.valueOf(); return this; } public Flags remove(Flags f) { flags &= ~f.valueOf(); return this; } public static Flags parse(String s) { char[] ca = s.toCharArray(); Flags f = new Flags(0); for (int i = 0; i < ca.length; i++) { Flags v = parse(ca[i]); if (f.contains(v)) throw new DuplicateFormatFlagsException(v.toString()); f.add(v); } return f; } // parse those flags which may be provided by users private static Flags parse(char c) { switch (c) { case '-': return LEFT_JUSTIFY; case '#': return ALTERNATE; case '+': return PLUS; case ' ': return LEADING_SPACE; case '0': return ZERO_PAD; case ',': return GROUP; case '(': return PARENTHESES; case '<': return PREVIOUS; default: throw new UnknownFormatFlagsException(String.valueOf(c)); } } // Returns a string representation of the current <tt>Flags</tt>. public static String toString(Flags f) { return f.toString(); } public String toString() { StringBuilder sb = new StringBuilder(); if (contains(LEFT_JUSTIFY)) sb.append('-'); if (contains(UPPERCASE)) sb.append('^'); if (contains(ALTERNATE)) sb.append('#'); if (contains(PLUS)) sb.append('+'); if (contains(LEADING_SPACE)) sb.append(' '); if (contains(ZERO_PAD)) sb.append('0'); if (contains(GROUP)) sb.append(','); if (contains(PARENTHESES)) sb.append('('); if (contains(PREVIOUS)) sb.append('<'); return sb.toString(); } } private static class Conversion { // Byte, Short, Integer, Long, BigInteger // (and associated primitives due to autoboxing) static final char DECIMAL_INTEGER = 'd'; static final char OCTAL_INTEGER = 'o'; static final char HEXADECIMAL_INTEGER = 'x'; static final char HEXADECIMAL_INTEGER_UPPER = 'X'; // Float, Double, BigDecimal // (and associated primitives due to autoboxing) static final char SCIENTIFIC = 'e'; static final char SCIENTIFIC_UPPER = 'E'; static final char GENERAL = 'g'; static final char GENERAL_UPPER = 'G'; static final char DECIMAL_FLOAT = 'f'; static final char HEXADECIMAL_FLOAT = 'a'; static final char HEXADECIMAL_FLOAT_UPPER = 'A'; // Character, Byte, Short, Integer // (and associated primitives due to autoboxing) static final char CHARACTER = 'c'; static final char CHARACTER_UPPER = 'C'; // java.util.Date, java.util.Calendar, long static final char DATE_TIME = 't'; static final char DATE_TIME_UPPER = 'T'; // if (arg.TYPE != boolean) return boolean // if (arg != null) return true; else return false; static final char BOOLEAN = 'b'; static final char BOOLEAN_UPPER = 'B'; // if (arg instanceof Formattable) arg.formatTo() // else arg.toString(); static final char STRING = 's'; static final char STRING_UPPER = 'S'; // arg.hashCode() static final char HASHCODE = 'h'; static final char HASHCODE_UPPER = 'H'; static final char LINE_SEPARATOR = 'n'; static final char PERCENT_SIGN = '%'; static boolean isValid(char c) { return (isGeneral(c) || isInteger(c) || isFloat(c) || isText(c) || c == 't' || isCharacter(c)); } // Returns true iff the Conversion is applicable to all objects. static boolean isGeneral(char c) { switch (c) { case BOOLEAN: case BOOLEAN_UPPER: case STRING: case STRING_UPPER: case HASHCODE: case HASHCODE_UPPER: return true; default: return false; } } // Returns true iff the Conversion is applicable to character. static boolean isCharacter(char c) { switch (c) { case CHARACTER: case CHARACTER_UPPER: return true; default: return false; } } // Returns true iff the Conversion is an integer type. static boolean isInteger(char c) { switch (c) { case DECIMAL_INTEGER: case OCTAL_INTEGER: case HEXADECIMAL_INTEGER: case HEXADECIMAL_INTEGER_UPPER: return true; default: return false; } } // Returns true iff the Conversion is a floating-point type. static boolean isFloat(char c) { switch (c) { case SCIENTIFIC: case SCIENTIFIC_UPPER: case GENERAL: case GENERAL_UPPER: case DECIMAL_FLOAT: case HEXADECIMAL_FLOAT: case HEXADECIMAL_FLOAT_UPPER: return true; default: return false; } } // Returns true iff the Conversion does not require an argument static boolean isText(char c) { switch (c) { case LINE_SEPARATOR: case PERCENT_SIGN: return true; default: return false; } } } private static class DateTime { static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23) static final char HOUR_0 = 'I'; // (01 - 12) static final char HOUR_OF_DAY = 'k'; // (0 - 23) -- like H static final char HOUR = 'l'; // (1 - 12) -- like I static final char MINUTE = 'M'; // (00 - 59) static final char NANOSECOND = 'N'; // (000000000 - 999999999) static final char MILLISECOND = 'L'; // jdk, not in gnu (000 - 999) static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?) static final char AM_PM = 'p'; // (am or pm) static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?) static final char SECOND = 'S'; // (00 - 60 - leap second) static final char TIME = 'T'; // (24 hour hh:mm:ss) static final char ZONE_NUMERIC = 'z'; // (-1200 - +1200) - ls minus? static final char ZONE = 'Z'; // (symbol) // Date static final char NAME_OF_DAY_ABBREV = 'a'; // 'a' static final char NAME_OF_DAY = 'A'; // 'A' static final char NAME_OF_MONTH_ABBREV = 'b'; // 'b' static final char NAME_OF_MONTH = 'B'; // 'B' static final char CENTURY = 'C'; // (00 - 99) static final char DAY_OF_MONTH_0 = 'd'; // (01 - 31) static final char DAY_OF_MONTH = 'e'; // (1 - 31) -- like d // * static final char ISO_WEEK_OF_YEAR_2 = 'g'; // cross %y %V // * static final char ISO_WEEK_OF_YEAR_4 = 'G'; // cross %Y %V static final char NAME_OF_MONTH_ABBREV_X = 'h'; // -- same b static final char DAY_OF_YEAR = 'j'; // (001 - 366) static final char MONTH = 'm'; // (01 - 12) // * static final char DAY_OF_WEEK_1 = 'u'; // (1 - 7) Monday // * static final char WEEK_OF_YEAR_SUNDAY = 'U'; // (0 - 53) Sunday+ // * static final char WEEK_OF_YEAR_MONDAY_01 = 'V'; // (01 - 53) Monday+ // * static final char DAY_OF_WEEK_0 = 'w'; // (0 - 6) Sunday // * static final char WEEK_OF_YEAR_MONDAY = 'W'; // (00 - 53) Monday static final char YEAR_2 = 'y'; // (00 - 99) static final char YEAR_4 = 'Y'; // (0000 - 9999) // Composites static final char TIME_12_HOUR = 'r'; // (hh:mm:ss [AP]M) static final char TIME_24_HOUR = 'R'; // (hh:mm same as %H:%M) // * static final char LOCALE_TIME = 'X'; // (%H:%M:%S) - parse format? static final char DATE_TIME = 'c'; // (Sat Nov 04 12:02:33 EST 1999) static final char DATE = 'D'; // (mm/dd/yy) static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d) // * static final char LOCALE_DATE = 'x'; // (mm/dd/yy) static boolean isValid(char c) { switch (c) { case HOUR_OF_DAY_0: case HOUR_0: case HOUR_OF_DAY: case HOUR: case MINUTE: case NANOSECOND: case MILLISECOND: case MILLISECOND_SINCE_EPOCH: case AM_PM: case SECONDS_SINCE_EPOCH: case SECOND: case TIME: case ZONE_NUMERIC: case ZONE: // Date case NAME_OF_DAY_ABBREV: case NAME_OF_DAY: case NAME_OF_MONTH_ABBREV: case NAME_OF_MONTH: case CENTURY: case DAY_OF_MONTH_0: case DAY_OF_MONTH: // * case ISO_WEEK_OF_YEAR_2: // * case ISO_WEEK_OF_YEAR_4: case NAME_OF_MONTH_ABBREV_X: case DAY_OF_YEAR: case MONTH: // * case DAY_OF_WEEK_1: // * case WEEK_OF_YEAR_SUNDAY: // * case WEEK_OF_YEAR_MONDAY_01: // * case DAY_OF_WEEK_0: // * case WEEK_OF_YEAR_MONDAY: case YEAR_2: case YEAR_4: // Composites case TIME_12_HOUR: case TIME_24_HOUR: // * case LOCALE_TIME: case DATE_TIME: case DATE: case ISO_STANDARD_DATE: // * case LOCALE_DATE: return true; default: return false; } } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Resizable-array implementation of the <tt>List</tt> interface. Implements * all optional list operations, and permits all elements, including * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface, * this class provides methods to manipulate the size of the array that is * used internally to store the list. (This class is roughly equivalent to * <tt>Vector</tt>, except that it is unsynchronized.) * * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>, * that is, adding n elements requires O(n) time. All of the other operations * run in linear time (roughly speaking). The constant factor is low compared * to that for the <tt>LinkedList</tt> implementation. * * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is * the size of the array used to store the elements in the list. It is always * at least as large as the list size. As elements are added to an ArrayList, * its capacity grows automatically. The details of the growth policy are not * specified beyond the fact that adding an element has constant amortized * time cost. * * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance * before adding a large number of elements using the <tt>ensureCapacity</tt> * operation. This may reduce the amount of incremental reallocation. * {@description.close} * * {@property.open uncheckable} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access an <tt>ArrayList</tt> instance concurrently, * and at least one of the threads modifies the list structurally, it * <i>must</i> be synchronized externally. (A structural modification is * any operation that adds or deletes one or more elements, or explicitly * resizes the backing array; merely setting the value of an element is not * a structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the list. * {@property.close} * * {@description.open} * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> * List list = Collections.synchronizedList(new ArrayList(...));</pre> * {@description.close} * * {@description.open} * <p><a name="fail-fast"/> * The iterators returned by this class's {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>: * if the list is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or * {@link ListIterator#add(Object) add} methods, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see LinkedList * @see Vector * @since 1.2 */ public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /** {@collect.stats} * {@description.open} * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. * {@description.close} */ private transient Object[] elementData; /** {@collect.stats} * {@description.open} * The size of the ArrayList (the number of elements it contains). * {@description.close} * * @serial */ private int size; /** {@collect.stats} * {@description.open} * Constructs an empty list with the specified initial capacity. * {@description.close} * * @param initialCapacity the initial capacity of the list * @exception IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** {@collect.stats} * {@description.open} * Constructs an empty list with an initial capacity of ten. * {@description.close} */ public ArrayList() { this(10); } /** {@collect.stats} * {@description.open} * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * {@description.close} * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } /** {@collect.stats} * {@description.open} * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. * {@description.close} */ public void trimToSize() { modCount++; int oldCapacity = elementData.length; if (size < oldCapacity) { elementData = Arrays.copyOf(elementData, size); } } /** {@collect.stats} * {@description.open} * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * {@description.close} * * @param minCapacity the desired minimum capacity */ public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } } /** {@collect.stats} * {@description.open} * Returns the number of elements in this list. * {@description.close} * * @return the number of elements in this list */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains no elements. * {@description.close} * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} */ public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} */ public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * {@description.close} * * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { try { @SuppressWarnings("unchecked") ArrayList<E> v = (ArrayList<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this list in * proper sequence */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list in proper * sequence (from first to last element); the runtime type of the returned * array is that of the specified array. If the list fits in the * specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * * <p>If the list fits in the specified array with room to spare * (i.e., the array has more elements than the list), the element in * the array immediately following the end of the collection is set to * <tt>null</tt>. (This is useful in determining the length of the * list <i>only</i> if the caller knows that the list does not contain * any null elements.) * {@description.close} * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") 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(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** {@collect.stats} * {@description.open} * Returns the element at the specified position in this list. * {@description.close} * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { rangeCheck(index); return elementData(index); } /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this list with * the specified element. * {@description.close} * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list. * {@description.close} * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * {@description.close} * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * {@description.close} * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } /** {@collect.stats} * {@description.open} * Removes all of the elements from this list. The list will * be empty after this call returns. * {@description.close} */ public void clear() { modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the * specified collection's Iterator. * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is * undefined if the specified collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified collection is this list, and this * list is nonempty.) * {@property.close} * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * {@description.close} * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** {@collect.stats} * {@description.open} * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * {@description.close} * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newSize = size - (toIndex-fromIndex); while (size != newSize) elementData[--size] = null; } /** {@collect.stats} * {@description.open} * Checks if the given index is in range. If not, throws an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. * {@description.close} */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** {@collect.stats} * {@description.open} * A version of rangeCheck used by add and addAll. * {@description.close} */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** {@collect.stats} * {@description.open} * Constructs an IndexOutOfBoundsException detail message. * Of the many possible refactorings of the error handling code, * this "outlining" performs best with both server and client VMs. * {@description.close} */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } /** {@collect.stats} * {@description.open} * Removes from this list all of its elements that are contained in the * specified collection. * {@description.close} * * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } /** {@collect.stats} * {@description.open} * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all * of its elements that are not contained in the specified collection. * {@description.close} * * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean retainAll(Collection<?> c) { return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } /** {@collect.stats} * {@description.open} * Save the state of the <tt>ArrayList</tt> instance to a stream (that * is, serialize it). * {@description.close} * * @serialData The length of the array backing the <tt>ArrayList</tt> * instance is emitted (int), followed by all of its elements * (each an <tt>Object</tt>) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out array length s.writeInt(elementData.length); // Write out all elements in the proper order. for (int i=0; i<size; i++) s.writeObject(elementData[i]); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, * deserialize it). * {@description.close} */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); // Read in array length and allocate array int arrayLength = s.readInt(); Object[] a = elementData = new Object[arrayLength]; // Read in all elements in the proper order. for (int i=0; i<size; i++) a[i] = s.readObject(); } /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list. * The specified index indicates the first element that would be * returned by an initial call to {@link ListIterator#next next}. * An initial call to {@link ListIterator#previous previous} would * return the element with the specified index minus one. * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence). * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @see #listIterator(int) */ public ListIterator<E> listIterator() { return new ListItr(0); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** {@collect.stats} * {@description.open} * An optimized version of AbstractList.Itr * {@description.close} */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** {@collect.stats} * {@description.open} * An optimized version of AbstractList.ListItr * {@description.close} */ private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } /** {@collect.stats} * {@description.open} * Returns a view of the portion of this list between the specified * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If * {@code fromIndex} and {@code toIndex} are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations. * * <p>This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list. For example, the following idiom * removes a range of elements from a list: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for {@link #indexOf(Object)} and * {@link #lastIndexOf(Object)}, and all of the algorithms in the * {@link Collections} class can be applied to a subList. * {@description.close} * * {@property.open formal:java.util.List_UnsynchronizedSubList} * <p>The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list. (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * {@property.close} * * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } private class SubList extends AbstractList<E> implements RandomAccess { private final AbstractList<E> parent; private final int parentOffset; private final int offset; private int size; SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; } public E set(int index, E e) { rangeCheck(index); checkForComodification(); E oldValue = ArrayList.this.elementData(offset + index); ArrayList.this.elementData[offset + index] = e; return oldValue; } public E get(int index) { rangeCheck(index); checkForComodification(); return ArrayList.this.elementData(offset + index); } public int size() { checkForComodification(); return this.size; } public void add(int index, E e) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount; this.size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = parent.remove(parentOffset + index); this.modCount = parent.modCount; this.size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); parent.removeRange(parentOffset + fromIndex, parentOffset + toIndex); this.modCount = parent.modCount; this.size -= toIndex - fromIndex; } public boolean addAll(Collection<? extends E> c) { return addAll(this.size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize==0) return false; checkForComodification(); parent.addAll(parentOffset + index, c); this.modCount = parent.modCount; this.size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); return new ListIterator<E>() { int cursor = index; int lastRet = -1; int expectedModCount = ArrayList.this.modCount; public boolean hasNext() { return cursor != SubList.this.size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= SubList.this.size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[offset + (lastRet = i)]; } public boolean hasPrevious() { return cursor != 0; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[offset + (lastRet = i)]; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; SubList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (expectedModCount != ArrayList.this.modCount) throw new ConcurrentModificationException(); } }; } public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, offset, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+this.size; } private void checkForComodification() { if (ArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A comparison function, which imposes a <i>total ordering</i> on some * collection of objects. Comparators can be passed to a sort method (such * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control * over the sort order. Comparators can also be used to control the order of * certain data structures (such as {@link SortedSet sorted sets} or {@link * SortedMap sorted maps}), or to provide an ordering for collections of * objects that don't have a {@link Comparable natural ordering}.<p> * * The ordering imposed by a comparator <tt>c</tt> on a set of elements * <tt>S</tt> is said to be <i>consistent with equals</i> if and only if * <tt>c.compare(e1, e2)==0</tt> has the same boolean value as * <tt>e1.equals(e2)</tt> for every <tt>e1</tt> and <tt>e2</tt> in * <tt>S</tt>.<p> * {@description.close} * * {@property.open uncheckable} * Caution should be exercised when using a comparator capable of imposing an * ordering inconsistent with equals to order a sorted set (or sorted map). * Suppose a sorted set (or sorted map) with an explicit comparator <tt>c</tt> * is used with elements (or keys) drawn from a set <tt>S</tt>. If the * ordering imposed by <tt>c</tt> on <tt>S</tt> is inconsistent with equals, * the sorted set (or sorted map) will behave "strangely." In particular the * sorted set (or sorted map) will violate the general contract for set (or * map), which is defined in terms of <tt>equals</tt>.<p> * * For example, suppose one adds two elements {@code a} and {@code b} such that * {@code (a.equals(b) && c.compare(a, b) != 0)} * to an empty {@code TreeSet} with comparator {@code c}. * The second {@code add} operation will return * true (and the size of the tree set will increase) because {@code a} and * {@code b} are not equivalent from the tree set's perspective, even though * this is contrary to the specification of the * {@link Set#add Set.add} method.<p> * {@property.close} * * {@description.open} * Note: It is generally a good idea for comparators to also implement * <tt>java.io.Serializable</tt>, as they may be used as ordering methods in * serializable data structures (like {@link TreeSet}, {@link TreeMap}). In * order for the data structure to serialize successfully, the comparator (if * provided) must implement <tt>Serializable</tt>.<p> * * For the mathematically inclined, the <i>relation</i> that defines the * <i>imposed ordering</i> that a given comparator <tt>c</tt> imposes on a * given set of objects <tt>S</tt> is:<pre> * {(x, y) such that c.compare(x, y) &lt;= 0}. * </pre> The <i>quotient</i> for this total order is:<pre> * {(x, y) such that c.compare(x, y) == 0}. * </pre> * * It follows immediately from the contract for <tt>compare</tt> that the * quotient is an <i>equivalence relation</i> on <tt>S</tt>, and that the * imposed ordering is a <i>total order</i> on <tt>S</tt>. When we say that * the ordering imposed by <tt>c</tt> on <tt>S</tt> is <i>consistent with * equals</i>, we mean that the quotient for the ordering is the equivalence * relation defined by the objects' {@link Object#equals(Object) * equals(Object)} method(s):<pre> * {(x, y) such that x.equals(y)}. </pre><p> * * This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <T> the type of objects that may be compared by this comparator * * @author Josh Bloch * @author Neal Gafter * @see Comparable * @see java.io.Serializable * @since 1.2 */ public interface Comparator<T> { /** {@collect.stats} * {@description.open} * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.<p> * * In the foregoing description, the notation * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical * <i>signum</i> function, which is defined to return one of <tt>-1</tt>, * <tt>0</tt>, or <tt>1</tt> according to whether the value of * <i>expression</i> is negative, zero or positive.<p> * {@description.close} * * {@property.open static} * The implementor must ensure that <tt>sgn(compare(x, y)) == * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This * implies that <tt>compare(x, y)</tt> must throw an exception if and only * if <tt>compare(y, x)</tt> throws an exception.)<p> * {@property.close} * * {@property.open static} * The implementor must also ensure that the relation is transitive: * <tt>((compare(x, y)&gt;0) &amp;&amp; (compare(y, z)&gt;0))</tt> implies * <tt>compare(x, z)&gt;0</tt>.<p> * {@property.close} * * {@property.open static} * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt> * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all * <tt>z</tt>.<p> * {@property.close} * * {@description.open} * It is generally the case, but <i>not</i> strictly required that * <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking, * any comparator that violates this condition should clearly indicate * this fact. The recommended language is "Note: this comparator * imposes orderings that are inconsistent with equals." * {@description.close} * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the * second. * @throws ClassCastException if the arguments' types prevent them from * being compared by this comparator. */ int compare(T o1, T o2); /** {@collect.stats} * {@description.open} * Indicates whether some other object is &quot;equal to&quot; this * comparator. This method must obey the general contract of * {@link Object#equals(Object)}. Additionally, this method can return * <tt>true</tt> <i>only</i> if the specified object is also a comparator * and it imposes the same ordering as this comparator. Thus, * <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1, * o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference * <tt>o1</tt> and <tt>o2</tt>.<p> * * Note that it is <i>always</i> safe <i>not</i> to override * <tt>Object.equals(Object)</tt>. However, overriding this method may, * in some cases, improve performance by allowing programs to determine * that two distinct comparators impose the same order. * {@description.close} * * @param obj the reference object with which to compare. * @return <code>true</code> only if the specified object is also * a comparator and it imposes the same ordering as this * comparator. * @see Object#equals(Object) * @see Object#hashCode() */ boolean equals(Object obj); }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.lang.reflect.*; /** {@collect.stats} * {@description.open} * This class contains various methods for manipulating arrays (such as * sorting and searching). This class also contains a static factory * that allows arrays to be viewed as lists. * * <p>The methods in this class all throw a <tt>NullPointerException</tt> if * the specified array reference is null, except where noted. * * <p>The documentation for the methods contained in this class includes * briefs description of the <i>implementations</i>. Such descriptions should * be regarded as <i>implementation notes</i>, rather than parts of the * <i>specification</i>. Implementors should feel free to substitute other * algorithms, so long as the specification itself is adhered to. (For * example, the algorithm used by <tt>sort(Object[])</tt> does not have to be * a mergesort, but it does have to be <i>stable</i>.) * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @author John Rose * @since 1.2 */ public class Arrays { // Suppresses default constructor, ensuring non-instantiability. private Arrays() { } // Sorting /** {@collect.stats} * {@description.open} * Sorts the specified array of longs into ascending numerical order. * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(long[] a) { sort1(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of longs into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.) * * <p>The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(long[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort1(a, fromIndex, toIndex-fromIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of ints into ascending numerical order. * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(int[] a) { sort1(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of ints into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.)<p> * * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(int[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort1(a, fromIndex, toIndex-fromIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of shorts into ascending numerical order. * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(short[] a) { sort1(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of shorts into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.)<p> * * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(short[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort1(a, fromIndex, toIndex-fromIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of chars into ascending numerical order. * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(char[] a) { sort1(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of chars into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.)<p> * * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(char[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort1(a, fromIndex, toIndex-fromIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of bytes into ascending numerical order. * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(byte[] a) { sort1(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of bytes into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.)<p> * * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(byte[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort1(a, fromIndex, toIndex-fromIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of doubles into ascending numerical order. * <p> * The <code>&lt;</code> relation does not provide a total order on * all floating-point values; although they are distinct numbers * <code>-0.0 == 0.0</code> is <code>true</code> and a NaN value * compares neither less than, greater than, nor equal to any * floating-point value, even itself. To allow the sort to * proceed, instead of using the <code>&lt;</code> relation to * determine ascending numerical order, this method uses the total * order imposed by {@link Double#compareTo}. This ordering * differs from the <code>&lt;</code> relation in that * <code>-0.0</code> is treated as less than <code>0.0</code> and * NaN is considered greater than any other floating-point value. * For the purposes of sorting, all NaN values are considered * equivalent and equal. * <p> * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(double[] a) { sort2(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of doubles into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.) * <p> * The <code>&lt;</code> relation does not provide a total order on * all floating-point values; although they are distinct numbers * <code>-0.0 == 0.0</code> is <code>true</code> and a NaN value * compares neither less than, greater than, nor equal to any * floating-point value, even itself. To allow the sort to * proceed, instead of using the <code>&lt;</code> relation to * determine ascending numerical order, this method uses the total * order imposed by {@link Double#compareTo}. This ordering * differs from the <code>&lt;</code> relation in that * <code>-0.0</code> is treated as less than <code>0.0</code> and * NaN is considered greater than any other floating-point value. * For the purposes of sorting, all NaN values are considered * equivalent and equal. * <p> * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(double[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort2(a, fromIndex, toIndex); } /** {@collect.stats} * {@description.open} * Sorts the specified array of floats into ascending numerical order. * <p> * The <code>&lt;</code> relation does not provide a total order on * all floating-point values; although they are distinct numbers * <code>-0.0f == 0.0f</code> is <code>true</code> and a NaN value * compares neither less than, greater than, nor equal to any * floating-point value, even itself. To allow the sort to * proceed, instead of using the <code>&lt;</code> relation to * determine ascending numerical order, this method uses the total * order imposed by {@link Float#compareTo}. This ordering * differs from the <code>&lt;</code> relation in that * <code>-0.0f</code> is treated as less than <code>0.0f</code> and * NaN is considered greater than any other floating-point value. * For the purposes of sorting, all NaN values are considered * equivalent and equal. * <p> * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted */ public static void sort(float[] a) { sort2(a, 0, a.length); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of floats into * ascending numerical order. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.) * <p> * The <code>&lt;</code> relation does not provide a total order on * all floating-point values; although they are distinct numbers * <code>-0.0f == 0.0f</code> is <code>true</code> and a NaN value * compares neither less than, greater than, nor equal to any * floating-point value, even itself. To allow the sort to * proceed, instead of using the <code>&lt;</code> relation to * determine ascending numerical order, this method uses the total * order imposed by {@link Float#compareTo}. This ordering * differs from the <code>&lt;</code> relation in that * <code>-0.0f</code> is treated as less than <code>0.0f</code> and * NaN is considered greater than any other floating-point value. * For the purposes of sorting, all NaN values are considered * equivalent and equal. * <p> * The sorting algorithm is a tuned quicksort, adapted from Jon * L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", * Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November * 1993). This algorithm offers n*log(n) performance on many data sets * that cause other quicksorts to degrade to quadratic performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void sort(float[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); sort2(a, fromIndex, toIndex); } private static void sort2(double a[], int fromIndex, int toIndex) { final long NEG_ZERO_BITS = Double.doubleToLongBits(-0.0d); /* * The sort is done in three phases to avoid the expense of using * NaN and -0.0 aware comparisons during the main sort. */ /* * Preprocessing phase: Move any NaN's to end of array, count the * number of -0.0's, and turn them into 0.0's. */ int numNegZeros = 0; int i = fromIndex, n = toIndex; while(i < n) { if (a[i] != a[i]) { swap(a, i, --n); } else { if (a[i]==0 && Double.doubleToLongBits(a[i])==NEG_ZERO_BITS) { a[i] = 0.0d; numNegZeros++; } i++; } } // Main sort phase: quicksort everything but the NaN's sort1(a, fromIndex, n-fromIndex); // Postprocessing phase: change 0.0's to -0.0's as required if (numNegZeros != 0) { int j = binarySearch0(a, fromIndex, n, 0.0d); // posn of ANY zero do { j--; } while (j>=fromIndex && a[j]==0.0d); // j is now one less than the index of the FIRST zero for (int k=0; k<numNegZeros; k++) a[++j] = -0.0d; } } private static void sort2(float a[], int fromIndex, int toIndex) { final int NEG_ZERO_BITS = Float.floatToIntBits(-0.0f); /* * The sort is done in three phases to avoid the expense of using * NaN and -0.0 aware comparisons during the main sort. */ /* * Preprocessing phase: Move any NaN's to end of array, count the * number of -0.0's, and turn them into 0.0's. */ int numNegZeros = 0; int i = fromIndex, n = toIndex; while(i < n) { if (a[i] != a[i]) { swap(a, i, --n); } else { if (a[i]==0 && Float.floatToIntBits(a[i])==NEG_ZERO_BITS) { a[i] = 0.0f; numNegZeros++; } i++; } } // Main sort phase: quicksort everything but the NaN's sort1(a, fromIndex, n-fromIndex); // Postprocessing phase: change 0.0's to -0.0's as required if (numNegZeros != 0) { int j = binarySearch0(a, fromIndex, n, 0.0f); // posn of ANY zero do { j--; } while (j>=fromIndex && a[j]==0.0f); // j is now one less than the index of the FIRST zero for (int k=0; k<numNegZeros; k++) a[++j] = -0.0f; } } /* * The code for each of the seven primitive types is largely identical. * C'est la vie. */ /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of longs into ascending order. * {@description.close} */ private static void sort1(long x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } long v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(long x[], int a, int b) { long t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(long x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed longs. * {@description.close} */ private static int med3(long x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of integers into ascending order. * {@description.close} */ private static void sort1(int x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } int v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(int x[], int a, int b) { int t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(int x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed integers. * {@description.close} */ private static int med3(int x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of shorts into ascending order. * {@description.close} */ private static void sort1(short x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } short v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(short x[], int a, int b) { short t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(short x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed shorts. * {@description.close} */ private static int med3(short x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of chars into ascending order. * {@description.close} */ private static void sort1(char x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } char v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(char x[], int a, int b) { char t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(char x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed chars. * {@description.close} */ private static int med3(char x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of bytes into ascending order. * {@description.close} */ private static void sort1(byte x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } byte v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(byte x[], int a, int b) { byte t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(byte x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed bytes. * {@description.close} */ private static int med3(byte x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of doubles into ascending order. * {@description.close} */ private static void sort1(double x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } double v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(double x[], int a, int b) { double t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(double x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed doubles. * {@description.close} */ private static int med3(double x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified sub-array of floats into ascending order. * {@description.close} */ private static void sort1(float x[], int off, int len) { // Insertion sort on smallest arrays if (len < 7) { for (int i=off; i<len+off; i++) for (int j=i; j>off && x[j-1]>x[j]; j--) swap(x, j, j-1); return; } // Choose a partition element, v int m = off + (len >> 1); // Small arrays, middle element if (len > 7) { int l = off; int n = off + len - 1; if (len > 40) { // Big arrays, pseudomedian of 9 int s = len/8; l = med3(x, l, l+s, l+2*s); m = med3(x, m-s, m, m+s); n = med3(x, n-2*s, n-s, n); } m = med3(x, l, m, n); // Mid-size, med of 3 } float v = x[m]; // Establish Invariant: v* (<v)* (>v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); } // Swap partition elements back to middle int s, n = off + len; s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); // Recursively sort non-partition-elements if ((s = b-a) > 1) sort1(x, off, s); if ((s = d-c) > 1) sort1(x, n-s, s); } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(float x[], int a, int b) { float t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)]. * {@description.close} */ private static void vecswap(float x[], int a, int b, int n) { for (int i=0; i<n; i++, a++, b++) swap(x, a, b); } /** {@collect.stats} * {@description.open} * Returns the index of the median of the three indexed floats. * {@description.close} */ private static int med3(float x[], int a, int b, int c) { return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a) : (x[b] > x[c] ? b : x[a] > x[c] ? c : a)); } /** {@collect.stats} * {@description.open} * Sorts the specified array of objects into ascending order, according to * the {@linkplain Comparable natural ordering} * of its elements. * {@description.close} * {@property.open formal:java.util.Arrays_Comparable} * All elements in the array * must implement the {@link Comparable} interface. Furthermore, all * elements in the array must be <i>mutually comparable</i> (that is, * <tt>e1.compareTo(e2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>e1</tt> and <tt>e2</tt> in the array).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * {@description.close} * * @param a the array to be sorted * @throws ClassCastException if the array contains elements that are not * <i>mutually comparable</i> (for example, strings and integers). */ public static void sort(Object[] a) { Object[] aux = (Object[])a.clone(); mergeSort(aux, a, 0, a.length, 0); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of objects into * ascending order, according to the * {@linkplain Comparable natural ordering} of its * elements. The range to be sorted extends from index * <tt>fromIndex</tt>, inclusive, to index <tt>toIndex</tt>, exclusive. * (If <tt>fromIndex==toIndex</tt>, the range to be sorted is empty.) * {@description.close} * {@property.open formal:java.util.Arrays_Comparable} * All * elements in this range must implement the {@link Comparable} * interface. Furthermore, all elements in this range must be <i>mutually * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the array).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> * @throws ClassCastException if the array contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). */ public static void sort(Object[] a, int fromIndex, int toIndex) { rangeCheck(a.length, fromIndex, toIndex); Object[] aux = copyOfRange(a, fromIndex, toIndex); mergeSort(aux, a, fromIndex, toIndex, -fromIndex); } /** {@collect.stats} * {@description.open} * Tuning parameter: list size at or below which insertion sort will be * used in preference to mergesort or quicksort. * {@description.close} */ private static final int INSERTIONSORT_THRESHOLD = 7; /** {@collect.stats} * {@description.open} * Src is the source array that starts at index 0 * Dest is the (possibly larger) array destination with a possible offset * low is the index in dest to start sorting * high is the end index in dest to end sorting * off is the offset to generate corresponding low, high in src * {@description.close} */ private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i=low; i<high; i++) for (int j=i; j>low && ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--) swap(dest, j, j-1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off); mergeSort(dest, src, mid, high, -off); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for(int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0) dest[i] = src[p++]; else dest[i] = src[q++]; } } /** {@collect.stats} * {@description.open} * Swaps x[a] with x[b]. * {@description.close} */ private static void swap(Object[] x, int a, int b) { Object t = x[a]; x[a] = x[b]; x[b] = t; } /** {@collect.stats} * {@description.open} * Sorts the specified array of objects according to the order induced by * the specified comparator. * {@description.close} * {@property.open formal:java.util.Arrays_MutuallyComparable} * All elements in the array must be * <i>mutually comparable</i> by the specified comparator (that is, * <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>e1</tt> and <tt>e2</tt> in the array).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * {@description.close} * * @param a the array to be sorted * @param c the comparator to determine the order of the array. A * <tt>null</tt> value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @throws ClassCastException if the array contains elements that are * not <i>mutually comparable</i> using the specified comparator. */ public static <T> void sort(T[] a, Comparator<? super T> c) { T[] aux = (T[])a.clone(); if (c==null) mergeSort(aux, a, 0, a.length, 0); else mergeSort(aux, a, 0, a.length, 0, c); } /** {@collect.stats} * {@description.open} * Sorts the specified range of the specified array of objects according * to the order induced by the specified comparator. The range to be * sorted extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be sorted is empty.) * {@description.close} * {@property.open formal:java.util.Arrays_MutuallyComparable} * All elements in the range must be * <i>mutually comparable</i> by the specified comparator (that is, * <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>e1</tt> and <tt>e2</tt> in the range).<p> * {@property.close} * * {@description.open} * This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort.<p> * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * {@description.close} * * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted * @param toIndex the index of the last element (exclusive) to be sorted * @param c the comparator to determine the order of the array. A * <tt>null</tt> value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @throws ClassCastException if the array contains elements that are not * <i>mutually comparable</i> using the specified comparator. * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) { rangeCheck(a.length, fromIndex, toIndex); T[] aux = (T[])copyOfRange(a, fromIndex, toIndex); if (c==null) mergeSort(aux, a, fromIndex, toIndex, -fromIndex); else mergeSort(aux, a, fromIndex, toIndex, -fromIndex, c); } /** {@collect.stats} * {@description.open} * Src is the source array that starts at index 0 * Dest is the (possibly larger) array destination with a possible offset * low is the index in dest to start sorting * high is the end index in dest to end sorting * off is the offset into src corresponding to low in dest * {@description.close} */ private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off, Comparator c) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i=low; i<high; i++) for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--) swap(dest, j, j-1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off, c); mergeSort(dest, src, mid, high, -off, c); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (c.compare(src[mid-1], src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for(int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0) dest[i] = src[p++]; else dest[i] = src[q++]; } } /** {@collect.stats} * {@description.open} * Check that fromIndex and toIndex are in range, and throw an * appropriate exception if they aren't. * {@description.close} */ private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) { if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex+")"); if (fromIndex < 0) throw new ArrayIndexOutOfBoundsException(fromIndex); if (toIndex > arrayLen) throw new ArrayIndexOutOfBoundsException(toIndex); } // Searching /** {@collect.stats} * {@description.open} * Searches the specified array of longs for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted (as * by the {@link #sort(long[])} method) prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(long[] a, long key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of longs for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted (as * by the {@link #sort(long[], int, int)} method) * prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(long[] a, int fromIndex, int toIndex, long key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(long[] a, int fromIndex, int toIndex, long key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of ints for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted (as * by the {@link #sort(int[])} method) prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(int[] a, int key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of ints for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted (as * by the {@link #sort(int[], int, int)} method) * prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of shorts for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted * (as by the {@link #sort(short[])} method) prior to making this call. If * it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(short[] a, short key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of shorts for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted * (as by the {@link #sort(short[], int, int)} method) * prior to making this call. If * it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(short[] a, int fromIndex, int toIndex, short key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(short[] a, int fromIndex, int toIndex, short key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; short midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of chars for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted (as * by the {@link #sort(char[])} method) prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(char[] a, char key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of chars for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted (as * by the {@link #sort(char[], int, int)} method) * prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(char[] a, int fromIndex, int toIndex, char key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(char[] a, int fromIndex, int toIndex, char key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; char midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of bytes for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted (as * by the {@link #sort(byte[])} method) prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(byte[] a, byte key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of bytes for the specified value using the * binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted (as * by the {@link #sort(byte[], int, int)} method) * prior to making this call. If it * is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(byte[] a, int fromIndex, int toIndex, byte key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(byte[] a, int fromIndex, int toIndex, byte key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; byte midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of doubles for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted * (as by the {@link #sort(double[])} method) prior to making this call. * If it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. This method considers all NaN values to be * equivalent and equal. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(double[] a, double key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of doubles for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted * (as by the {@link #sort(double[], int, int)} method) * prior to making this call. * If it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. This method considers all NaN values to be * equivalent and equal. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(double[] a, int fromIndex, int toIndex, double key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(double[] a, int fromIndex, int toIndex, double key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; double midVal = a[mid]; if (midVal < key) low = mid + 1; // Neither val is NaN, thisVal is smaller else if (midVal > key) high = mid - 1; // Neither val is NaN, thisVal is larger else { long midBits = Double.doubleToLongBits(midVal); long keyBits = Double.doubleToLongBits(key); if (midBits == keyBits) // Values are equal return mid; // Key found else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN) low = mid + 1; else // (0.0, -0.0) or (NaN, !NaN) high = mid - 1; } } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array of floats for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted * (as by the {@link #sort(float[])} method) prior to making this call. If * it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. This method considers all NaN values to be * equivalent and equal. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. */ public static int binarySearch(float[] a, float key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array of floats for the specified value using * the binary search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted * (as by the {@link #sort(float[], int, int)} method) * prior to making this call. If * it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains * multiple elements with the specified value, there is no guarantee which * one will be found. This method considers all NaN values to be * equivalent and equal. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(float[] a, int fromIndex, int toIndex, float key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(float[] a, int fromIndex, int toIndex, float key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; float midVal = a[mid]; if (midVal < key) low = mid + 1; // Neither val is NaN, thisVal is smaller else if (midVal > key) high = mid - 1; // Neither val is NaN, thisVal is larger else { int midBits = Float.floatToIntBits(midVal); int keyBits = Float.floatToIntBits(key); if (midBits == keyBits) // Values are equal return mid; // Key found else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN) low = mid + 1; else // (0.0, -0.0) or (NaN, !NaN) high = mid - 1; } } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted into ascending order * according to the * {@linkplain Comparable natural ordering} * of its elements (as by the * {@link #sort(Object[])} method) prior to making this call. * If it is not sorted, the results are undefined. * (If the array contains elements that are not mutually comparable (for * example, strings and integers), it <i>cannot</i> be sorted according * to the natural ordering of its elements, hence results are undefined.) * {@property.close} * {@description.open} * If the array contains multiple * elements equal to the specified object, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the search key is not comparable to the * elements of the array. */ public static int binarySearch(Object[] a, Object key) { return binarySearch0(a, 0, a.length, key); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted into ascending order * according to the * {@linkplain Comparable natural ordering} * of its elements (as by the * {@link #sort(Object[], int, int)} method) prior to making this * call. If it is not sorted, the results are undefined. * (If the range contains elements that are not mutually comparable (for * example, strings and integers), it <i>cannot</i> be sorted according * to the natural ordering of its elements, hence results are undefined.) * {@property.close} * {@description.open} * If the range contains multiple * elements equal to the specified object, there is no guarantee which * one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the search key is not comparable to the * elements of the array within the specified range. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(Object[] a, int fromIndex, int toIndex, Object key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; Comparable midVal = (Comparable)a[mid]; int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } /** {@collect.stats} * {@description.open} * Searches the specified array for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The array must be sorted into ascending order * according to the specified comparator (as by the * {@link #sort(Object[], Comparator) sort(T[], Comparator)} * method) prior to making this call. If it is * not sorted, the results are undefined. * {@property.close} * {@description.open} * If the array contains multiple * elements equal to the specified object, there is no guarantee which one * will be found. * {@description.close} * * @param a the array to be searched * @param key the value to be searched for * @param c the comparator by which the array is ordered. A * <tt>null</tt> value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @return index of the search key, if it is contained in the array; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element greater than the key, or <tt>a.length</tt> if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the array contains elements that are not * <i>mutually comparable</i> using the specified comparator, * or the search key is not comparable to the * elements of the array using this comparator. */ public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) { return binarySearch0(a, 0, a.length, key, c); } /** {@collect.stats} * {@description.open} * Searches a range of * the specified array for the specified object using the binary * search algorithm. * {@description.close} * {@property.open formal:java.util.Arrays_SortBeforeBinarySearch} * The range must be sorted into ascending order * according to the specified comparator (as by the * {@link #sort(Object[], int, int, Comparator) * sort(T[], int, int, Comparator)} * method) prior to making this call. * If it is not sorted, the results are undefined. * {@property.close} * {@description.open} * If the range contains multiple elements equal to the specified object, * there is no guarantee which one will be found. * {@description.close} * * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched * @param toIndex the index of the last element (exclusive) to be searched * @param key the value to be searched for * @param c the comparator by which the array is ordered. A * <tt>null</tt> value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the range contains elements that are not * <i>mutually comparable</i> using the specified comparator, * or the search key is not comparable to the * elements in the range using this comparator. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key, c); } // Like public version, but without range checks. private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) { if (c == null) { return binarySearch0(a, fromIndex, toIndex, key); } int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; T midVal = a[mid]; int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } // Equality Testing /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of longs are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(long[] a, long[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of ints are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(int[] a, int[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of shorts are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(short[] a, short a2[]) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of chars are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(char[] a, char[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of bytes are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(byte[] a, byte[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of booleans are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(boolean[] a, boolean[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of doubles are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * * Two doubles <tt>d1</tt> and <tt>d2</tt> are considered equal if: * <pre> <tt>new Double(d1).equals(new Double(d2))</tt></pre> * (Unlike the <tt>==</tt> operator, this method considers * <tt>NaN</tt> equals to itself, and 0.0d unequal to -0.0d.) * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal * @see Double#equals(Object) */ public static boolean equals(double[] a, double[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i])) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of floats are * <i>equal</i> to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are <tt>null</tt>.<p> * * Two floats <tt>f1</tt> and <tt>f2</tt> are considered equal if: * <pre> <tt>new Float(f1).equals(new Float(f2))</tt></pre> * (Unlike the <tt>==</tt> operator, this method considers * <tt>NaN</tt> equals to itself, and 0.0f unequal to -0.0f.) * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal * @see Float#equals(Object) */ public static boolean equals(float[] a, float[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i])) return false; return true; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays of Objects are * <i>equal</i> to one another. The two arrays are considered equal if * both arrays contain the same number of elements, and all corresponding * pairs of elements in the two arrays are equal. Two objects <tt>e1</tt> * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null * : e1.equals(e2))</tt>. In other words, the two arrays are equal if * they contain the same elements in the same order. Also, two array * references are considered equal if both are <tt>null</tt>.<p> * {@description.close} * * @param a one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal */ public static boolean equals(Object[] a, Object[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) { Object o1 = a[i]; Object o2 = a2[i]; if (!(o1==null ? o2==null : o1.equals(o2))) return false; } return true; } // Filling /** {@collect.stats} * {@description.open} * Assigns the specified long value to each element of the specified array * of longs. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(long[] a, long val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified long value to each element of the specified * range of the specified array of longs. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(long[] a, int fromIndex, int toIndex, long val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified int value to each element of the specified array * of ints. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(int[] a, int val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified int value to each element of the specified * range of the specified array of ints. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(int[] a, int fromIndex, int toIndex, int val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified short value to each element of the specified array * of shorts. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(short[] a, short val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified short value to each element of the specified * range of the specified array of shorts. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(short[] a, int fromIndex, int toIndex, short val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified char value to each element of the specified array * of chars. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(char[] a, char val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified char value to each element of the specified * range of the specified array of chars. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(char[] a, int fromIndex, int toIndex, char val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified byte value to each element of the specified array * of bytes. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(byte[] a, byte val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified byte value to each element of the specified * range of the specified array of bytes. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(byte[] a, int fromIndex, int toIndex, byte val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified boolean value to each element of the specified * array of booleans. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(boolean[] a, boolean val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified boolean value to each element of the specified * range of the specified array of booleans. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(boolean[] a, int fromIndex, int toIndex, boolean val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified double value to each element of the specified * array of doubles. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(double[] a, double val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified double value to each element of the specified * range of the specified array of doubles. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(double[] a, int fromIndex, int toIndex,double val){ rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified float value to each element of the specified array * of floats. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array */ public static void fill(float[] a, float val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified float value to each element of the specified * range of the specified array of floats. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> */ public static void fill(float[] a, int fromIndex, int toIndex, float val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified Object reference to each element of the specified * array of Objects. * {@description.close} * * @param a the array to be filled * @param val the value to be stored in all elements of the array * @throws ArrayStoreException if the specified value is not of a * runtime type that can be stored in the specified array */ public static void fill(Object[] a, Object val) { for (int i = 0, len = a.length; i < len; i++) a[i] = val; } /** {@collect.stats} * {@description.open} * Assigns the specified Object reference to each element of the specified * range of the specified array of Objects. The range to be filled * extends from index <tt>fromIndex</tt>, inclusive, to index * <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the * range to be filled is empty.) * {@description.close} * * @param a the array to be filled * @param fromIndex the index of the first element (inclusive) to be * filled with the specified value * @param toIndex the index of the last element (exclusive) to be * filled with the specified value * @param val the value to be stored in all elements of the array * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt> * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or * <tt>toIndex &gt; a.length</tt> * @throws ArrayStoreException if the specified value is not of a * runtime type that can be stored in the specified array */ public static void fill(Object[] a, int fromIndex, int toIndex, Object val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) a[i] = val; } // Cloning /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with nulls (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>null</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * The resulting array is of exactly the same class as the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with nulls (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>null</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * The resulting array is of the class <tt>newType</tt>. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @throws ArrayStoreException if an element copied from * <tt>original</tt> is not of a runtime type that can be stored in * an array of class <tt>newType</tt> * @since 1.6 */ public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>(byte)0</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static byte[] copyOf(byte[] original, int newLength) { byte[] copy = new byte[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>(short)0</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static short[] copyOf(short[] original, int newLength) { short[] copy = new short[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>0</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>0L</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static long[] copyOf(long[] original, int newLength) { long[] copy = new long[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with null characters (if necessary) * so the copy has the specified length. For all indices that are valid * in both the original array and the copy, the two arrays will contain * identical values. For any indices that are valid in the copy but not * the original, the copy will contain <tt>'\\u000'</tt>. Such indices * will exist if and only if the specified length is greater than that of * the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with null characters * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static char[] copyOf(char[] original, int newLength) { char[] copy = new char[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>0f</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static float[] copyOf(float[] original, int newLength) { float[] copy = new float[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with zeros (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>0d</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static double[] copyOf(double[] original, int newLength) { double[] copy = new double[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified array, truncating or padding with <tt>false</tt> (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>false</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * {@description.close} * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with false elements * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static boolean[] copyOf(boolean[] original, int newLength) { boolean[] copy = new boolean[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>null</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * <p> * The resulting array is of exactly the same class as the original array. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with nulls to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static <T> T[] copyOfRange(T[] original, int from, int to) { return copyOfRange(original, from, to, (Class<T[]>) original.getClass()); } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>null</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * The resulting array is of the class <tt>newType</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @param newType the class of the copy to be returned * @return a new array containing the specified range from the original array, * truncated or padded with nulls to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @throws ArrayStoreException if an element copied from * <tt>original</tt> is not of a runtime type that can be stored in * an array of class <tt>newType</tt>. * @since 1.6 */ public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>(byte)0</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>(short)0</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static short[] copyOfRange(short[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); short[] copy = new short[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>0</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>0L</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static long[] copyOfRange(long[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); long[] copy = new long[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>'\\u000'</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with null characters to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static char[] copyOfRange(char[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); char[] copy = new char[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>0f</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static float[] copyOfRange(float[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); float[] copy = new float[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>0d</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with zeros to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static double[] copyOfRange(double[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); double[] copy = new double[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } /** {@collect.stats} * {@description.open} * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>false</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * {@description.close} * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @return a new array containing the specified range from the original array, * truncated or padded with false elements to obtain the required length * @throws ArrayIndexOutOfBoundsException if {@code from < 0} * or {@code from > original.length} * @throws IllegalArgumentException if <tt>from &gt; to</tt> * @throws NullPointerException if <tt>original</tt> is null * @since 1.6 */ public static boolean[] copyOfRange(boolean[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); boolean[] copy = new boolean[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } // Misc /** {@collect.stats} * {@description.open} * Returns a fixed-size list backed by the specified array. (Changes to * the returned list "write through" to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collection#toArray}. The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly"); * </pre> * {@description.close} * * @param a the array by which the list will be backed * @return a list view of the specified array */ public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); } /** {@collect.stats} * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; ArrayList(E[] array) { if (array==null) throw new NullPointerException(); a = array; } public int size() { return a.length; } public Object[] toArray() { return a.clone(); } public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) return Arrays.copyOf(this.a, size, (Class<? extends T[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } public E get(int index) { return a[index]; } public E set(int index, E element) { E oldValue = a[index]; a[index] = element; return oldValue; } public int indexOf(Object o) { if (o==null) { for (int i=0; i<a.length; i++) if (a[i]==null) return i; } else { for (int i=0; i<a.length; i++) if (o.equals(a[i])) return i; } return -1; } public boolean contains(Object o) { return indexOf(o) != -1; } } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>long</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Long} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(long a[]) { if (a == null) return 0; int result = 1; for (long element : a) { int elementHash = (int)(element ^ (element >>> 32)); result = 31 * result + elementHash; } return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two non-null <tt>int</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Integer} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(int a[]) { if (a == null) return 0; int result = 1; for (int element : a) result = 31 * result + element; return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>short</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Short} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(short a[]) { if (a == null) return 0; int result = 1; for (short element : a) result = 31 * result + element; return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>char</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Character} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(char a[]) { if (a == null) return 0; int result = 1; for (char element : a) result = 31 * result + element; return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>byte</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Byte} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(byte a[]) { if (a == null) return 0; int result = 1; for (byte element : a) result = 31 * result + element; return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>boolean</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Boolean} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(boolean a[]) { if (a == null) return 0; int result = 1; for (boolean element : a) result = 31 * result + (element ? 1231 : 1237); return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>float</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Float} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(float a[]) { if (a == null) return 0; int result = 1; for (float element : a) result = 31 * result + Float.floatToIntBits(element); return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. * For any two <tt>double</tt> arrays <tt>a</tt> and <tt>b</tt> * such that <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is the same value that would be * obtained by invoking the {@link List#hashCode() <tt>hashCode</tt>} * method on a {@link List} containing a sequence of {@link Double} * instances representing the elements of <tt>a</tt> in the same order. * If <tt>a</tt> is <tt>null</tt>, this method returns 0. * {@description.close} * * @param a the array whose hash value to compute * @return a content-based hash code for <tt>a</tt> * @since 1.5 */ public static int hashCode(double a[]) { if (a == null) return 0; int result = 1; for (double element : a) { long bits = Double.doubleToLongBits(element); result = 31 * result + (int)(bits ^ (bits >>> 32)); } return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the contents of the specified array. If * the array contains other arrays as elements, the hash code is based on * their identities rather than their contents. It is therefore * acceptable to invoke this method on an array that contains itself as an * element, either directly or indirectly through one or more levels of * arrays. * * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that * <tt>Arrays.equals(a, b)</tt>, it is also the case that * <tt>Arrays.hashCode(a) == Arrays.hashCode(b)</tt>. * * <p>The value returned by this method is equal to the value that would * be returned by <tt>Arrays.asList(a).hashCode()</tt>, unless <tt>a</tt> * is <tt>null</tt>, in which case <tt>0</tt> is returned. * {@description.close} * * @param a the array whose content-based hash code to compute * @return a content-based hash code for <tt>a</tt> * @see #deepHashCode(Object[]) * @since 1.5 */ public static int hashCode(Object a[]) { if (a == null) return 0; int result = 1; for (Object element : a) result = 31 * result + (element == null ? 0 : element.hashCode()); return result; } /** {@collect.stats} * {@description.open} * Returns a hash code based on the "deep contents" of the specified * array. If the array contains other arrays as elements, the * hash code is based on their contents and so on, ad infinitum. * {@description.close} * {@property.open formal:java.util.Arrays_DeepHashCode} * It is therefore unacceptable to invoke this method on an array that * contains itself as an element, either directly or indirectly through * one or more levels of arrays. The behavior of such an invocation is * undefined. * {@property.close} * * {@description.open} * <p>For any two arrays <tt>a</tt> and <tt>b</tt> such that * <tt>Arrays.deepEquals(a, b)</tt>, it is also the case that * <tt>Arrays.deepHashCode(a) == Arrays.deepHashCode(b)</tt>. * * <p>The computation of the value returned by this method is similar to * that of the value returned by {@link List#hashCode()} on a list * containing the same elements as <tt>a</tt> in the same order, with one * difference: If an element <tt>e</tt> of <tt>a</tt> is itself an array, * its hash code is computed not by calling <tt>e.hashCode()</tt>, but as * by calling the appropriate overloading of <tt>Arrays.hashCode(e)</tt> * if <tt>e</tt> is an array of a primitive type, or as by calling * <tt>Arrays.deepHashCode(e)</tt> recursively if <tt>e</tt> is an array * of a reference type. If <tt>a</tt> is <tt>null</tt>, this method * returns 0. * {@description.close} * * @param a the array whose deep-content-based hash code to compute * @return a deep-content-based hash code for <tt>a</tt> * @see #hashCode(Object[]) * @since 1.5 */ public static int deepHashCode(Object a[]) { if (a == null) return 0; int result = 1; for (Object element : a) { int elementHash = 0; if (element instanceof Object[]) elementHash = deepHashCode((Object[]) element); else if (element instanceof byte[]) elementHash = hashCode((byte[]) element); else if (element instanceof short[]) elementHash = hashCode((short[]) element); else if (element instanceof int[]) elementHash = hashCode((int[]) element); else if (element instanceof long[]) elementHash = hashCode((long[]) element); else if (element instanceof char[]) elementHash = hashCode((char[]) element); else if (element instanceof float[]) elementHash = hashCode((float[]) element); else if (element instanceof double[]) elementHash = hashCode((double[]) element); else if (element instanceof boolean[]) elementHash = hashCode((boolean[]) element); else if (element != null) elementHash = element.hashCode(); result = 31 * result + elementHash; } return result; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if the two specified arrays are <i>deeply * equal</i> to one another. Unlike the {@link #equals(Object[],Object[])} * method, this method is appropriate for use with nested arrays of * arbitrary depth. * * <p>Two array references are considered deeply equal if both * are <tt>null</tt>, or if they refer to arrays that contain the same * number of elements and all corresponding pairs of elements in the two * arrays are deeply equal. * * <p>Two possibly <tt>null</tt> elements <tt>e1</tt> and <tt>e2</tt> are * deeply equal if any of the following conditions hold: * <ul> * <li> <tt>e1</tt> and <tt>e2</tt> are both arrays of object reference * types, and <tt>Arrays.deepEquals(e1, e2) would return true</tt> * <li> <tt>e1</tt> and <tt>e2</tt> are arrays of the same primitive * type, and the appropriate overloading of * <tt>Arrays.equals(e1, e2)</tt> would return true. * <li> <tt>e1 == e2</tt> * <li> <tt>e1.equals(e2)</tt> would return true. * </ul> * Note that this definition permits <tt>null</tt> elements at any depth. * * <p>If either of the specified arrays contain themselves as elements * either directly or indirectly through one or more levels of arrays, * the behavior of this method is undefined. * {@description.close} * * @param a1 one array to be tested for equality * @param a2 the other array to be tested for equality * @return <tt>true</tt> if the two arrays are equal * @see #equals(Object[],Object[]) * @since 1.5 */ public static boolean deepEquals(Object[] a1, Object[] a2) { if (a1 == a2) return true; if (a1 == null || a2==null) return false; int length = a1.length; if (a2.length != length) return false; for (int i = 0; i < length; i++) { Object e1 = a1[i]; Object e2 = a2[i]; if (e1 == e2) continue; if (e1 == null) return false; // Figure out whether the two elements are equal boolean eq; if (e1 instanceof Object[] && e2 instanceof Object[]) eq = deepEquals ((Object[]) e1, (Object[]) e2); else if (e1 instanceof byte[] && e2 instanceof byte[]) eq = equals((byte[]) e1, (byte[]) e2); else if (e1 instanceof short[] && e2 instanceof short[]) eq = equals((short[]) e1, (short[]) e2); else if (e1 instanceof int[] && e2 instanceof int[]) eq = equals((int[]) e1, (int[]) e2); else if (e1 instanceof long[] && e2 instanceof long[]) eq = equals((long[]) e1, (long[]) e2); else if (e1 instanceof char[] && e2 instanceof char[]) eq = equals((char[]) e1, (char[]) e2); else if (e1 instanceof float[] && e2 instanceof float[]) eq = equals((float[]) e1, (float[]) e2); else if (e1 instanceof double[] && e2 instanceof double[]) eq = equals((double[]) e1, (double[]) e2); else if (e1 instanceof boolean[] && e2 instanceof boolean[]) eq = equals((boolean[]) e1, (boolean[]) e2); else eq = e1.equals(e2); if (!eq) return false; } return true; } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(long)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(long[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(int)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is * <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(int[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(short)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(short[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(char)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(char[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements * are separated by the characters <tt>", "</tt> (a comma followed * by a space). Elements are converted to strings as by * <tt>String.valueOf(byte)</tt>. Returns <tt>"null"</tt> if * <tt>a</tt> is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(byte[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(boolean)</tt>. Returns <tt>"null"</tt> if * <tt>a</tt> is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(boolean[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(float)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(float[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * The string representation consists of a list of the array's elements, * enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are * separated by the characters <tt>", "</tt> (a comma followed by a * space). Elements are converted to strings as by * <tt>String.valueOf(double)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @since 1.5 */ public static String toString(double[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the contents of the specified array. * If the array contains other arrays as elements, they are converted to * strings by the {@link Object#toString} method inherited from * <tt>Object</tt>, which describes their <i>identities</i> rather than * their contents. * * <p>The value returned by this method is equal to the value that would * be returned by <tt>Arrays.asList(a).toString()</tt>, unless <tt>a</tt> * is <tt>null</tt>, in which case <tt>"null"</tt> is returned. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @see #deepToString(Object[]) * @since 1.5 */ public static String toString(Object[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) { b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); } } /** {@collect.stats} * {@description.open} * Returns a string representation of the "deep contents" of the specified * array. If the array contains other arrays as elements, the string * representation contains their contents and so on. This method is * designed for converting multidimensional arrays to strings. * * <p>The string representation consists of a list of the array's * elements, enclosed in square brackets (<tt>"[]"</tt>). Adjacent * elements are separated by the characters <tt>", "</tt> (a comma * followed by a space). Elements are converted to strings as by * <tt>String.valueOf(Object)</tt>, unless they are themselves * arrays. * * <p>If an element <tt>e</tt> is an array of a primitive type, it is * converted to a string as by invoking the appropriate overloading of * <tt>Arrays.toString(e)</tt>. If an element <tt>e</tt> is an array of a * reference type, it is converted to a string as by invoking * this method recursively. * * <p>To avoid infinite recursion, if the specified array contains itself * as an element, or contains an indirect reference to itself through one * or more levels of arrays, the self-reference is converted to the string * <tt>"[...]"</tt>. For example, an array containing only a reference * to itself would be rendered as <tt>"[[...]]"</tt>. * * <p>This method returns <tt>"null"</tt> if the specified array * is <tt>null</tt>. * {@description.close} * * @param a the array whose string representation to return * @return a string representation of <tt>a</tt> * @see #toString(Object[]) * @since 1.5 */ public static String deepToString(Object[] a) { if (a == null) return "null"; int bufLen = 20 * a.length; if (a.length != 0 && bufLen <= 0) bufLen = Integer.MAX_VALUE; StringBuilder buf = new StringBuilder(bufLen); deepToString(a, buf, new HashSet()); return buf.toString(); } private static void deepToString(Object[] a, StringBuilder buf, Set<Object[]> dejaVu) { if (a == null) { buf.append("null"); return; } int iMax = a.length - 1; if (iMax == -1) { buf.append("[]"); return; } dejaVu.add(a); buf.append('['); for (int i = 0; ; i++) { Object element = a[i]; if (element == null) { buf.append("null"); } else { Class eClass = element.getClass(); if (eClass.isArray()) { if (eClass == byte[].class) buf.append(toString((byte[]) element)); else if (eClass == short[].class) buf.append(toString((short[]) element)); else if (eClass == int[].class) buf.append(toString((int[]) element)); else if (eClass == long[].class) buf.append(toString((long[]) element)); else if (eClass == char[].class) buf.append(toString((char[]) element)); else if (eClass == float[].class) buf.append(toString((float[]) element)); else if (eClass == double[].class) buf.append(toString((double[]) element)); else if (eClass == boolean[].class) buf.append(toString((boolean[]) element)); else { // element is an array of object references if (dejaVu.contains(element)) buf.append("[...]"); else deepToString((Object[])element, buf, dejaVu); } } else { // element is non-null and not an array buf.append(element.toString()); } } if (i == iMax) break; buf.append(", "); } buf.append(']'); dejaVu.remove(a); } }
Java
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; /** {@collect.stats} * {@description.open} * The management interface for the logging facility. * * <p>There is a single global instance of the <tt>LoggingMXBean</tt>. * This instance is an * <a href="../../lang/management/ManagementFactory.html#MXBean">MXBean</a> * can be obtained by calling * the {@link LogManager#getLoggingMXBean} method or from the * {@link java.lang.management.ManagementFactory#getPlatformMBeanServer * platform <tt>MBeanServer</tt>} method. * * <p>The {@link javax.management.ObjectName ObjectName} for uniquely * identifying the <tt>LoggingMXBean</tt> within an MBeanServer is: * <blockquote> * {@link LogManager#LOGGING_MXBEAN_NAME * <tt>java.util.logging:type=Logging</tt>} * </blockquote> * {@description.close} * * @see java.lang.management.ManagementFactory * * @author Ron Mann * @author Mandy Chung * @since 1.5 * */ public interface LoggingMXBean { /** {@collect.stats} * {@description.open} * Returns the list of currently registered loggers. This method * calls {@link LogManager#getLoggerNames} and returns a list * of the logger names. * {@description.close} * * @return A list of <tt>String</tt> each of which is a * currently registered <tt>Logger</tt> name. */ public java.util.List<String> getLoggerNames(); /** {@collect.stats} * {@description.open} * Gets the name of the log level associated with the specified logger. * If the specified logger does not exist, <tt>null</tt> * is returned. * This method first finds the logger of the given name and * then returns the name of the log level by calling: * <blockquote> * {@link Logger#getLevel Logger.getLevel()}.{@link Level#getName getName()}; * </blockquote> * * <p> * If the <tt>Level</tt> of the specified logger is <tt>null</tt>, * which means that this logger's effective level is inherited * from its parent, an empty string will be returned. * {@description.close} * * @param loggerName The name of the <tt>Logger</tt> to be retrieved. * * @return The name of the log level of the specified logger; or * an empty string if the log level of the specified logger * is <tt>null</tt>. If the specified logger does not * exist, <tt>null</tt> is returned. * * @see Logger#getLevel */ public String getLoggerLevel( String loggerName ); /** {@collect.stats} * {@description.open} * Sets the specified logger to the specified new level. * If the <tt>levelName</tt> is not <tt>null</tt>, the level * of the specified logger is set to the parsed <tt>Level</tt> * matching the <tt>levelName</tt>. * If the <tt>levelName</tt> is <tt>null</tt>, the level * of the specified logger is set to <tt>null</tt> and * the effective level of the logger is inherited from * its nearest ancestor with a specific (non-null) level value. * {@description.close} * * @param loggerName The name of the <tt>Logger</tt> to be set. * Must be non-null. * @param levelName The name of the level to set the specified logger to, * or <tt>null</tt> if to set the level to inherit * from its nearest ancestor. * * @throws IllegalArgumentException if the specified logger * does not exist, or <tt>levelName</tt> is not a valid level name. * * @throws SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). * * @see Logger#setLevel */ public void setLoggerLevel( String loggerName, String levelName ); /** {@collect.stats} * {@description.open} * Returns the name of the parent for the specified logger. * If the specified logger does not exist, <tt>null</tt> is returned. * If the specified logger is the root <tt>Logger</tt> in the namespace, * the result will be an empty string. * {@description.close} * * @param loggerName The name of a <tt>Logger</tt>. * * @return the name of the nearest existing parent logger; * an empty string if the specified logger is the root logger. * If the specified logger does not exist, <tt>null</tt> * is returned. */ public String getParentLoggerName(String loggerName); }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; /** {@collect.stats} * {@description.open} * A Filter can be used to provide fine grain control over * what is logged, beyond the control provided by log levels. * <p> * Each Logger and each Handler can have a filter associated with it. * The Logger or Handler will call the isLoggable method to check * if a given LogRecord should be published. If isLoggable returns * false, the LogRecord will be discarded. * {@description.close} * * @since 1.4 */ public interface Filter { /** {@collect.stats} * {@description.open} * Check if a given log record should be published. * {@description.close} * @param record a LogRecord * @return true if the log record should be published. */ public boolean isLoggable(LogRecord record); }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.text.*; import java.util.Date; /** {@collect.stats} * {@description.open} * Print a brief summary of the LogRecord in a human readable * format. The summary will typically be 1 or 2 lines. * {@description.close} * * @since 1.4 */ public class SimpleFormatter extends Formatter { Date dat = new Date(); private final static String format = "{0,date} {0,time}"; private MessageFormat formatter; private Object args[] = new Object[1]; // Line separator string. This is the value of the line.separator // property at the moment that the SimpleFormatter was created. private String lineSeparator = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("line.separator")); /** {@collect.stats} * {@description.open} * Format the given LogRecord. * <p> * This method can be overridden in a subclass. * It is recommended to use the {@link Formatter#formatMessage} * convenience method to localize and format the message field. * {@description.close} * * @param record the log record to be formatted. * @return a formatted log record */ public synchronized String format(LogRecord record) { StringBuffer sb = new StringBuffer(); // Minimize memory allocations here. dat.setTime(record.getMillis()); args[0] = dat; StringBuffer text = new StringBuffer(); if (formatter == null) { formatter = new MessageFormat(format); } formatter.format(args, text, null); sb.append(text); sb.append(" "); if (record.getSourceClassName() != null) { sb.append(record.getSourceClassName()); } else { sb.append(record.getLoggerName()); } if (record.getSourceMethodName() != null) { sb.append(" "); sb.append(record.getSourceMethodName()); } sb.append(lineSeparator); String message = formatMessage(record); sb.append(record.getLevel().getLocalizedName()); sb.append(": "); sb.append(message); sb.append(lineSeparator); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { } } return sb.toString(); } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.security.*; /** {@collect.stats} * {@description.open} * The permission which the SecurityManager will check when code * that is running with a SecurityManager calls one of the logging * control methods (such as Logger.setLevel). * <p> * Currently there is only one named LoggingPermission. This is "control" * and it grants the ability to control the logging configuration, for * example by adding or removing Handlers, by adding or removing Filters, * or by changing logging levels. * <p> * Programmers do not normally create LoggingPermission objects directly. * Instead they are created by the security policy code based on reading * the security policy file. * {@description.close} * * * @since 1.4 * @see java.security.BasicPermission * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection * @see java.lang.SecurityManager * */ public final class LoggingPermission extends java.security.BasicPermission { private static final long serialVersionUID = 63564341580231582L; /** {@collect.stats} * {@description.open} * Creates a new LoggingPermission object. * {@description.close} * * @param name Permission name. Must be "control". * @param actions Must be either null or the empty string. * * @throws NullPointerException if <code>name</code> is <code>null</code>. * @throws IllegalArgumentException if <code>name</code> is empty or if * arguments are invalid. */ public LoggingPermission(String name, String actions) throws IllegalArgumentException { super(name); if (!name.equals("control")) { throw new IllegalArgumentException("name: " + name); } if (actions != null && actions.length() > 0) { throw new IllegalArgumentException("actions: " + actions); } } }
Java
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; /** {@collect.stats} * {@description.open} * <tt>Handler</tt> that buffers requests in a circular buffer in memory. * <p> * Normally this <tt>Handler</tt> simply stores incoming <tt>LogRecords</tt> * into its memory buffer and discards earlier records. This buffering * is very cheap and avoids formatting costs. On certain trigger * conditions, the <tt>MemoryHandler</tt> will push out its current buffer * contents to a target <tt>Handler</tt>, which will typically publish * them to the outside world. * <p> * There are three main models for triggering a push of the buffer: * <ul> * <li> * An incoming <tt>LogRecord</tt> has a type that is greater than * a pre-defined level, the <tt>pushLevel</tt>. * <li> * An external class calls the <tt>push</tt> method explicitly. * <li> * A subclass overrides the <tt>log</tt> method and scans each incoming * <tt>LogRecord</tt> and calls <tt>push</tt> if a record matches some * desired criteria. * </ul> * <p> * <b>Configuration:</b> * By default each <tt>MemoryHandler</tt> is initialized using the following * LogManager configuration properties. If properties are not defined * (or have invalid values) then the specified default values are used. * If no default value is defined then a RuntimeException is thrown. * <ul> * <li> java.util.logging.MemoryHandler.level * specifies the level for the <tt>Handler</tt> * (defaults to <tt>Level.ALL</tt>). * <li> java.util.logging.MemoryHandler.filter * specifies the name of a <tt>Filter</tt> class to use * (defaults to no <tt>Filter</tt>). * <li> java.util.logging.MemoryHandler.size * defines the buffer size (defaults to 1000). * <li> java.util.logging.MemoryHandler.push * defines the <tt>pushLevel</tt> (defaults to <tt>level.SEVERE</tt>). * <li> java.util.logging.MemoryHandler.target * specifies the name of the target <tt>Handler </tt> class. * (no default). * </ul> * {@description.close} * * @since 1.4 */ public class MemoryHandler extends Handler { private final static int DEFAULT_SIZE = 1000; private Level pushLevel; private int size; private Handler target; private LogRecord buffer[]; int start, count; // Private method to configure a ConsoleHandler from LogManager // properties and/or default values as specified in the class // javadoc. private void configure() { LogManager manager = LogManager.getLogManager(); String cname = getClass().getName(); pushLevel = manager.getLevelProperty(cname +".push", Level.SEVERE); size = manager.getIntProperty(cname + ".size", DEFAULT_SIZE); if (size <= 0) { size = DEFAULT_SIZE; } setLevel(manager.getLevelProperty(cname +".level", Level.ALL)); setFilter(manager.getFilterProperty(cname +".filter", null)); setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); } /** {@collect.stats} * {@description.open} * Create a <tt>MemoryHandler</tt> and configure it based on * <tt>LogManager</tt> configuration properties. * {@description.close} */ public MemoryHandler() { sealed = false; configure(); sealed = true; String name = "???"; try { LogManager manager = LogManager.getLogManager(); name = manager.getProperty("java.util.logging.MemoryHandler.target"); Class clz = ClassLoader.getSystemClassLoader().loadClass(name); target = (Handler) clz.newInstance(); } catch (Exception ex) { throw new RuntimeException("MemoryHandler can't load handler \"" + name + "\"" , ex); } init(); } // Initialize. Size is a count of LogRecords. private void init() { buffer = new LogRecord[size]; start = 0; count = 0; } /** {@collect.stats} * {@description.open} * Create a <tt>MemoryHandler</tt>. * <p> * The <tt>MemoryHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given <tt>pushLevel</tt> * argument and buffer size argument are used. * {@description.close} * * @param target the Handler to which to publish output. * @param size the number of log records to buffer (must be greater than zero) * @param pushLevel message level to push on * * @throws IllegalArgumentException is size is <= 0 */ public MemoryHandler(Handler target, int size, Level pushLevel) { if (target == null || pushLevel == null) { throw new NullPointerException(); } if (size <= 0) { throw new IllegalArgumentException(); } sealed = false; configure(); sealed = true; this.target = target; this.pushLevel = pushLevel; this.size = size; init(); } /** {@collect.stats} * {@description.open} * Store a <tt>LogRecord</tt> in an internal buffer. * <p> * If there is a <tt>Filter</tt>, its <tt>isLoggable</tt> * method is called to check if the given log record is loggable. * If not we return. Otherwise the given record is copied into * an internal circular buffer. Then the record's level property is * compared with the <tt>pushLevel</tt>. If the given level is * greater than or equal to the <tt>pushLevel</tt> then <tt>push</tt> * is called to write all buffered records to the target output * <tt>Handler</tt>. * {@description.close} * * @param record description of the log event. A null record is * silently ignored and is not published */ public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } int ix = (start+count)%buffer.length; buffer[ix] = record; if (count < buffer.length) { count++; } else { start++; start %= buffer.length; } if (record.getLevel().intValue() >= pushLevel.intValue()) { push(); } } /** {@collect.stats} * {@description.open} * Push any buffered output to the target <tt>Handler</tt>. * <p> * The buffer is then cleared. * {@description.close} */ public synchronized void push() { for (int i = 0; i < count; i++) { int ix = (start+i)%buffer.length; LogRecord record = buffer[ix]; target.publish(record); } // Empty the buffer. start = 0; count = 0; } /** {@collect.stats} * {@description.open} * Causes a flush on the target <tt>Handler</tt>. * <p> * {@description.close} * {@property.open} * Note that the current contents of the <tt>MemoryHandler</tt> * buffer are <b>not</b> written out. That requires a "push". * {@property.close} */ public void flush() { target.flush(); } /** {@collect.stats} * {@description.open} * Close the <tt>Handler</tt> and free all associated resources. * This will also close the target <tt>Handler</tt>. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public void close() throws SecurityException { target.close(); setLevel(Level.OFF); } /** {@collect.stats} * {@description.open} * Set the <tt>pushLevel</tt>. After a <tt>LogRecord</tt> is copied * into our internal buffer, if its level is greater than or equal to * the <tt>pushLevel</tt>, then <tt>push</tt> will be called. * {@description.close} * * @param newLevel the new value of the <tt>pushLevel</tt> * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public void setPushLevel(Level newLevel) throws SecurityException { if (newLevel == null) { throw new NullPointerException(); } LogManager manager = LogManager.getLogManager(); checkAccess(); pushLevel = newLevel; } /** {@collect.stats} * {@description.open} * Get the <tt>pushLevel</tt>. * {@description.close} * * @return the value of the <tt>pushLevel</tt> */ public synchronized Level getPushLevel() { return pushLevel; } /** {@collect.stats} * {@description.open} * Check if this <tt>Handler</tt> would actually log a given * <tt>LogRecord</tt> into its internal buffer. * <p> * This method checks if the <tt>LogRecord</tt> has an appropriate level and * whether it satisfies any <tt>Filter</tt>. However it does <b>not</b> * check whether the <tt>LogRecord</tt> would result in a "push" of the * buffer contents. It will return false if the <tt>LogRecord</tt> is Null. * <p> * {@description.close} * @param record a <tt>LogRecord</tt> * @return true if the <tt>LogRecord</tt> would be logged. * */ public boolean isLoggable(LogRecord record) { return super.isLoggable(record); } }
Java
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.util.ResourceBundle; /** {@collect.stats} * {@description.open} * The Level class defines a set of standard logging levels that * can be used to control logging output. The logging Level objects * are ordered and are specified by ordered integers. Enabling logging * at a given level also enables logging at all higher levels. * <p> * Clients should normally use the predefined Level constants such * as Level.SEVERE. * <p> * The levels in descending order are: * <ul> * <li>SEVERE (highest value) * <li>WARNING * <li>INFO * <li>CONFIG * <li>FINE * <li>FINER * <li>FINEST (lowest value) * </ul> * In addition there is a level OFF that can be used to turn * off logging, and a level ALL that can be used to enable * logging of all messages. * <p> * It is possible for third parties to define additional logging * levels by subclassing Level. In such cases subclasses should * take care to chose unique integer level values and to ensure that * they maintain the Object uniqueness property across serialization * by defining a suitable readResolve method. * {@description.close} * * @since 1.4 */ public class Level implements java.io.Serializable { private static java.util.ArrayList<Level> known = new java.util.ArrayList<Level>(); private static String defaultBundle = "sun.util.logging.resources.logging"; /** {@collect.stats} * @serial The non-localized name of the level. */ private final String name; /** {@collect.stats} * @serial The integer value of the level. */ private final int value; /** {@collect.stats} * @serial The resource bundle name to be used in localizing the level name. */ private final String resourceBundleName; /** {@collect.stats} * {@description.open} * OFF is a special level that can be used to turn off logging. * This level is initialized to <CODE>Integer.MAX_VALUE</CODE>. * {@description.close} */ public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle); /** {@collect.stats} * {@description.open} * SEVERE is a message level indicating a serious failure. * <p> * In general SEVERE messages should describe events that are * of considerable importance and which will prevent normal * program execution. They should be reasonably intelligible * to end users and to system administrators. * This level is initialized to <CODE>1000</CODE>. * {@description.close} */ public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle); /** {@collect.stats} * {@description.open} * WARNING is a message level indicating a potential problem. * <p> * In general WARNING messages should describe events that will * be of interest to end users or system managers, or which * indicate potential problems. * This level is initialized to <CODE>900</CODE>. * {@description.close} */ public static final Level WARNING = new Level("WARNING", 900, defaultBundle); /** {@collect.stats} * {@description.open} * INFO is a message level for informational messages. * <p> * Typically INFO messages will be written to the console * or its equivalent. So the INFO level should only be * used for reasonably significant messages that will * make sense to end users and system admins. * This level is initialized to <CODE>800</CODE>. * {@description.close} */ public static final Level INFO = new Level("INFO", 800, defaultBundle); /** {@collect.stats} * {@description.open} * CONFIG is a message level for static configuration messages. * <p> * CONFIG messages are intended to provide a variety of static * configuration information, to assist in debugging problems * that may be associated with particular configurations. * For example, CONFIG message might include the CPU type, * the graphics depth, the GUI look-and-feel, etc. * This level is initialized to <CODE>700</CODE>. * {@description.close} */ public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle); /** {@collect.stats} * {@description.open} * FINE is a message level providing tracing information. * <p> * All of FINE, FINER, and FINEST are intended for relatively * detailed tracing. The exact meaning of the three levels will * vary between subsystems, but in general, FINEST should be used * for the most voluminous detailed output, FINER for somewhat * less detailed output, and FINE for the lowest volume (and * most important) messages. * <p> * In general the FINE level should be used for information * that will be broadly interesting to developers who do not have * a specialized interest in the specific subsystem. * <p> * FINE messages might include things like minor (recoverable) * failures. Issues indicating potential performance problems * are also worth logging as FINE. * This level is initialized to <CODE>500</CODE>. * {@description.close} */ public static final Level FINE = new Level("FINE", 500, defaultBundle); /** {@collect.stats} * {@description.open} * FINER indicates a fairly detailed tracing message. * By default logging calls for entering, returning, or throwing * an exception are traced at this level. * This level is initialized to <CODE>400</CODE>. * {@description.close} */ public static final Level FINER = new Level("FINER", 400, defaultBundle); /** {@collect.stats} * {@description.open} * FINEST indicates a highly detailed tracing message. * This level is initialized to <CODE>300</CODE>. * {@description.close} */ public static final Level FINEST = new Level("FINEST", 300, defaultBundle); /** {@collect.stats} * {@description.open} * ALL indicates that all messages should be logged. * This level is initialized to <CODE>Integer.MIN_VALUE</CODE>. * {@description.close} */ public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle); /** {@collect.stats} * {@description.open} * Create a named Level with a given integer value. * <p> * Note that this constructor is "protected" to allow subclassing. * In general clients of logging should use one of the constant Level * objects such as SEVERE or FINEST. However, if clients need to * add new logging levels, they may subclass Level and define new * constants. * {@description.close} * @param name the name of the Level, for example "SEVERE". * @param value an integer value for the level. * @throws NullPointerException if the name is null */ protected Level(String name, int value) { this(name, value, null); } /** {@collect.stats} * {@description.open} * Create a named Level with a given integer value and a * given localization resource name. * <p> * {@description.close} * @param name the name of the Level, for example "SEVERE". * @param value an integer value for the level. * @param resourceBundleName name of a resource bundle to use in * localizing the given name. If the resourceBundleName is null * or an empty string, it is ignored. * @throws NullPointerException if the name is null */ protected Level(String name, int value, String resourceBundleName) { if (name == null) { throw new NullPointerException(); } this.name = name; this.value = value; this.resourceBundleName = resourceBundleName; synchronized (Level.class) { known.add(this); } } /** {@collect.stats} * {@description.open} * Return the level's localization resource bundle name, or * null if no localization bundle is defined. * {@description.close} * * @return localization resource bundle name */ public String getResourceBundleName() { return resourceBundleName; } /** {@collect.stats} * {@description.open} * Return the non-localized string name of the Level. * {@description.close} * * @return non-localized name */ public String getName() { return name; } /** {@collect.stats} * {@description.open} * Return the localized string name of the Level, for * the current default locale. * <p> * If no localization information is available, the * non-localized name is returned. * {@description.close} * * @return localized name */ public String getLocalizedName() { try { ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName); return rb.getString(name); } catch (Exception ex) { return name; } } /** {@collect.stats} * @return the non-localized name of the Level, for example "INFO". */ public final String toString() { return name; } /** {@collect.stats} * {@description.open} * Get the integer value for this level. This integer value * can be used for efficient ordering comparisons between * Level objects. * {@description.close} * @return the integer value for this level. */ public final int intValue() { return value; } private static final long serialVersionUID = -8176160795706313070L; // Serialization magic to prevent "doppelgangers". // This is a performance optimization. private Object readResolve() { synchronized (Level.class) { for (int i = 0; i < known.size(); i++) { Level other = known.get(i); if (this.name.equals(other.name) && this.value == other.value && (this.resourceBundleName == other.resourceBundleName || (this.resourceBundleName != null && this.resourceBundleName.equals(other.resourceBundleName)))) { return other; } } // Woops. Whoever sent us this object knows // about a new log level. Add it to our list. known.add(this); return this; } } /** {@collect.stats} * {@description.open} * Parse a level name string into a Level. * <p> * The argument string may consist of either a level name * or an integer value. * <p> * For example: * <ul> * <li> "SEVERE" * <li> "1000" * </ul> * {@description.close} * @param name string to be parsed * @throws NullPointerException if the name is null * @throws IllegalArgumentException if the value is not valid. * Valid values are integers between <CODE>Integer.MIN_VALUE</CODE> * and <CODE>Integer.MAX_VALUE</CODE>, and all known level names. * Known names are the levels defined by this class (i.e. <CODE>FINE</CODE>, * <CODE>FINER</CODE>, <CODE>FINEST</CODE>), or created by this class with * appropriate package access, or new levels defined or created * by subclasses. * * @return The parsed value. Passing an integer that corresponds to a known name * (eg 700) will return the associated name (eg <CODE>CONFIG</CODE>). * Passing an integer that does not (eg 1) will return a new level name * initialized to that value. */ public static synchronized Level parse(String name) throws IllegalArgumentException { // Check that name is not null. name.length(); // Look for a known Level with the given non-localized name. for (int i = 0; i < known.size(); i++) { Level l = known.get(i); if (name.equals(l.name)) { return l; } } // Now, check if the given name is an integer. If so, // first look for a Level with the given value and then // if necessary create one. try { int x = Integer.parseInt(name); for (int i = 0; i < known.size(); i++) { Level l = known.get(i); if (l.value == x) { return l; } } // Create a new Level. return new Level(name, x); } catch (NumberFormatException ex) { // Not an integer. // Drop through. } // Finally, look for a known level with the given localized name, // in the current default locale. // This is relatively expensive, but not excessively so. for (int i = 0; i < known.size(); i++) { Level l = known.get(i); if (name.equals(l.getLocalizedName())) { return l; } } // OK, we've tried everything and failed throw new IllegalArgumentException("Bad level \"" + name + "\""); } /** {@collect.stats} * {@description.open} * Compare two objects for value equality. * {@description.close} * @return true if and only if the two objects have the same level value. */ public boolean equals(Object ox) { try { Level lx = (Level)ox; return (lx.value == this.value); } catch (Exception ex) { return false; } } /** {@collect.stats} * {@description.open} * Generate a hashcode. * {@description.close} * @return a hashcode based on the level value */ public int hashCode() { return this.value; } }
Java
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.util.Enumeration; import java.util.List; import java.util.ArrayList; /** {@collect.stats} * {@description.open} * Logging is the implementation class of LoggingMXBean. * * The <tt>LoggingMXBean</tt> interface provides a standard * method for management access to the individual * java.util.Logger objects available at runtime. * {@description.close} * * @author Ron Mann * @author Mandy Chung * @since 1.5 * * @see javax.management * @see java.util.Logger * @see java.util.LogManager */ class Logging implements LoggingMXBean { private static LogManager logManager = LogManager.getLogManager(); /** {@collect.stats} * {@description.open} * Constructor of Logging which is the implementation class * of LoggingMXBean. * {@description.close} */ Logging() { } public List<String> getLoggerNames() { Enumeration loggers = logManager.getLoggerNames(); ArrayList<String> array = new ArrayList<String>(); for (; loggers.hasMoreElements();) { array.add((String) loggers.nextElement()); } return array; } private static String EMPTY_STRING = ""; public String getLoggerLevel(String loggerName) { Logger l = logManager.getLogger(loggerName); if (l == null) { return null; } Level level = l.getLevel(); if (level == null) { return EMPTY_STRING; } else { return level.getName(); } } public void setLoggerLevel(String loggerName, String levelName) { if (loggerName == null) { throw new NullPointerException("loggerName is null"); } Logger logger = logManager.getLogger(loggerName); if (logger == null) { throw new IllegalArgumentException("Logger " + loggerName + "does not exist"); } Level level = null; if (levelName != null) { // parse will throw IAE if logLevel is invalid level = Level.parse(levelName); } logger.setLevel(level); } public String getParentLoggerName( String loggerName ) { Logger l = logManager.getLogger( loggerName ); if (l == null) { return null; } Logger p = l.getParent(); if (p == null) { // root logger return EMPTY_STRING; } else { return p.getName(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.UnsupportedEncodingException; /** {@collect.stats} * {@description.open} * A <tt>Handler</tt> object takes log messages from a <tt>Logger</tt> and * exports them. It might for example, write them to a console * or write them to a file, or send them to a network logging service, * or forward them to an OS log, or whatever. * <p> * A <tt>Handler</tt> can be disabled by doing a <tt>setLevel(Level.OFF)</tt> * and can be re-enabled by doing a <tt>setLevel</tt> with an appropriate level. * <p> * <tt>Handler</tt> classes typically use <tt>LogManager</tt> properties to set * default values for the <tt>Handler</tt>'s <tt>Filter</tt>, <tt>Formatter</tt>, * and <tt>Level</tt>. See the specific documentation for each concrete * <tt>Handler</tt> class. * * {@description.close} * * @since 1.4 */ public abstract class Handler { private static final int offValue = Level.OFF.intValue(); private LogManager manager = LogManager.getLogManager(); private Filter filter; private Formatter formatter; private Level logLevel = Level.ALL; private ErrorManager errorManager = new ErrorManager(); private String encoding; // Package private support for security checking. When sealed // is true, we access check updates to the class. boolean sealed = true; /** {@collect.stats} * {@description.open} * Default constructor. The resulting <tt>Handler</tt> has a log * level of <tt>Level.ALL</tt>, no <tt>Formatter</tt>, and no * <tt>Filter</tt>. A default <tt>ErrorManager</tt> instance is installed * as the <tt>ErrorManager</tt>. * {@description.close} */ protected Handler() { } /** {@collect.stats} * {@description.open} * Publish a <tt>LogRecord</tt>. * <p> * The logging request was made initially to a <tt>Logger</tt> object, * which initialized the <tt>LogRecord</tt> and forwarded it here. * <p> * The <tt>Handler</tt> is responsible for formatting the message, when and * if necessary. The formatting should include localization. * {@description.close} * * @param record description of the log event. A null record is * silently ignored and is not published */ public abstract void publish(LogRecord record); /** {@collect.stats} * {@description.open} * Flush any buffered output. * {@description.close} */ public abstract void flush(); /** {@collect.stats} * {@description.open} * Close the <tt>Handler</tt> and free all associated resources. * <p> * {@description.close} * {@property.open} * The close method will perform a <tt>flush</tt> and then close the * <tt>Handler</tt>. After close has been called this <tt>Handler</tt> * should no longer be used. Method calls may either be silently * ignored or may throw runtime exceptions. * {@property.close} * * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public abstract void close() throws SecurityException; /** {@collect.stats} * {@description.open} * Set a <tt>Formatter</tt>. This <tt>Formatter</tt> will be used * to format <tt>LogRecords</tt> for this <tt>Handler</tt>. * <p> * Some <tt>Handlers</tt> may not use <tt>Formatters</tt>, in * which case the <tt>Formatter</tt> will be remembered, but not used. * <p> * {@description.close} * @param newFormatter the <tt>Formatter</tt> to use (may not be null) * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public void setFormatter(Formatter newFormatter) throws SecurityException { checkAccess(); // Check for a null pointer: newFormatter.getClass(); formatter = newFormatter; } /** {@collect.stats} * {@description.open} * Return the <tt>Formatter</tt> for this <tt>Handler</tt>. * {@description.close} * @return the <tt>Formatter</tt> (may be null). */ public Formatter getFormatter() { return formatter; } /** {@collect.stats} * {@description.open} * Set the character encoding used by this <tt>Handler</tt>. * <p> * The encoding should be set before any <tt>LogRecords</tt> are written * to the <tt>Handler</tt>. * {@description.close} * * @param encoding The name of a supported character encoding. * May be null, to indicate the default platform encoding. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception UnsupportedEncodingException if the named encoding is * not supported. */ public void setEncoding(String encoding) throws SecurityException, java.io.UnsupportedEncodingException { checkAccess(); if (encoding != null) { try { if(!java.nio.charset.Charset.isSupported(encoding)) { throw new UnsupportedEncodingException(encoding); } } catch (java.nio.charset.IllegalCharsetNameException e) { throw new UnsupportedEncodingException(encoding); } } this.encoding = encoding; } /** {@collect.stats} * {@description.open} * Return the character encoding for this <tt>Handler</tt>. * {@description.close} * * @return The encoding name. May be null, which indicates the * default encoding should be used. */ public String getEncoding() { return encoding; } /** {@collect.stats} * {@description.open} * Set a <tt>Filter</tt> to control output on this <tt>Handler</tt>. * <P> * For each call of <tt>publish</tt> the <tt>Handler</tt> will call * this <tt>Filter</tt> (if it is non-null) to check if the * <tt>LogRecord</tt> should be published or discarded. * {@description.close} * * @param newFilter a <tt>Filter</tt> object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public void setFilter(Filter newFilter) throws SecurityException { checkAccess(); filter = newFilter; } /** {@collect.stats} * {@description.open} * Get the current <tt>Filter</tt> for this <tt>Handler</tt>. * {@description.close} * * @return a <tt>Filter</tt> object (may be null) */ public Filter getFilter() { return filter; } /** {@collect.stats} * {@description.open} * Define an ErrorManager for this Handler. * <p> * The ErrorManager's "error" method will be invoked if any * errors occur while using this Handler. * {@description.close} * * @param em the new ErrorManager * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public void setErrorManager(ErrorManager em) { checkAccess(); if (em == null) { throw new NullPointerException(); } errorManager = em; } /** {@collect.stats} * {@description.open} * Retrieves the ErrorManager for this Handler. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public ErrorManager getErrorManager() { checkAccess(); return errorManager; } /** {@collect.stats} * {@description.open} * Protected convenience method to report an error to this Handler's * ErrorManager. Note that this method retrieves and uses the ErrorManager * without doing a security check. It can therefore be used in * environments where the caller may be non-privileged. * {@description.close} * * @param msg a descriptive string (may be null) * @param ex an exception (may be null) * @param code an error code defined in ErrorManager */ protected void reportError(String msg, Exception ex, int code) { try { errorManager.error(msg, ex, code); } catch (Exception ex2) { System.err.println("Handler.reportError caught:"); ex2.printStackTrace(); } } /** {@collect.stats} * {@description.open} * Set the log level specifying which message levels will be * logged by this <tt>Handler</tt>. Message levels lower than this * value will be discarded. * <p> * The intention is to allow developers to turn on voluminous * logging, but to limit the messages that are sent to certain * <tt>Handlers</tt>. * {@description.close} * * @param newLevel the new value for the log level * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public synchronized void setLevel(Level newLevel) throws SecurityException { if (newLevel == null) { throw new NullPointerException(); } checkAccess(); logLevel = newLevel; } /** {@collect.stats} * {@description.open} * Get the log level specifying which messages will be * logged by this <tt>Handler</tt>. Message levels lower * than this level will be discarded. * {@description.close} * @return the level of messages being logged. */ public synchronized Level getLevel() { return logLevel; } /** {@collect.stats} * {@description.open} * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>. * <p> * This method checks if the <tt>LogRecord</tt> has an appropriate * <tt>Level</tt> and whether it satisfies any <tt>Filter</tt>. It also * may make other <tt>Handler</tt> specific checks that might prevent a * handler from logging the <tt>LogRecord</tt>. It will return false if * the <tt>LogRecord</tt> is Null. * <p> * {@description.close} * @param record a <tt>LogRecord</tt> * @return true if the <tt>LogRecord</tt> would be logged. * */ public boolean isLoggable(LogRecord record) { int levelValue = getLevel().intValue(); if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return false; } Filter filter = getFilter(); if (filter == null) { return true; } return filter.isLoggable(record); } // Package-private support method for security checks. // If "sealed" is true, we check that the caller has // appropriate security privileges to update Handler // state and if not throw a SecurityException. void checkAccess() throws SecurityException { if (sealed) { manager.checkAccess(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.security.*; /** {@collect.stats} * {@description.open} * Simple file logging <tt>Handler</tt>. * <p> * The <tt>FileHandler</tt> can either write to a specified file, * or it can write to a rotating set of files. * <p> * For a rotating set of files, as each file reaches a given size * limit, it is closed, rotated out, and a new file opened. * Successively older files are named by adding "0", "1", "2", * etc into the base filename. * <p> * By default buffering is enabled in the IO libraries but each log * record is flushed out when it is complete. * <p> * By default the <tt>XMLFormatter</tt> class is used for formatting. * <p> * <b>Configuration:</b> * By default each <tt>FileHandler</tt> is initialized using the following * <tt>LogManager</tt> configuration properties. If properties are not defined * (or have invalid values) then the specified default values are used. * <ul> * <li> java.util.logging.FileHandler.level * specifies the default level for the <tt>Handler</tt> * (defaults to <tt>Level.ALL</tt>). * <li> java.util.logging.FileHandler.filter * specifies the name of a <tt>Filter</tt> class to use * (defaults to no <tt>Filter</tt>). * <li> java.util.logging.FileHandler.formatter * specifies the name of a <tt>Formatter</tt> class to use * (defaults to <tt>java.util.logging.XMLFormatter</tt>) * <li> java.util.logging.FileHandler.encoding * the name of the character set encoding to use (defaults to * the default platform encoding). * <li> java.util.logging.FileHandler.limit * specifies an approximate maximum amount to write (in bytes) * to any one file. If this is zero, then there is no limit. * (Defaults to no limit). * <li> java.util.logging.FileHandler.count * specifies how many output files to cycle through (defaults to 1). * <li> java.util.logging.FileHandler.pattern * specifies a pattern for generating the output file name. See * below for details. (Defaults to "%h/java%u.log"). * <li> java.util.logging.FileHandler.append * specifies whether the FileHandler should append onto * any existing files (defaults to false). * </ul> * <p> * <p> * A pattern consists of a string that includes the following special * components that will be replaced at runtime: * <ul> * <li> "/" the local pathname separator * <li> "%t" the system temporary directory * <li> "%h" the value of the "user.home" system property * <li> "%g" the generation number to distinguish rotated logs * <li> "%u" a unique number to resolve conflicts * <li> "%%" translates to a single percent sign "%" * </ul> * If no "%g" field has been specified and the file count is greater * than one, then the generation number will be added to the end of * the generated filename, after a dot. * <p> * Thus for example a pattern of "%t/java%g.log" with a count of 2 * would typically cause log files to be written on Solaris to * /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they * would be typically written to C:\TEMP\java0.log and C:\TEMP\java1.log * <p> * Generation numbers follow the sequence 0, 1, 2, etc. * <p> * Normally the "%u" unique field is set to 0. However, if the <tt>FileHandler</tt> * tries to open the filename and finds the file is currently in use by * another process it will increment the unique number field and try * again. This will be repeated until <tt>FileHandler</tt> finds a file name that * is not currently in use. If there is a conflict and no "%u" field has * been specified, it will be added at the end of the filename after a dot. * (This will be after any automatically added generation number.) * <p> * Thus if three processes were all trying to log to fred%u.%g.txt then * they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as * the first file in their rotating sequences. * <p> * {@description.close} * {@property.open uncheckable} * Note that the use of unique ids to avoid conflicts is only guaranteed * to work reliably when using a local disk file system. * {@property.close} * * @since 1.4 */ public class FileHandler extends StreamHandler { private MeteredStream meter; private boolean append; private int limit; // zero => no limit. private int count; private String pattern; private String lockFileName; private FileOutputStream lockStream; private File files[]; private static final int MAX_LOCKS = 100; private static java.util.HashMap<String, String> locks = new java.util.HashMap<String, String>(); // A metered stream is a subclass of OutputStream that // (a) forwards all its output to a target stream // (b) keeps track of how many bytes have been written private class MeteredStream extends OutputStream { OutputStream out; int written; MeteredStream(OutputStream out, int written) { this.out = out; this.written = written; } public void write(int b) throws IOException { out.write(b); written++; } public void write(byte buff[]) throws IOException { out.write(buff); written += buff.length; } public void write(byte buff[], int off, int len) throws IOException { out.write(buff,off,len); written += len; } public void flush() throws IOException { out.flush(); } public void close() throws IOException { out.close(); } } private void open(File fname, boolean append) throws IOException { int len = 0; if (append) { len = (int)fname.length(); } FileOutputStream fout = new FileOutputStream(fname.toString(), append); BufferedOutputStream bout = new BufferedOutputStream(fout); meter = new MeteredStream(bout, len); setOutputStream(meter); } // Private method to configure a FileHandler from LogManager // properties and/or default values as specified in the class // javadoc. private void configure() { LogManager manager = LogManager.getLogManager(); String cname = getClass().getName(); pattern = manager.getStringProperty(cname + ".pattern", "%h/java%u.log"); limit = manager.getIntProperty(cname + ".limit", 0); if (limit < 0) { limit = 0; } count = manager.getIntProperty(cname + ".count", 1); if (count <= 0) { count = 1; } append = manager.getBooleanProperty(cname + ".append", false); setLevel(manager.getLevelProperty(cname + ".level", Level.ALL)); setFilter(manager.getFilterProperty(cname + ".filter", null)); setFormatter(manager.getFormatterProperty(cname + ".formatter", new XMLFormatter())); try { setEncoding(manager.getStringProperty(cname +".encoding", null)); } catch (Exception ex) { try { setEncoding(null); } catch (Exception ex2) { // doing a setEncoding with null should always work. // assert false; } } } /** {@collect.stats} * {@description.open} * Construct a default <tt>FileHandler</tt>. This will be configured * entirely from <tt>LogManager</tt> properties (or their default values). * <p> * {@description.close} * @exception IOException if there are IO problems opening the files. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control"))</tt>. * @exception NullPointerException if pattern property is an empty String. */ public FileHandler() throws IOException, SecurityException { checkAccess(); configure(); openFiles(); } /** {@collect.stats} * {@description.open} * Initialize a <tt>FileHandler</tt> to write to the given filename. * <p> * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given pattern * argument is used as the filename pattern, the file limit is * set to no limit, and the file count is set to one. * <p> * There is no limit on the amount of data that may be written, * so use this with care. * {@description.close} * * @param pattern the name of the output file * @exception IOException if there are IO problems opening the files. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern) throws IOException, SecurityException { if (pattern.length() < 1 ) { throw new IllegalArgumentException(); } checkAccess(); configure(); this.pattern = pattern; this.limit = 0; this.count = 1; openFiles(); } /** {@collect.stats} * {@description.open} * Initialize a <tt>FileHandler</tt> to write to the given filename, * with optional append. * <p> * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given pattern * argument is used as the filename pattern, the file limit is * set to no limit, the file count is set to one, and the append * mode is set to the given <tt>append</tt> argument. * <p> * There is no limit on the amount of data that may be written, * so use this with care. * {@description.close} * * @param pattern the name of the output file * @param append specifies append mode * @exception IOException if there are IO problems opening the files. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern, boolean append) throws IOException, SecurityException { if (pattern.length() < 1 ) { throw new IllegalArgumentException(); } checkAccess(); configure(); this.pattern = pattern; this.limit = 0; this.count = 1; this.append = append; openFiles(); } /** {@collect.stats} * {@description.open} * Initialize a <tt>FileHandler</tt> to write to a set of files. When * (approximately) the given limit has been written to one file, * another file will be opened. The output will cycle through a set * of count files. * <p> * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given pattern * argument is used as the filename pattern, the file limit is * set to the limit argument, and the file count is set to the * given count argument. * <p> * {@description.close} * {@property.open} * The count must be at least 1. * {@property.close} * * @param pattern the pattern for naming the output file * @param limit the maximum number of bytes to write to any one file * @param count the number of files to use * @exception IOException if there are IO problems opening the files. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception IllegalArgumentException if limit < 0, or count < 1. * @exception IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern, int limit, int count) throws IOException, SecurityException { if (limit < 0 || count < 1 || pattern.length() < 1) { throw new IllegalArgumentException(); } checkAccess(); configure(); this.pattern = pattern; this.limit = limit; this.count = count; openFiles(); } /** {@collect.stats} * {@description.open} * Initialize a <tt>FileHandler</tt> to write to a set of files * with optional append. When (approximately) the given limit has * been written to one file, another file will be opened. The * output will cycle through a set of count files. * <p> * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given pattern * argument is used as the filename pattern, the file limit is * set to the limit argument, and the file count is set to the * given count argument, and the append mode is set to the given * <tt>append</tt> argument. * <p> * {@description.close} * {@property.open} * The count must be at least 1. * {@property.close} * * @param pattern the pattern for naming the output file * @param limit the maximum number of bytes to write to any one file * @param count the number of files to use * @param append specifies append mode * @exception IOException if there are IO problems opening the files. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception IllegalArgumentException if limit < 0, or count < 1. * @exception IllegalArgumentException if pattern is an empty string * */ public FileHandler(String pattern, int limit, int count, boolean append) throws IOException, SecurityException { if (limit < 0 || count < 1 || pattern.length() < 1) { throw new IllegalArgumentException(); } checkAccess(); configure(); this.pattern = pattern; this.limit = limit; this.count = count; this.append = append; openFiles(); } // Private method to open the set of output files, based on the // configured instance variables. private void openFiles() throws IOException { LogManager manager = LogManager.getLogManager(); manager.checkAccess(); if (count < 1) { throw new IllegalArgumentException("file count = " + count); } if (limit < 0) { limit = 0; } // We register our own ErrorManager during initialization // so we can record exceptions. InitializationErrorManager em = new InitializationErrorManager(); setErrorManager(em); // Create a lock file. This grants us exclusive access // to our set of output files, as long as we are alive. int unique = -1; for (;;) { unique++; if (unique > MAX_LOCKS) { throw new IOException("Couldn't get lock for " + pattern); } // Generate a lock file name from the "unique" int. lockFileName = generate(pattern, 0, unique).toString() + ".lck"; // Now try to lock that filename. // Because some systems (e.g. Solaris) can only do file locks // between processes (and not within a process), we first check // if we ourself already have the file locked. synchronized(locks) { if (locks.get(lockFileName) != null) { // We already own this lock, for a different FileHandler // object. Try again. continue; } FileChannel fc; try { lockStream = new FileOutputStream(lockFileName); fc = lockStream.getChannel(); } catch (IOException ix) { // We got an IOException while trying to open the file. // Try the next file. continue; } try { FileLock fl = fc.tryLock(); if (fl == null) { // We failed to get the lock. Try next file. continue; } // We got the lock OK. } catch (IOException ix) { // We got an IOException while trying to get the lock. // This normally indicates that locking is not supported // on the target directory. We have to proceed without // getting a lock. Drop through. } // We got the lock. Remember it. locks.put(lockFileName, lockFileName); break; } } files = new File[count]; for (int i = 0; i < count; i++) { files[i] = generate(pattern, i, unique); } // Create the initial log file. if (append) { open(files[0], true); } else { rotate(); } // Did we detect any exceptions during initialization? Exception ex = em.lastException; if (ex != null) { if (ex instanceof IOException) { throw (IOException) ex; } else if (ex instanceof SecurityException) { throw (SecurityException) ex; } else { throw new IOException("Exception: " + ex); } } // Install the normal default ErrorManager. setErrorManager(new ErrorManager()); } // Generate a filename from a pattern. private File generate(String pattern, int generation, int unique) throws IOException { File file = null; String word = ""; int ix = 0; boolean sawg = false; boolean sawu = false; while (ix < pattern.length()) { char ch = pattern.charAt(ix); ix++; char ch2 = 0; if (ix < pattern.length()) { ch2 = Character.toLowerCase(pattern.charAt(ix)); } if (ch == '/') { if (file == null) { file = new File(word); } else { file = new File(file, word); } word = ""; continue; } else if (ch == '%') { if (ch2 == 't') { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir == null) { tmpDir = System.getProperty("user.home"); } file = new File(tmpDir); ix++; word = ""; continue; } else if (ch2 == 'h') { file = new File(System.getProperty("user.home")); if (isSetUID()) { // Ok, we are in a set UID program. For safety's sake // we disallow attempts to open files relative to %h. throw new IOException("can't use %h in set UID program"); } ix++; word = ""; continue; } else if (ch2 == 'g') { word = word + generation; sawg = true; ix++; continue; } else if (ch2 == 'u') { word = word + unique; sawu = true; ix++; continue; } else if (ch2 == '%') { word = word + "%"; ix++; continue; } } word = word + ch; } if (count > 1 && !sawg) { word = word + "." + generation; } if (unique > 0 && !sawu) { word = word + "." + unique; } if (word.length() > 0) { if (file == null) { file = new File(word); } else { file = new File(file, word); } } return file; } // Rotate the set of output files private synchronized void rotate() { Level oldLevel = getLevel(); setLevel(Level.OFF); super.close(); for (int i = count-2; i >= 0; i--) { File f1 = files[i]; File f2 = files[i+1]; if (f1.exists()) { if (f2.exists()) { f2.delete(); } f1.renameTo(f2); } } try { open(files[0], false); } catch (IOException ix) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ix, ErrorManager.OPEN_FAILURE); } setLevel(oldLevel); } /** {@collect.stats} * {@description.open} * Format and publish a <tt>LogRecord</tt>. * {@description.close} * * @param record description of the log event. A null record is * silently ignored and is not published */ public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } super.publish(record); flush(); if (limit > 0 && meter.written >= limit) { // We performed access checks in the "init" method to make sure // we are only initialized from trusted code. So we assume // it is OK to write the target files, even if we are // currently being called from untrusted code. // So it is safe to raise privilege here. AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { rotate(); return null; } }); } } /** {@collect.stats} * {@description.open} * Close all the files. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public synchronized void close() throws SecurityException { super.close(); // Unlock any lock file. if (lockFileName == null) { return; } try { // Closing the lock file's FileOutputStream will close // the underlying channel and free any locks. lockStream.close(); } catch (Exception ex) { // Problems closing the stream. Punt. } synchronized(locks) { locks.remove(lockFileName); } new File(lockFileName).delete(); lockFileName = null; lockStream = null; } private static class InitializationErrorManager extends ErrorManager { Exception lastException; public void error(String msg, Exception ex, int code) { lastException = ex; } } // Private native method to check if we are in a set UID program. private static native boolean isSetUID(); }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.net.*; /** {@collect.stats} * {@description.open} * Simple network logging <tt>Handler</tt>. * <p> * <tt>LogRecords</tt> are published to a network stream connection. By default * the <tt>XMLFormatter</tt> class is used for formatting. * <p> * <b>Configuration:</b> * By default each <tt>SocketHandler</tt> is initialized using the following * <tt>LogManager</tt> configuration properties. If properties are not defined * (or have invalid values) then the specified default values are used. * <ul> * <li> java.util.logging.SocketHandler.level * specifies the default level for the <tt>Handler</tt> * (defaults to <tt>Level.ALL</tt>). * <li> java.util.logging.SocketHandler.filter * specifies the name of a <tt>Filter</tt> class to use * (defaults to no <tt>Filter</tt>). * <li> java.util.logging.SocketHandler.formatter * specifies the name of a <tt>Formatter</tt> class to use * (defaults to <tt>java.util.logging.XMLFormatter</tt>). * <li> java.util.logging.SocketHandler.encoding * the name of the character set encoding to use (defaults to * the default platform encoding). * <li> java.util.logging.SocketHandler.host * specifies the target host name to connect to (no default). * <li> java.util.logging.SocketHandler.port * specifies the target TCP port to use (no default). * </ul> * <p> * The output IO stream is buffered, but is flushed after each * <tt>LogRecord</tt> is written. * {@description.close} * * @since 1.4 */ public class SocketHandler extends StreamHandler { private Socket sock; private String host; private int port; private String portProperty; // Private method to configure a SocketHandler from LogManager // properties and/or default values as specified in the class // javadoc. private void configure() { LogManager manager = LogManager.getLogManager(); String cname = getClass().getName(); setLevel(manager.getLevelProperty(cname +".level", Level.ALL)); setFilter(manager.getFilterProperty(cname +".filter", null)); setFormatter(manager.getFormatterProperty(cname +".formatter", new XMLFormatter())); try { setEncoding(manager.getStringProperty(cname +".encoding", null)); } catch (Exception ex) { try { setEncoding(null); } catch (Exception ex2) { // doing a setEncoding with null should always work. // assert false; } } port = manager.getIntProperty(cname + ".port", 0); host = manager.getStringProperty(cname + ".host", null); } /** {@collect.stats} * {@description.open} * Create a <tt>SocketHandler</tt>, using only <tt>LogManager</tt> properties * (or their defaults). * {@description.close} * @throws IllegalArgumentException if the host or port are invalid or * are not specified as LogManager properties. * @throws IOException if we are unable to connect to the target * host and port. */ public SocketHandler() throws IOException { // We are going to use the logging defaults. sealed = false; configure(); try { connect(); } catch (IOException ix) { System.err.println("SocketHandler: connect failed to " + host + ":" + port); throw ix; } sealed = true; } /** {@collect.stats} * {@description.open} * Construct a <tt>SocketHandler</tt> using a specified host and port. * * The <tt>SocketHandler</tt> is configured based on <tt>LogManager</tt> * properties (or their default values) except that the given target host * and port arguments are used. If the host argument is empty, but not * null String then the localhost is used. * {@description.close} * * @param host target host. * @param port target port. * * @throws IllegalArgumentException if the host or port are invalid. * @throws IOException if we are unable to connect to the target * host and port. */ public SocketHandler(String host, int port) throws IOException { sealed = false; configure(); sealed = true; this.port = port; this.host = host; connect(); } private void connect() throws IOException { // Check the arguments are valid. if (port == 0) { throw new IllegalArgumentException("Bad port: " + port); } if (host == null) { throw new IllegalArgumentException("Null host name: " + host); } // Try to open a new socket. sock = new Socket(host, port); OutputStream out = sock.getOutputStream(); BufferedOutputStream bout = new BufferedOutputStream(out); setOutputStream(bout); } /** {@collect.stats} * {@description.open} * Close this output stream. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ public synchronized void close() throws SecurityException { super.close(); if (sock != null) { try { sock.close(); } catch (IOException ix) { // drop through. } } sock = null; } /** {@collect.stats} * {@description.open} * Format and publish a <tt>LogRecord</tt>. * {@description.close} * * @param record description of the log event. A null record is * silently ignored and is not published */ public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } super.publish(record); flush(); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; /** {@collect.stats} * {@description.open} * Stream based logging <tt>Handler</tt>. * <p> * This is primarily intended as a base class or support class to * be used in implementing other logging <tt>Handlers</tt>. * <p> * <tt>LogRecords</tt> are published to a given <tt>java.io.OutputStream</tt>. * <p> * <b>Configuration:</b> * By default each <tt>StreamHandler</tt> is initialized using the following * <tt>LogManager</tt> configuration properties. If properties are not defined * (or have invalid values) then the specified default values are used. * <ul> * <li> java.util.logging.StreamHandler.level * specifies the default level for the <tt>Handler</tt> * (defaults to <tt>Level.INFO</tt>). * <li> java.util.logging.StreamHandler.filter * specifies the name of a <tt>Filter</tt> class to use * (defaults to no <tt>Filter</tt>). * <li> java.util.logging.StreamHandler.formatter * specifies the name of a <tt>Formatter</tt> class to use * (defaults to <tt>java.util.logging.SimpleFormatter</tt>). * <li> java.util.logging.StreamHandler.encoding * the name of the character set encoding to use (defaults to * the default platform encoding). * </ul> * {@description.close} * * @since 1.4 */ public class StreamHandler extends Handler { private LogManager manager = LogManager.getLogManager(); private OutputStream output; private boolean doneHeader; private Writer writer; // Private method to configure a StreamHandler from LogManager // properties and/or default values as specified in the class // javadoc. private void configure() { LogManager manager = LogManager.getLogManager(); String cname = getClass().getName(); setLevel(manager.getLevelProperty(cname +".level", Level.INFO)); setFilter(manager.getFilterProperty(cname +".filter", null)); setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); try { setEncoding(manager.getStringProperty(cname +".encoding", null)); } catch (Exception ex) { try { setEncoding(null); } catch (Exception ex2) { // doing a setEncoding with null should always work. // assert false; } } } /** {@collect.stats} * {@description.open} * Create a <tt>StreamHandler</tt>, with no current output stream. * {@description.close} */ public StreamHandler() { sealed = false; configure(); sealed = true; } /** {@collect.stats} * {@description.open} * Create a <tt>StreamHandler</tt> with a given <tt>Formatter</tt> * and output stream. * <p> * {@description.close} * @param out the target output stream * @param formatter Formatter to be used to format output */ public StreamHandler(OutputStream out, Formatter formatter) { sealed = false; configure(); setFormatter(formatter); setOutputStream(out); sealed = true; } /** {@collect.stats} * {@description.open} * Change the output stream. * <P> * If there is a current output stream then the <tt>Formatter</tt>'s * tail string is written and the stream is flushed and closed. * Then the output stream is replaced with the new output stream. * {@description.close} * * @param out New output stream. May not be null. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. */ protected synchronized void setOutputStream(OutputStream out) throws SecurityException { if (out == null) { throw new NullPointerException(); } flushAndClose(); output = out; doneHeader = false; String encoding = getEncoding(); if (encoding == null) { writer = new OutputStreamWriter(output); } else { try { writer = new OutputStreamWriter(output, encoding); } catch (UnsupportedEncodingException ex) { // This shouldn't happen. The setEncoding method // should have validated that the encoding is OK. throw new Error("Unexpected exception " + ex); } } } /** {@collect.stats} * {@description.open} * Set (or change) the character encoding used by this <tt>Handler</tt>. * <p> * The encoding should be set before any <tt>LogRecords</tt> are written * to the <tt>Handler</tt>. * {@description.close} * * @param encoding The name of a supported character encoding. * May be null, to indicate the default platform encoding. * @exception SecurityException if a security manager exists and if * the caller does not have <tt>LoggingPermission("control")</tt>. * @exception UnsupportedEncodingException if the named encoding is * not supported. */ public void setEncoding(String encoding) throws SecurityException, java.io.UnsupportedEncodingException { super.setEncoding(encoding); if (output == null) { return; } // Replace the current writer with a writer for the new encoding. flush(); if (encoding == null) { writer = new OutputStreamWriter(output); } else { writer = new OutputStreamWriter(output, encoding); } } /** {@collect.stats} * {@description.open} * Format and publish a <tt>LogRecord</tt>. * <p> * The <tt>StreamHandler</tt> first checks if there is an <tt>OutputStream</tt> * and if the given <tt>LogRecord</tt> has at least the required log level. * If not it silently returns. If so, it calls any associated * <tt>Filter</tt> to check if the record should be published. If so, * it calls its <tt>Formatter</tt> to format the record and then writes * the result to the current output stream. * <p> * If this is the first <tt>LogRecord</tt> to be written to a given * <tt>OutputStream</tt>, the <tt>Formatter</tt>'s "head" string is * written to the stream before the <tt>LogRecord</tt> is written. * {@description.close} * * @param record description of the log event. A null record is * silently ignored and is not published */ public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } String msg; try { msg = getFormatter().format(record); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.FORMAT_FAILURE); return; } try { if (!doneHeader) { writer.write(getFormatter().getHead(this)); doneHeader = true; } writer.write(msg); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.WRITE_FAILURE); } } /** {@collect.stats} * {@description.open} * Check if this <tt>Handler</tt> would actually log a given <tt>LogRecord</tt>. * <p> * This method checks if the <tt>LogRecord</tt> has an appropriate level and * whether it satisfies any <tt>Filter</tt>. It will also return false if * no output stream has been assigned yet or the LogRecord is Null. * <p> * {@description.close} * @param record a <tt>LogRecord</tt> * @return true if the <tt>LogRecord</tt> would be logged. * */ public boolean isLoggable(LogRecord record) { if (writer == null || record == null) { return false; } return super.isLoggable(record); } /** {@collect.stats} * {@description.open} * Flush any buffered messages. * {@description.close} */ public synchronized void flush() { if (writer != null) { try { writer.flush(); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.FLUSH_FAILURE); } } } private synchronized void flushAndClose() throws SecurityException { checkAccess(); if (writer != null) { try { if (!doneHeader) { writer.write(getFormatter().getHead(this)); doneHeader = true; } writer.write(getFormatter().getTail(this)); writer.flush(); writer.close(); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.CLOSE_FAILURE); } writer = null; output = null; } } /** {@collect.stats} * {@description.open} * Close the current output stream. * <p> * The <tt>Formatter</tt>'s "tail" string is written to the stream before it * is closed. In addition, if the <tt>Formatter</tt>'s "head" string has not * yet been written to the stream, it will be written before the * "tail" string. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public synchronized void close() throws SecurityException { flushAndClose(); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; /** {@collect.stats} * {@description.open} * A Formatter provides support for formatting LogRecords. * <p> * Typically each logging Handler will have a Formatter associated * with it. The Formatter takes a LogRecord and converts it to * a string. * <p> * Some formatters (such as the XMLFormatter) need to wrap head * and tail strings around a set of formatted records. The getHeader * and getTail methods can be used to obtain these strings. * {@description.close} * * @since 1.4 */ public abstract class Formatter { /** {@collect.stats} * {@description.open} * Construct a new formatter. * {@description.close} */ protected Formatter() { } /** {@collect.stats} * {@description.open} * Format the given log record and return the formatted string. * <p> * The resulting formatted String will normally include a * localized and formated version of the LogRecord's message field. * It is recommended to use the {@link Formatter#formatMessage} * convenience method to localize and format the message field. * {@description.close} * * @param record the log record to be formatted. * @return the formatted log record */ public abstract String format(LogRecord record); /** {@collect.stats} * {@description.open} * Return the header string for a set of formatted records. * <p> * This base class returns an empty string, but this may be * overriden by subclasses. * {@description.close} * * @param h The target handler (can be null) * @return header string */ public String getHead(Handler h) { return ""; } /** {@collect.stats} * {@description.open} * Return the tail string for a set of formatted records. * <p> * This base class returns an empty string, but this may be * overriden by subclasses. * {@description.close} * * @param h The target handler (can be null) * @return tail string */ public String getTail(Handler h) { return ""; } /** {@collect.stats} * {@description.open} * Localize and format the message string from a log record. This * method is provided as a convenience for Formatter subclasses to * use when they are performing formatting. * <p> * The message string is first localized to a format string using * the record's ResourceBundle. (If there is no ResourceBundle, * or if the message key is not found, then the key is used as the * format string.) The format String uses java.text style * formatting. * <ul> * <li>If there are no parameters, no formatter is used. * <li>Otherwise, if the string contains "{0" then * java.text.MessageFormat is used to format the string. * <li>Otherwise no formatting is performed. * </ul> * <p> * {@description.close} * * @param record the log record containing the raw message * @return a localized and formatted message */ public synchronized String formatMessage(LogRecord record) { String format = record.getMessage(); java.util.ResourceBundle catalog = record.getResourceBundle(); if (catalog != null) { try { format = catalog.getString(record.getMessage()); } catch (java.util.MissingResourceException ex) { // Drop through. Use record message as format format = record.getMessage(); } } // Do the formatting. try { Object parameters[] = record.getParameters(); if (parameters == null || parameters.length == 0) { // No parameters. Just return format string. return format; } // Is it a java.text style format? // Ideally we could match with // Pattern.compile("\\{\\d").matcher(format).find()) // However the cost is 14% higher, so we cheaply check for // 1 of the first 4 parameters if (format.indexOf("{0") >= 0 || format.indexOf("{1") >=0 || format.indexOf("{2") >=0|| format.indexOf("{3") >=0) { return java.text.MessageFormat.format(format, parameters); } return format; } catch (Exception ex) { // Formatting failed: use localized format string. return format; } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.nio.charset.Charset; import java.util.*; /** {@collect.stats} * {@description.open} * Format a LogRecord into a standard XML format. * <p> * The DTD specification is provided as Appendix A to the * Java Logging APIs specification. * <p> * The XMLFormatter can be used with arbitrary character encodings, * but it is recommended that it normally be used with UTF-8. The * character encoding can be set on the output Handler. * {@description.close} * * @since 1.4 */ public class XMLFormatter extends Formatter { private LogManager manager = LogManager.getLogManager(); // Append a two digit number. private void a2(StringBuffer sb, int x) { if (x < 10) { sb.append('0'); } sb.append(x); } // Append the time and date in ISO 8601 format private void appendISO8601(StringBuffer sb, long millis) { Date date = new Date(millis); sb.append(date.getYear() + 1900); sb.append('-'); a2(sb, date.getMonth() + 1); sb.append('-'); a2(sb, date.getDate()); sb.append('T'); a2(sb, date.getHours()); sb.append(':'); a2(sb, date.getMinutes()); sb.append(':'); a2(sb, date.getSeconds()); } // Append to the given StringBuffer an escaped version of the // given text string where XML special characters have been escaped. // For a null string we append "<null>" private void escape(StringBuffer sb, String text) { if (text == null) { text = "<null>"; } for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '<') { sb.append("&lt;"); } else if (ch == '>') { sb.append("&gt;"); } else if (ch == '&') { sb.append("&amp;"); } else { sb.append(ch); } } } /** {@collect.stats} * {@description.open} * Format the given message to XML. * <p> * This method can be overridden in a subclass. * It is recommended to use the {@link Formatter#formatMessage} * convenience method to localize and format the message field. * {@description.close} * * @param record the log record to be formatted. * @return a formatted log record */ public String format(LogRecord record) { StringBuffer sb = new StringBuffer(500); sb.append("<record>\n"); sb.append(" <date>"); appendISO8601(sb, record.getMillis()); sb.append("</date>\n"); sb.append(" <millis>"); sb.append(record.getMillis()); sb.append("</millis>\n"); sb.append(" <sequence>"); sb.append(record.getSequenceNumber()); sb.append("</sequence>\n"); String name = record.getLoggerName(); if (name != null) { sb.append(" <logger>"); escape(sb, name); sb.append("</logger>\n"); } sb.append(" <level>"); escape(sb, record.getLevel().toString()); sb.append("</level>\n"); if (record.getSourceClassName() != null) { sb.append(" <class>"); escape(sb, record.getSourceClassName()); sb.append("</class>\n"); } if (record.getSourceMethodName() != null) { sb.append(" <method>"); escape(sb, record.getSourceMethodName()); sb.append("</method>\n"); } sb.append(" <thread>"); sb.append(record.getThreadID()); sb.append("</thread>\n"); if (record.getMessage() != null) { // Format the message string and its accompanying parameters. String message = formatMessage(record); sb.append(" <message>"); escape(sb, message); sb.append("</message>"); sb.append("\n"); } // If the message is being localized, output the key, resource // bundle name, and params. ResourceBundle bundle = record.getResourceBundle(); try { if (bundle != null && bundle.getString(record.getMessage()) != null) { sb.append(" <key>"); escape(sb, record.getMessage()); sb.append("</key>\n"); sb.append(" <catalog>"); escape(sb, record.getResourceBundleName()); sb.append("</catalog>\n"); } } catch (Exception ex) { // The message is not in the catalog. Drop through. } Object parameters[] = record.getParameters(); // Check to see if the parameter was not a messagetext format // or was not null or empty if ( parameters != null && parameters.length != 0 && record.getMessage().indexOf("{") == -1 ) { for (int i = 0; i < parameters.length; i++) { sb.append(" <param>"); try { escape(sb, parameters[i].toString()); } catch (Exception ex) { sb.append("???"); } sb.append("</param>\n"); } } if (record.getThrown() != null) { // Report on the state of the throwable. Throwable th = record.getThrown(); sb.append(" <exception>\n"); sb.append(" <message>"); escape(sb, th.toString()); sb.append("</message>\n"); StackTraceElement trace[] = th.getStackTrace(); for (int i = 0; i < trace.length; i++) { StackTraceElement frame = trace[i]; sb.append(" <frame>\n"); sb.append(" <class>"); escape(sb, frame.getClassName()); sb.append("</class>\n"); sb.append(" <method>"); escape(sb, frame.getMethodName()); sb.append("</method>\n"); // Check for a line number. if (frame.getLineNumber() >= 0) { sb.append(" <line>"); sb.append(frame.getLineNumber()); sb.append("</line>\n"); } sb.append(" </frame>\n"); } sb.append(" </exception>\n"); } sb.append("</record>\n"); return sb.toString(); } /** {@collect.stats} * {@description.open} * Return the header string for a set of XML formatted records. * {@description.close} * * @param h The target handler (can be null) * @return a valid XML string */ public String getHead(Handler h) { StringBuffer sb = new StringBuffer(); String encoding; sb.append("<?xml version=\"1.0\""); if (h != null) { encoding = h.getEncoding(); } else { encoding = null; } if (encoding == null) { // Figure out the default encoding. encoding = java.nio.charset.Charset.defaultCharset().name(); } // Try to map the encoding name to a canonical name. try { Charset cs = Charset.forName(encoding); encoding = cs.name(); } catch (Exception ex) { // We hit problems finding a canonical name. // Just use the raw encoding name. } sb.append(" encoding=\""); sb.append(encoding); sb.append("\""); sb.append(" standalone=\"no\"?>\n"); sb.append("<!DOCTYPE log SYSTEM \"logger.dtd\">\n"); sb.append("<log>\n"); return sb.toString(); } /** {@collect.stats} * {@description.open} * Return the tail string for a set of XML formatted records. * {@description.close} * * @param h The target handler (can be null) * @return a valid XML string */ public String getTail(Handler h) { return "</log>\n"; } }
Java
/* * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.util.*; import java.security.*; import java.lang.ref.WeakReference; /** {@collect.stats} * {@description.open} * A Logger object is used to log messages for a specific * system or application component. Loggers are normally named, * using a hierarchical dot-separated namespace. Logger names * can be arbitrary strings, but they should normally be based on * the package name or class name of the logged component, such * as java.net or javax.swing. In addition it is possible to create * "anonymous" Loggers that are not stored in the Logger namespace. * <p> * Logger objects may be obtained by calls on one of the getLogger * factory methods. These will either create a new Logger or * return a suitable existing Logger. It is important to note that * the Logger returned by one of the {@code getLogger} factory methods * may be garbage collected at any time if a strong reference to the * Logger is not kept. * <p> * Logging messages will be forwarded to registered Handler * objects, which can forward the messages to a variety of * destinations, including consoles, files, OS logs, etc. * <p> * Each Logger keeps track of a "parent" Logger, which is its * nearest existing ancestor in the Logger namespace. * <p> * Each Logger has a "Level" associated with it. This reflects * a minimum Level that this logger cares about. If a Logger's * level is set to <tt>null</tt>, then its effective level is inherited * from its parent, which may in turn obtain it recursively from its * parent, and so on up the tree. * <p> * The log level can be configured based on the properties from the * logging configuration file, as described in the description * of the LogManager class. However it may also be dynamically changed * by calls on the Logger.setLevel method. If a logger's level is * changed the change may also affect child loggers, since any child * logger that has <tt>null</tt> as its level will inherit its * effective level from its parent. * <p> * On each logging call the Logger initially performs a cheap * check of the request level (e.g. SEVERE or FINE) against the * effective log level of the logger. If the request level is * lower than the log level, the logging call returns immediately. * <p> * After passing this initial (cheap) test, the Logger will allocate * a LogRecord to describe the logging message. It will then call a * Filter (if present) to do a more detailed check on whether the * record should be published. If that passes it will then publish * the LogRecord to its output Handlers. By default, loggers also * publish to their parent's Handlers, recursively up the tree. * <p> * Each Logger may have a ResourceBundle name associated with it. * The named bundle will be used for localizing logging messages. * If a Logger does not have its own ResourceBundle name, then * it will inherit the ResourceBundle name from its parent, * recursively up the tree. * <p> * Most of the logger output methods take a "msg" argument. This * msg argument may be either a raw value or a localization key. * During formatting, if the logger has (or inherits) a localization * ResourceBundle and if the ResourceBundle has a mapping for the msg * string, then the msg string is replaced by the localized value. * Otherwise the original msg string is used. Typically, formatters use * java.text.MessageFormat style formatting to format parameters, so * for example a format string "{0} {1}" would format two parameters * as strings. * <p> * When mapping ResourceBundle names to ResourceBundles, the Logger * will first try to use the Thread's ContextClassLoader. If that * is null it will try the SystemClassLoader instead. As a temporary * transition feature in the initial implementation, if the Logger is * unable to locate a ResourceBundle from the ContextClassLoader or * SystemClassLoader the Logger will also search up the class stack * and use successive calling ClassLoaders to try to locate a ResourceBundle. * (This call stack search is to allow containers to transition to * using ContextClassLoaders and is likely to be removed in future * versions.) * <p> * Formatting (including localization) is the responsibility of * the output Handler, which will typically call a Formatter. * <p> * Note that formatting need not occur synchronously. It may be delayed * until a LogRecord is actually written to an external sink. * <p> * The logging methods are grouped in five main categories: * <ul> * <li><p> * There are a set of "log" methods that take a log level, a message * string, and optionally some parameters to the message string. * <li><p> * There are a set of "logp" methods (for "log precise") that are * like the "log" methods, but also take an explicit source class name * and method name. * <li><p> * There are a set of "logrb" method (for "log with resource bundle") * that are like the "logp" method, but also take an explicit resource * bundle name for use in localizing the log message. * <li><p> * There are convenience methods for tracing method entries (the * "entering" methods), method returns (the "exiting" methods) and * throwing exceptions (the "throwing" methods). * <li><p> * Finally, there are a set of convenience methods for use in the * very simplest cases, when a developer simply wants to log a * simple string at a given log level. These methods are named * after the standard Level names ("severe", "warning", "info", etc.) * and take a single argument, a message string. * </ul> * <p> * For the methods that do not take an explicit source name and * method name, the Logging framework will make a "best effort" * to determine which class and method called into the logging method. * However, it is important to realize that this automatically inferred * information may only be approximate (or may even be quite wrong!). * Virtual machines are allowed to do extensive optimizations when * JITing and may entirely remove stack frames, making it impossible * to reliably locate the calling class and method. * <P> * All methods on Logger are multi-thread safe. * <p> * <b>Subclassing Information:</b> Note that a LogManager class may * provide its own implementation of named Loggers for any point in * the namespace. Therefore, any subclasses of Logger (unless they * are implemented in conjunction with a new LogManager class) should * take care to obtain a Logger instance from the LogManager class and * should delegate operations such as "isLoggable" and "log(LogRecord)" * to that instance. Note that in order to intercept all logging * output, subclasses need only override the log(LogRecord) method. * All the other logging methods are implemented as calls on this * log(LogRecord) method. * {@description.close} * * @since 1.4 */ public class Logger { private static final Handler emptyHandlers[] = new Handler[0]; private static final int offValue = Level.OFF.intValue(); private LogManager manager; private String name; private ArrayList<Handler> handlers; private String resourceBundleName; private boolean useParentHandlers = true; private Filter filter; private boolean anonymous; private ResourceBundle catalog; // Cached resource bundle private String catalogName; // name associated with catalog private Locale catalogLocale; // locale associated with catalog // The fields relating to parent-child relationships and levels // are managed under a separate lock, the treeLock. private static Object treeLock = new Object(); // We keep weak references from parents to children, but strong // references from children to parents. private Logger parent; // our nearest parent. private ArrayList<LogManager.LoggerWeakRef> kids; // WeakReferences to loggers that have us as parent private Level levelObject; private volatile int levelValue; // current effective level value /** {@collect.stats} * {@description.open} * GLOBAL_LOGGER_NAME is a name for the global logger. * This name is provided as a convenience to developers who are making * casual use of the Logging package. Developers who are making serious * use of the logging package (for example in products) should create * and use their own Logger objects, with appropriate names, so that * logging can be controlled on a suitable per-Logger granularity. * Developers also need to keep a strong reference to their Logger * objects to prevent them from being garbage collected. * <p> * The preferred way to get the global logger object is via the call * <code>Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)</code>. * {@description.close} * @since 1.6 */ public static final String GLOBAL_LOGGER_NAME = "global"; /** {@collect.stats} * {@description.open} * The "global" Logger object is provided as a convenience to developers * who are making casual use of the Logging package. Developers * who are making serious use of the logging package (for example * in products) should create and use their own Logger objects, * with appropriate names, so that logging can be controlled on a * suitable per-Logger granularity. Developers also need to keep a * strong reference to their Logger objects to prevent them from * being garbage collected. * <p> * {@description.close} * @deprecated Initialization of this field is prone to deadlocks. * The field must be initialized by the Logger class initialization * which may cause deadlocks with the LogManager class initialization. * In such cases two class initialization wait for each other to complete. * As of JDK version 1.6, the preferred way to get the global logger object * is via the call <code>Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)</code>. */ @Deprecated public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); /** {@collect.stats} * {@description.open} * Protected method to construct a logger for a named subsystem. * <p> * The logger will be initially configured with a null Level * and with useParentHandlers true. * {@description.close} * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing. It may be null for anonymous Loggers. * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. * @throws MissingResourceException if the ResourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { this.manager = LogManager.getLogManager(); if (resourceBundleName != null) { // Note: we may get a MissingResourceException here. setupResourceInfo(resourceBundleName); } this.name = name; levelValue = Level.INFO.intValue(); } // This constructor is used only to create the global Logger. // It is needed to break a cyclic dependence between the LogManager // and Logger static initializers causing deadlocks. private Logger(String name) { // The manager field is not initialized here. this.name = name; levelValue = Level.INFO.intValue(); } // It is called from the LogManager.<clinit> to complete // initialization of the global Logger. void setLogManager(LogManager manager) { this.manager = manager; } private void checkAccess() throws SecurityException { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } manager.checkAccess(); } } /** {@collect.stats} * {@description.open} * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * <p> * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured * to also send logging output to its parent's handlers. It will * be registered in the LogManager global namespace. * <p> * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger").log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * {@description.close} * * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @return a suitable Logger * @throws NullPointerException if the name is null. */ public static synchronized Logger getLogger(String name) { LogManager manager = LogManager.getLogManager(); return manager.demandLogger(name); } /** {@collect.stats} * {@description.open} * Find or create a logger for a named subsystem. If a logger has * already been created with the given name it is returned. Otherwise * a new logger is created. * <p> * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging * output to its parent loggers Handlers. It will be registered in * the LogManager global namespace. * <p> * Note: The LogManager may only retain a weak reference to the newly * created Logger. It is important to understand that a previously * created Logger with the given name may be garbage collected at any * time if there is no strong reference to the Logger. In particular, * this means that two back-to-back calls like * {@code getLogger("MyLogger", ...).log(...)} may use different Logger * objects named "MyLogger" if there is no strong reference to the * Logger named "MyLogger" elsewhere in the program. * <p> * If the named Logger already exists and does not yet have a * localization resource bundle then the given resource bundle * name is used. If the named Logger already exists and has * a different resource bundle name then an IllegalArgumentException * is thrown. * <p> * {@description.close} * @param name A name for the logger. This should * be a dot-separated name and should normally * be based on the package name or class name * of the subsystem, such as java.net * or javax.swing * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be <CODE>null</CODE> if none of * the messages require localization. * @return a suitable Logger * @throws MissingResourceException if the named ResourceBundle cannot be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. */ public static synchronized Logger getLogger(String name, String resourceBundleName) { LogManager manager = LogManager.getLogManager(); Logger result = manager.demandLogger(name); if (result.resourceBundleName == null) { // Note: we may get a MissingResourceException here. result.setupResourceInfo(resourceBundleName); } else if (!result.resourceBundleName.equals(resourceBundleName)) { throw new IllegalArgumentException(result.resourceBundleName + " != " + resourceBundleName); } return result; } /** {@collect.stats} * {@description.open} * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * <p> * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * <p> * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * <p> * {@description.close} * * @return a newly created private Logger */ public static Logger getAnonymousLogger() { return getAnonymousLogger(null); } /** {@collect.stats} * {@description.open} * Create an anonymous Logger. The newly created Logger is not * registered in the LogManager namespace. There will be no * access checks on updates to the logger. * <p> * This factory method is primarily intended for use from applets. * Because the resulting Logger is anonymous it can be kept private * by the creating class. This removes the need for normal security * checks, which in turn allows untrusted applet code to update * the control state of the Logger. For example an applet can do * a setLevel or an addHandler on an anonymous Logger. * <p> * Even although the new logger is anonymous, it is configured * to have the root logger ("") as its parent. This means that * by default it inherits its effective level and handlers * from the root logger. * <p> * {@description.close} * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger * @throws MissingResourceException if the named ResourceBundle cannot be found. */ public static synchronized Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); // cleanup some Loggers that have been GC'ed manager.drainLoggerRefQueueBounded(); Logger result = new Logger(null, resourceBundleName); result.anonymous = true; Logger root = manager.getLogger(""); result.doSetParent(root); return result; } /** {@collect.stats} * {@description.open} * Retrieve the localization resource bundle for this * logger for the current default locale. Note that if * the result is null, then the Logger will use a resource * bundle inherited from its parent. * {@description.close} * * @return localization bundle (may be null) */ public ResourceBundle getResourceBundle() { return findResourceBundle(getResourceBundleName()); } /** {@collect.stats} * {@description.open} * Retrieve the localization resource bundle name for this * logger. Note that if the result is null, then the Logger * will use a resource bundle name inherited from its parent. * {@description.close} * * @return localization bundle name (may be null) */ public String getResourceBundleName() { return resourceBundleName; } /** {@collect.stats} * {@description.open} * Set a filter to control output on this Logger. * <P> * After passing the initial "level" check, the Logger will * call this Filter to check if a log record should really * be published. * {@description.close} * * @param newFilter a filter object (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public synchronized void setFilter(Filter newFilter) throws SecurityException { checkAccess(); filter = newFilter; } /** {@collect.stats} * {@description.open} * Get the current filter for this Logger. * {@description.close} * * @return a filter object (may be null) */ public synchronized Filter getFilter() { return filter; } /** {@collect.stats} * {@description.open} * Log a LogRecord. * <p> * All the other logging methods in this class call through * this method to actually perform any logging. Subclasses can * override this single method to capture all log activity. * {@description.close} * * @param record the LogRecord to be published */ public void log(LogRecord record) { if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } synchronized (this) { if (filter != null && !filter.isLoggable(record)) { return; } } // Post the LogRecord to all our Handlers, and then to // our parents' handlers, all the way up the tree. Logger logger = this; while (logger != null) { Handler targets[] = logger.getHandlers(); if (targets != null) { for (int i = 0; i < targets.length; i++) { targets[i].publish(record); } } if (!logger.getUseParentHandlers()) { break; } logger = logger.getParent(); } } // private support method for logging. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr) { lr.setLoggerName(name); String ebname = getEffectiveResourceBundleName(); if (ebname != null) { lr.setResourceBundleName(ebname); lr.setResourceBundle(findResourceBundle(ebname)); } log(lr); } //================================================================ // Start of convenience methods WITHOUT className and methodName //================================================================ /** {@collect.stats} * {@description.open} * Log a message, with no arguments. * <p> * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, with one object parameter. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ public void log(Level level, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, with an array of object arguments. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void log(Level level, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setParameters(params); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, with associated Throwable information. * <p> * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * <p> * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void log(Level level, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setThrown(thrown); doLog(lr); } //================================================================ // Start of convenience methods WITH className and methodName //================================================================ /** {@collect.stats} * {@description.open} * Log a message, specifying source class and method, * with no arguments. * <p> * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) */ public void logp(Level level, String sourceClass, String sourceMethod, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class and method, * with a single object parameter to the log message. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class and method, * with an array of object arguments. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class and method, * with associated Throwable information. * <p> * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * <p> * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //========================================================================= // Start of convenience methods WITH className, methodName and bundle name. //========================================================================= // Private support method for logging for "logrb" methods. // We fill in the logger name, resource bundle name, and // resource bundle and then call "void log(LogRecord)". private void doLog(LogRecord lr, String rbname) { lr.setLoggerName(name); if (rbname != null) { lr.setResourceBundleName(rbname); lr.setResourceBundle(findResourceBundle(rbname)); } log(lr); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class, method, and resource bundle name * with no arguments. * <p> * If the logger is currently enabled for the given message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); doLog(lr, bundleName); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class, method, and resource bundle name, * with a single object parameter to the log message. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param param1 Parameter to the log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); Object params[] = { param1 }; lr.setParameters(params); doLog(lr, bundleName); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class, method, and resource bundle name, * with an array of object arguments. * <p> * If the logger is currently enabled for the given message * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. * <p> * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null. * @param msg The string message (or a key in the message catalog) * @param params Array of parameters to the message */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object params[]) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setParameters(params); doLog(lr, bundleName); } /** {@collect.stats} * {@description.open} * Log a message, specifying source class, method, and resource bundle name, * with associated Throwable information. * <p> * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. * <p> * The msg string is localized using the named resource bundle. If the * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. * <p> * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * <p> * {@description.close} * @param level One of the message level identifiers, e.g. SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, * can be null * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { if (level.intValue() < levelValue || levelValue == offValue) { return; } LogRecord lr = new LogRecord(level, msg); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr, bundleName); } //====================================================================== // Start of convenience methods for logging method entries and returns. //====================================================================== /** {@collect.stats} * {@description.open} * Log a method entry. * <p> * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY", log level * FINER, and the given sourceMethod and sourceClass is logged. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered */ public void entering(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); } /** {@collect.stats} * {@description.open} * Log a method entry, with one parameter. * <p> * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY {0}", log level * FINER, and the given sourceMethod, sourceClass, and parameter * is logged. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param param1 parameter to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object param1) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { param1 }; logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); } /** {@collect.stats} * {@description.open} * Log a method entry, with an array of parameters. * <p> * This is a convenience method that can be used to log entry * to a method. A LogRecord with message "ENTRY" (followed by a * format {N} indicator for each entry in the parameter array), * log level FINER, and the given sourceMethod, sourceClass, and * parameters is logged. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that is being entered * @param params array of parameters to the method being entered */ public void entering(String sourceClass, String sourceMethod, Object params[]) { if (Level.FINER.intValue() < levelValue) { return; } String msg = "ENTRY"; if (params == null ) { logp(Level.FINER, sourceClass, sourceMethod, msg); return; } for (int i = 0; i < params.length; i++) { msg = msg + " {" + i + "}"; } logp(Level.FINER, sourceClass, sourceMethod, msg, params); } /** {@collect.stats} * {@description.open} * Log a method return. * <p> * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN", log level * FINER, and the given sourceMethod and sourceClass is logged. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method */ public void exiting(String sourceClass, String sourceMethod) { if (Level.FINER.intValue() < levelValue) { return; } logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); } /** {@collect.stats} * {@description.open} * Log a method return, with result object. * <p> * This is a convenience method that can be used to log returning * from a method. A LogRecord with message "RETURN {0}", log level * FINER, and the gives sourceMethod, sourceClass, and result * object is logged. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method * @param result Object that is being returned */ public void exiting(String sourceClass, String sourceMethod, Object result) { if (Level.FINER.intValue() < levelValue) { return; } Object params[] = { result }; logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); } /** {@collect.stats} * {@description.open} * Log throwing an exception. * <p> * This is a convenience method to log that a method is * terminating by throwing an exception. The logging is done * using the FINER level. * <p> * If the logger is currently enabled for the given message * level then the given arguments are stored in a LogRecord * which is forwarded to all registered output handlers. The * LogRecord's message is set to "THROW". * <p> * Note that the thrown argument is stored in the LogRecord thrown * property, rather than the LogRecord parameters property. Thus is it * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. * <p> * {@description.close} * @param sourceClass name of class that issued the logging request * @param sourceMethod name of the method. * @param thrown The Throwable that is being thrown. */ public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { return; } LogRecord lr = new LogRecord(Level.FINER, "THROW"); lr.setSourceClassName(sourceClass); lr.setSourceMethodName(sourceMethod); lr.setThrown(thrown); doLog(lr); } //======================================================================= // Start of simple convenience methods using level names as method names //======================================================================= /** {@collect.stats} * {@description.open} * Log a SEVERE message. * <p> * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void severe(String msg) { if (Level.SEVERE.intValue() < levelValue) { return; } log(Level.SEVERE, msg); } /** {@collect.stats} * {@description.open} * Log a WARNING message. * <p> * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void warning(String msg) { if (Level.WARNING.intValue() < levelValue) { return; } log(Level.WARNING, msg); } /** {@collect.stats} * {@description.open} * Log an INFO message. * <p> * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void info(String msg) { if (Level.INFO.intValue() < levelValue) { return; } log(Level.INFO, msg); } /** {@collect.stats} * {@description.open} * Log a CONFIG message. * <p> * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void config(String msg) { if (Level.CONFIG.intValue() < levelValue) { return; } log(Level.CONFIG, msg); } /** {@collect.stats} * {@description.open} * Log a FINE message. * <p> * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void fine(String msg) { if (Level.FINE.intValue() < levelValue) { return; } log(Level.FINE, msg); } /** {@collect.stats} * {@description.open} * Log a FINER message. * <p> * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void finer(String msg) { if (Level.FINER.intValue() < levelValue) { return; } log(Level.FINER, msg); } /** {@collect.stats} * {@description.open} * Log a FINEST message. * <p> * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * <p> * {@description.close} * @param msg The string message (or a key in the message catalog) */ public void finest(String msg) { if (Level.FINEST.intValue() < levelValue) { return; } log(Level.FINEST, msg); } //================================================================ // End of convenience methods //================================================================ /** {@collect.stats} * {@description.open} * Set the log level specifying which message levels will be * logged by this logger. Message levels lower than this * value will be discarded. The level value Level.OFF * can be used to turn off logging. * <p> * If the new level is null, it means that this node should * inherit its level from its nearest ancestor with a specific * (non-null) level value. * {@description.close} * * @param newLevel the new value for the log level (may be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setLevel(Level newLevel) throws SecurityException { checkAccess(); synchronized (treeLock) { levelObject = newLevel; updateEffectiveLevel(); } } /** {@collect.stats} * {@description.open} * Get the log Level that has been specified for this Logger. * The result may be null, which means that this logger's * effective level will be inherited from its parent. * {@description.close} * * @return this Logger's level */ public Level getLevel() { return levelObject; } /** {@collect.stats} * {@description.open} * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * {@description.close} * * @param level a message logging level * @return true if the given message level is currently being logged. */ public boolean isLoggable(Level level) { if (level.intValue() < levelValue || levelValue == offValue) { return false; } return true; } /** {@collect.stats} * {@description.open} * Get the name for this logger. * {@description.close} * @return logger name. Will be null for anonymous Loggers. */ public String getName() { return name; } /** {@collect.stats} * {@description.open} * Add a log Handler to receive logging messages. * <p> * By default, Loggers also send their output to their parent logger. * Typically the root Logger is configured with a set of Handlers * that essentially act as default handlers for all loggers. * {@description.close} * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public synchronized void addHandler(Handler handler) throws SecurityException { // Check for null handler handler.getClass(); checkAccess(); if (handlers == null) { handlers = new ArrayList<Handler>(); } handlers.add(handler); } /** {@collect.stats} * {@description.open} * Remove a log Handler. * <P> * Returns silently if the given Handler is not found or is null * {@description.close} * * @param handler a logging Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public synchronized void removeHandler(Handler handler) throws SecurityException { checkAccess(); if (handler == null) { return; } if (handlers == null) { return; } handlers.remove(handler); } /** {@collect.stats} * {@description.open} * Get the Handlers associated with this logger. * <p> * {@description.close} * @return an array of all registered Handlers */ public synchronized Handler[] getHandlers() { if (handlers == null) { return emptyHandlers; } return handlers.toArray(new Handler[handlers.size()]); } /** {@collect.stats} * {@description.open} * Specify whether or not this logger should send its output * to it's parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * {@description.close} * * @param useParentHandlers true if output is to be sent to the * logger's parent. * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public synchronized void setUseParentHandlers(boolean useParentHandlers) { checkAccess(); this.useParentHandlers = useParentHandlers; } /** {@collect.stats} * {@description.open} * Discover whether or not this logger is sending its output * to its parent logger. * {@description.close} * * @return true if output is to be sent to the logger's parent */ public synchronized boolean getUseParentHandlers() { return useParentHandlers; } // Private utility method to map a resource bundle name to an // actual resource bundle, using a simple one-entry cache. // Returns null for a null name. // May also return null if we can't find the resource bundle and // there is no suitable previous cached value. private synchronized ResourceBundle findResourceBundle(String name) { // Return a null bundle for a null name. if (name == null) { return null; } Locale currentLocale = Locale.getDefault(); // Normally we should hit on our simple one entry cache. if (catalog != null && currentLocale == catalogLocale && name == catalogName) { return catalog; } // Use the thread's context ClassLoader. If there isn't one, // use the SystemClassloader. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // Woops. We can't find the ResourceBundle in the default // ClassLoader. Drop through. } // Fall back to searching up the call stack and trying each // calling ClassLoader. for (int ix = 0; ; ix++) { Class clz = sun.reflect.Reflection.getCallerClass(ix); if (clz == null) { break; } ClassLoader cl2 = clz.getClassLoader(); if (cl2 == null) { cl2 = ClassLoader.getSystemClassLoader(); } if (cl == cl2) { // We've already checked this classloader. continue; } cl = cl2; try { catalog = ResourceBundle.getBundle(name, currentLocale, cl); catalogName = name; catalogLocale = currentLocale; return catalog; } catch (MissingResourceException ex) { // Ok, this one didn't work either. // Drop through, and try the next one. } } if (name.equals(catalogName)) { // Return the previous cached value for that name. // This may be null. return catalog; } // Sorry, we're out of luck. return null; } // Private utility method to initialize our one entry // resource bundle cache. // Note: for consistency reasons, we are careful to check // that a suitable ResourceBundle exists before setting the // ResourceBundleName. private synchronized void setupResourceInfo(String name) { if (name == null) { return; } ResourceBundle rb = findResourceBundle(name); if (rb == null) { // We've failed to find an expected ResourceBundle. throw new MissingResourceException("Can't find " + name + " bundle", name, ""); } resourceBundleName = name; } /** {@collect.stats} * {@description.open} * Return the parent for this Logger. * <p> * This method returns the nearest extant parent in the namespace. * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" * has been created but no logger "a.b.c" exists, then a call of * getParent on the Logger "a.b.c.d" will return the Logger "a.b". * <p> * The result will be null if it is called on the root Logger * in the namespace. * {@description.close} * * @return nearest existing parent Logger */ public Logger getParent() { synchronized (treeLock) { return parent; } } /** {@collect.stats} * {@description.open} * Set the parent for this Logger. This method is used by * the LogManager to update a Logger when the namespace changes. * <p> * It should not be called from application code. * <p> * {@description.close} * @param parent the new parent logger * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void setParent(Logger parent) { if (parent == null) { throw new NullPointerException(); } manager.checkAccess(); doSetParent(parent); } // Private method to do the work for parenting a child // Logger onto a parent logger. private void doSetParent(Logger newParent) { // System.err.println("doSetParent \"" + getName() + "\" \"" // + newParent.getName() + "\""); synchronized (treeLock) { // Remove ourself from any previous parent. LogManager.LoggerWeakRef ref = null; if (parent != null) { // assert parent.kids != null; for (Iterator<LogManager.LoggerWeakRef> iter = parent.kids.iterator(); iter.hasNext(); ) { ref = iter.next(); Logger kid = ref.get(); if (kid == this) { // ref is used down below to complete the reparenting iter.remove(); break; } else { ref = null; } } // We have now removed ourself from our parents' kids. } // Set our new parent. parent = newParent; if (parent.kids == null) { parent.kids = new ArrayList<LogManager.LoggerWeakRef>(2); } if (ref == null) { // we didn't have a previous parent ref = manager.new LoggerWeakRef(this); } ref.setParentRef(new WeakReference<Logger>(parent)); parent.kids.add(ref); // As a result of the reparenting, the effective level // may have changed for us and our children. updateEffectiveLevel(); } } // Package-level method. // Remove the weak reference for the specified child Logger from the // kid list. We should only be called from LoggerWeakRef.dispose(). final void removeChildLogger(LogManager.LoggerWeakRef child) { synchronized (treeLock) { for (Iterator<LogManager.LoggerWeakRef> iter = kids.iterator(); iter.hasNext(); ) { LogManager.LoggerWeakRef ref = iter.next(); if (ref == child) { iter.remove(); return; } } } } // Recalculate the effective level for this node and // recursively for our children. private void updateEffectiveLevel() { // assert Thread.holdsLock(treeLock); // Figure out our current effective level. int newLevelValue; if (levelObject != null) { newLevelValue = levelObject.intValue(); } else { if (parent != null) { newLevelValue = parent.levelValue; } else { // This may happen during initialization. newLevelValue = Level.INFO.intValue(); } } // If our effective value hasn't changed, we're done. if (levelValue == newLevelValue) { return; } levelValue = newLevelValue; // System.err.println("effective level: \"" + getName() + "\" := " + level); // Recursively update the level on each of our kids. if (kids != null) { for (int i = 0; i < kids.size(); i++) { LogManager.LoggerWeakRef ref = kids.get(i); Logger kid = ref.get(); if (kid != null) { kid.updateEffectiveLevel(); } } } } // Private method to get the potentially inherited // resource bundle name for this Logger. // May return null private String getEffectiveResourceBundleName() { Logger target = this; while (target != null) { String rbn = target.getResourceBundleName(); if (rbn != null) { return rbn; } target = target.getParent(); } return null; } }
Java
/* * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.util.*; import java.security.*; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.URL; import sun.security.action.GetPropertyAction; /** {@collect.stats} * {@description.open} * There is a single global LogManager object that is used to * maintain a set of shared state about Loggers and log services. * <p> * This LogManager object: * <ul> * <li> Manages a hierarchical namespace of Logger objects. All * named Loggers are stored in this namespace. * <li> Manages a set of logging control properties. These are * simple key-value pairs that can be used by Handlers and * other logging objects to configure themselves. * </ul> * <p> * The global LogManager object can be retrieved using LogManager.getLogManager(). * The LogManager object is created during class initialization and * cannot subsequently be changed. * <p> * At startup the LogManager class is located using the * java.util.logging.manager system property. * <p> * By default, the LogManager reads its initial configuration from * a properties file "lib/logging.properties" in the JRE directory. * If you edit that property file you can change the default logging * configuration for all uses of that JRE. * <p> * In addition, the LogManager uses two optional system properties that * allow more control over reading the initial configuration: * <ul> * <li>"java.util.logging.config.class" * <li>"java.util.logging.config.file" * </ul> * These two properties may be set via the Preferences API, or as * command line property definitions to the "java" command, or as * system property definitions passed to JNI_CreateJavaVM. * <p> * If the "java.util.logging.config.class" property is set, then the * property value is treated as a class name. The given class will be * loaded, an object will be instantiated, and that object's constructor * is responsible for reading in the initial configuration. (That object * may use other system properties to control its configuration.) The * alternate configuration class can use <tt>readConfiguration(InputStream)</tt> * to define properties in the LogManager. * <p> * If "java.util.logging.config.class" property is <b>not</b> set, * then the "java.util.logging.config.file" system property can be used * to specify a properties file (in java.util.Properties format). The * initial logging configuration will be read from this file. * <p> * If neither of these properties is defined then, as described * above, the LogManager will read its initial configuration from * a properties file "lib/logging.properties" in the JRE directory. * <p> * The properties for loggers and Handlers will have names starting * with the dot-separated name for the handler or logger. * <p> * The global logging properties may include: * <ul> * <li>A property "handlers". This defines a whitespace or comma separated * list of class names for handler classes to load and register as * handlers on the root Logger (the Logger named ""). Each class * name must be for a Handler class which has a default constructor. * Note that these Handlers may be created lazily, when they are * first used. * * <li>A property "&lt;logger&gt;.handlers". This defines a whitespace or * comma separated list of class names for handlers classes to * load and register as handlers to the specified logger. Each class * name must be for a Handler class which has a default constructor. * Note that these Handlers may be created lazily, when they are * first used. * * <li>A property "&lt;logger&gt;.useParentHandlers". This defines a boolean * value. By default every logger calls its parent in addition to * handling the logging message itself, this often result in messages * being handled by the root logger as well. When setting this property * to false a Handler needs to be configured for this logger otherwise * no logging messages are delivered. * * <li>A property "config". This property is intended to allow * arbitrary configuration code to be run. The property defines a * whitespace or comma separated list of class names. A new instance will be * created for each named class. The default constructor of each class * may execute arbitrary code to update the logging configuration, such as * setting logger levels, adding handlers, adding filters, etc. * </ul> * <p> * Note that all classes loaded during LogManager configuration are * first searched on the system class path before any user class path. * That includes the LogManager class, any config classes, and any * handler classes. * <p> * Loggers are organized into a naming hierarchy based on their * dot separated names. Thus "a.b.c" is a child of "a.b", but * "a.b1" and a.b2" are peers. * <p> * All properties whose names end with ".level" are assumed to define * log levels for Loggers. Thus "foo.level" defines a log level for * the logger called "foo" and (recursively) for any of its children * in the naming hierarchy. Log Levels are applied in the order they * are defined in the properties file. Thus level settings for child * nodes in the tree should come after settings for their parents. * The property name ".level" can be used to set the level for the * root of the tree. * <p> * All methods on the LogManager object are multi-thread safe. * {@description.close} * * @since 1.4 */ public class LogManager { // The global LogManager object private static LogManager manager; private final static Handler[] emptyHandlers = { }; private Properties props = new Properties(); private PropertyChangeSupport changes = new PropertyChangeSupport(LogManager.class); private final static Level defaultLevel = Level.INFO; // Table of named Loggers that maps names to Loggers. private Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<String,LoggerWeakRef>(); // Tree of named Loggers private LogNode root = new LogNode(null); private Logger rootLogger; // Have we done the primordial reading of the configuration file? // (Must be done after a suitable amount of java.lang.System // initialization has been done) private volatile boolean readPrimordialConfiguration; // Have we initialized global (root) handlers yet? // This gets set to false in readConfiguration private boolean initializedGlobalHandlers = true; // True if JVM death is imminent and the exit hook has been called. private boolean deathImminent; static { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { String cname = null; try { cname = System.getProperty("java.util.logging.manager"); if (cname != null) { try { Class clz = ClassLoader.getSystemClassLoader().loadClass(cname); manager = (LogManager) clz.newInstance(); } catch (ClassNotFoundException ex) { Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname); manager = (LogManager) clz.newInstance(); } } } catch (Exception ex) { System.err.println("Could not load Logmanager \"" + cname + "\""); ex.printStackTrace(); } if (manager == null) { manager = new LogManager(); } // Create and retain Logger for the root of the namespace. manager.rootLogger = manager.new RootLogger(); manager.addLogger(manager.rootLogger); // Adding the global Logger. Doing so in the Logger.<clinit> // would deadlock with the LogManager.<clinit>. Logger.global.setLogManager(manager); manager.addLogger(Logger.global); // We don't call readConfiguration() here, as we may be running // very early in the JVM startup sequence. Instead readConfiguration // will be called lazily in getLogManager(). return null; } }); } // This private class is used as a shutdown hook. // It does a "reset" to close all open handlers. private class Cleaner extends Thread { public void run() { // This is to ensure the LogManager.<clinit> is completed // before synchronized block. Otherwise deadlocks are possible. LogManager mgr = manager; // If the global handlers haven't been initialized yet, we // don't want to initialize them just so we can close them! synchronized (LogManager.this) { // Note that death is imminent. deathImminent = true; initializedGlobalHandlers = true; } // Do a reset to close all active handlers. reset(); } } /** {@collect.stats} * {@description.open} * Protected constructor. This is protected so that container applications * (such as J2EE containers) can subclass the object. It is non-public as * it is intended that there only be one LogManager object, whose value is * retrieved by calling Logmanager.getLogManager. * {@description.close} */ protected LogManager() { // Add a shutdown hook to close the global handlers. try { Runtime.getRuntime().addShutdownHook(new Cleaner()); } catch (IllegalStateException e) { // If the VM is already shutting down, // We do not need to register shutdownHook. } } /** {@collect.stats} * {@description.open} * Return the global LogManager object. * {@description.close} */ public static LogManager getLogManager() { if (manager != null) { manager.readPrimordialConfiguration(); } return manager; } private void readPrimordialConfiguration() { if (!readPrimordialConfiguration) { synchronized (this) { if (!readPrimordialConfiguration) { // If System.in/out/err are null, it's a good // indication that we're still in the // bootstrapping phase if (System.out == null) { return; } readPrimordialConfiguration = true; try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { readConfiguration(); return null; } }); } catch (Exception ex) { // System.err.println("Can't read logging configuration:"); // ex.printStackTrace(); } } } } } /** {@collect.stats} * {@description.open} * Adds an event listener to be invoked when the logging * properties are re-read. Adding multiple instances of * the same event Listener results in multiple entries * in the property event listener table. * {@description.close} * * @param l event listener * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). * @exception NullPointerException if the PropertyChangeListener is null. */ public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException { if (l == null) { throw new NullPointerException(); } checkAccess(); changes.addPropertyChangeListener(l); } /** {@collect.stats} * {@description.open} * Removes an event listener for property change events. * If the same listener instance has been added to the listener table * through multiple invocations of <CODE>addPropertyChangeListener</CODE>, * then an equivalent number of * <CODE>removePropertyChangeListener</CODE> invocations are required to remove * all instances of that listener from the listener table. * <P> * Returns silently if the given listener is not found. * {@description.close} * * @param l event listener (can be null) * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException { checkAccess(); changes.removePropertyChangeListener(l); } // Package-level method. // Find or create a specified logger instance. If a logger has // already been created with the given name it is returned. // Otherwise a new logger instance is created and registered // in the LogManager global namespace. synchronized Logger demandLogger(String name) { Logger result = getLogger(name); if (result == null) { result = new Logger(name, null); addLogger(result); result = getLogger(name); } return result; } // If logger.getUseParentHandlers() returns 'true' and any of the logger's // parents have levels or handlers defined, make sure they are instantiated. private void processParentHandlers(Logger logger, String name) { int ix = 1; for (;;) { int ix2 = name.indexOf(".", ix); if (ix2 < 0) { break; } String pname = name.substring(0,ix2); if (getProperty(pname+".level") != null || getProperty(pname+".handlers") != null) { // This pname has a level/handlers definition. // Make sure it exists. demandLogger(pname); } ix = ix2+1; } } // Add new per logger handlers. // We need to raise privilege here. All our decisions will // be made based on the logging configuration, which can // only be modified by trusted code. private void loadLoggerHandlers(final Logger logger, final String name, final String handlersPropertyName) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { if (logger != rootLogger) { boolean useParent = getBooleanProperty(name + ".useParentHandlers", true); if (!useParent) { logger.setUseParentHandlers(false); } } String names[] = parseClassNames(handlersPropertyName); for (int i = 0; i < names.length; i++) { String word = names[i]; try { Class clz = ClassLoader.getSystemClassLoader().loadClass(word); Handler hdl = (Handler) clz.newInstance(); try { // Check if there is a property defining the // this handler's level. String levs = getProperty(word + ".level"); if (levs != null) { hdl.setLevel(Level.parse(levs)); } } catch (Exception ex) { System.err.println("Can't set level for " + word); // Probably a bad level. Drop through. } // Add this Handler to the logger logger.addHandler(hdl); } catch (Exception ex) { System.err.println("Can't load log handler \"" + word + "\""); System.err.println("" + ex); ex.printStackTrace(); } } return null; }}); } // loggerRefQueue holds LoggerWeakRef objects for Logger objects // that have been GC'ed. private final ReferenceQueue<Logger> loggerRefQueue = new ReferenceQueue<Logger>(); // Package-level inner class. // Helper class for managing WeakReferences to Logger objects. // // LogManager.namedLoggers // - has weak references to all named Loggers // - namedLoggers keeps the LoggerWeakRef objects for the named // Loggers around until we can deal with the book keeping for // the named Logger that is being GC'ed. // LogManager.LogNode.loggerRef // - has a weak reference to a named Logger // - the LogNode will also keep the LoggerWeakRef objects for // the named Loggers around; currently LogNodes never go away. // Logger.kids // - has a weak reference to each direct child Logger; this // includes anonymous and named Loggers // - anonymous Loggers are always children of the rootLogger // which is a strong reference; rootLogger.kids keeps the // LoggerWeakRef objects for the anonymous Loggers around // until we can deal with the book keeping. // final class LoggerWeakRef extends WeakReference<Logger> { private String name; // for namedLoggers cleanup private LogNode node; // for loggerRef cleanup private WeakReference<Logger> parentRef; // for kids cleanup LoggerWeakRef(Logger logger) { super(logger, loggerRefQueue); name = logger.getName(); // save for namedLoggers cleanup } // dispose of this LoggerWeakRef object void dispose() { if (node != null) { // if we have a LogNode, then we were a named Logger // so clear namedLoggers weak ref to us manager.namedLoggers.remove(name); name = null; // clear our ref to the Logger's name node.loggerRef = null; // clear LogNode's weak ref to us node = null; // clear our ref to LogNode } if (parentRef != null) { // this LoggerWeakRef has or had a parent Logger Logger parent = parentRef.get(); if (parent != null) { // the parent Logger is still there so clear the // parent Logger's weak ref to us parent.removeChildLogger(this); } parentRef = null; // clear our weak ref to the parent Logger } } // set the node field to the specified value void setNode(LogNode node) { this.node = node; } // set the parentRef field to the specified value void setParentRef(WeakReference<Logger> parentRef) { this.parentRef = parentRef; } } // Package-level method. // Drain some Logger objects that have been GC'ed. // // drainLoggerRefQueueBounded() is called by addLogger() below // and by Logger.getAnonymousLogger(String) so we'll drain up to // MAX_ITERATIONS GC'ed Loggers for every Logger we add. // // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives // us about a 50/50 mix in increased weak ref counts versus // decreased weak ref counts in the AnonLoggerWeakRefLeak test. // Here are stats for cleaning up sets of 400 anonymous Loggers: // - test duration 1 minute // - sample size of 125 sets of 400 // - average: 1.99 ms // - minimum: 0.57 ms // - maximum: 25.3 ms // // The same config gives us a better decreased weak ref count // than increased weak ref count in the LoggerWeakRefLeak test. // Here are stats for cleaning up sets of 400 named Loggers: // - test duration 2 minutes // - sample size of 506 sets of 400 // - average: 0.57 ms // - minimum: 0.02 ms // - maximum: 10.9 ms // private final static int MAX_ITERATIONS = 400; final synchronized void drainLoggerRefQueueBounded() { for (int i = 0; i < MAX_ITERATIONS; i++) { if (loggerRefQueue == null) { // haven't finished loading LogManager yet break; } // this hack is needed to build this for release jdk6 WeakReference<Logger> dummy = (WeakReference<Logger>) loggerRefQueue.poll(); LoggerWeakRef ref = (LoggerWeakRef) dummy; if (ref == null) { break; } // a Logger object has been GC'ed so clean it up ref.dispose(); } } /** {@collect.stats} * {@description.open} * Add a named logger. This does nothing and returns false if a logger * with the same name is already registered. * <p> * The Logger factory methods call this method to register each * newly created Logger. * <p> * {@description.close} * {@property.open} * The application should retain its own reference to the Logger * object to avoid it being garbage collected. The LogManager * may only retain a weak reference. * {@property.close} * * @param logger the new logger. * @return true if the argument logger was registered successfully, * false if a logger of that name already exists. * @exception NullPointerException if the logger name is null. */ public synchronized boolean addLogger(Logger logger) { final String name = logger.getName(); if (name == null) { throw new NullPointerException(); } // cleanup some Loggers that have been GC'ed drainLoggerRefQueueBounded(); LoggerWeakRef ref = namedLoggers.get(name); if (ref != null) { if (ref.get() == null) { // It's possible that the Logger was GC'ed after the // drainLoggerRefQueueBounded() call above so allow // a new one to be registered. namedLoggers.remove(name); } else { // We already have a registered logger with the given name. return false; } } // We're adding a new logger. // Note that we are creating a weak reference here. ref = new LoggerWeakRef(logger); namedLoggers.put(name, ref); // Apply any initial level defined for the new logger. Level level = getLevelProperty(name+".level", null); if (level != null) { doSetLevel(logger, level); } // Do we have a per logger handler too? // Note: this will add a 200ms penalty loadLoggerHandlers(logger, name, name+".handlers"); processParentHandlers(logger, name); // Find the new node and its parent. LogNode node = findNode(name); node.loggerRef = ref; Logger parent = null; LogNode nodep = node.parent; while (nodep != null) { LoggerWeakRef nodeRef = nodep.loggerRef; if (nodeRef != null) { parent = nodeRef.get(); if (parent != null) { break; } } nodep = nodep.parent; } if (parent != null) { doSetParent(logger, parent); } // Walk over the children and tell them we are their new parent. node.walkAndSetParent(logger); // new LogNode is ready so tell the LoggerWeakRef about it ref.setNode(node); return true; } // Private method to set a level on a logger. // If necessary, we raise privilege before doing the call. private static void doSetLevel(final Logger logger, final Level level) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { // There is no security manager, so things are easy. logger.setLevel(level); return; } // There is a security manager. Raise privilege before // calling setLevel. AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { logger.setLevel(level); return null; }}); } // Private method to set a parent on a logger. // If necessary, we raise privilege before doing the setParent call. private static void doSetParent(final Logger logger, final Logger parent) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { // There is no security manager, so things are easy. logger.setParent(parent); return; } // There is a security manager. Raise privilege before // calling setParent. AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { logger.setParent(parent); return null; }}); } // Find a node in our tree of logger nodes. // If necessary, create it. private LogNode findNode(String name) { if (name == null || name.equals("")) { return root; } LogNode node = root; while (name.length() > 0) { int ix = name.indexOf("."); String head; if (ix > 0) { head = name.substring(0,ix); name = name.substring(ix+1); } else { head = name; name = ""; } if (node.children == null) { node.children = new HashMap<String,LogNode>(); } LogNode child = node.children.get(head); if (child == null) { child = new LogNode(node); node.children.put(head, child); } node = child; } return node; } /** {@collect.stats} * {@description.open} * Method to find a named logger. * <p> * Note that since untrusted code may create loggers with * arbitrary names this method should not be relied on to * find Loggers for security sensitive logging. * It is also important to note that the Logger associated with the * String {@code name} may be garbage collected at any time if there * is no strong reference to the Logger. * {@description.close} * {@property.open static} * The caller of this method * must check the return value for null in order to properly handle * the case where the Logger has been garbage collected. * <p> * {@property.close} * @param name name of the logger * @return matching logger or null if none is found */ public synchronized Logger getLogger(String name) { LoggerWeakRef ref = namedLoggers.get(name); if (ref == null) { return null; } Logger logger = ref.get(); if (logger == null) { // Hashtable holds stale weak reference // to a logger which has been GC-ed. namedLoggers.remove(name); } return logger; } /** {@collect.stats} * {@description.open} * Get an enumeration of known logger names. * <p> * Note: Loggers may be added dynamically as new classes are loaded. * This method only reports on the loggers that are currently registered. * It is also important to note that this method only returns the name * of a Logger, not a strong reference to the Logger itself. * The returned String does nothing to prevent the Logger from being * garbage collected. In particular, if the returned name is passed * to {@code LogManager.getLogger()}, then the caller must check the * return value from {@code LogManager.getLogger()} for null to properly * handle the case where the Logger has been garbage collected in the * time since its name was returned by this method. * <p> * {@description.close} * @return enumeration of logger name strings */ public synchronized Enumeration<String> getLoggerNames() { return namedLoggers.keys(); } /** {@collect.stats} * {@description.open} * Reinitialize the logging properties and reread the logging configuration. * <p> * The same rules are used for locating the configuration properties * as are used at startup. So normally the logging properties will * be re-read from the same file that was used at startup. * <P> * Any log level definitions in the new configuration file will be * applied using Logger.setLevel(), if the target Logger exists. * <p> * A PropertyChangeEvent will be fired after the properties are read. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). * @exception IOException if there are IO problems reading the configuration. */ public void readConfiguration() throws IOException, SecurityException { checkAccess(); // if a configuration class is specified, load it and use it. String cname = System.getProperty("java.util.logging.config.class"); if (cname != null) { try { // Instantiate the named class. It is its constructor's // responsibility to initialize the logging configuration, by // calling readConfiguration(InputStream) with a suitable stream. try { Class clz = ClassLoader.getSystemClassLoader().loadClass(cname); clz.newInstance(); return; } catch (ClassNotFoundException ex) { Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname); clz.newInstance(); return; } } catch (Exception ex) { System.err.println("Logging configuration class \"" + cname + "\" failed"); System.err.println("" + ex); // keep going and useful config file. } } String fname = System.getProperty("java.util.logging.config.file"); if (fname == null) { fname = System.getProperty("java.home"); if (fname == null) { throw new Error("Can't find java.home ??"); } File f = new File(fname, "lib"); f = new File(f, "logging.properties"); fname = f.getCanonicalPath(); } InputStream in = new FileInputStream(fname); BufferedInputStream bin = new BufferedInputStream(in); try { readConfiguration(bin); } finally { if (in != null) { in.close(); } } } /** {@collect.stats} * {@description.open} * Reset the logging configuration. * <p> * For all named loggers, the reset operation removes and closes * all Handlers and (except for the root logger) sets the level * to null. The root logger's level is set to Level.INFO. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void reset() throws SecurityException { checkAccess(); synchronized (this) { props = new Properties(); // Since we are doing a reset we no longer want to initialize // the global handlers, if they haven't been initialized yet. initializedGlobalHandlers = true; } Enumeration enum_ = getLoggerNames(); while (enum_.hasMoreElements()) { String name = (String)enum_.nextElement(); resetLogger(name); } } // Private method to reset an individual target logger. private void resetLogger(String name) { Logger logger = getLogger(name); if (logger == null) { return; } // Close all the Logger's handlers. Handler[] targets = logger.getHandlers(); for (int i = 0; i < targets.length; i++) { Handler h = targets[i]; logger.removeHandler(h); try { h.close(); } catch (Exception ex) { // Problems closing a handler? Keep going... } } if (name != null && name.equals("")) { // This is the root logger. logger.setLevel(defaultLevel); } else { logger.setLevel(null); } } // get a list of whitespace separated classnames from a property. private String[] parseClassNames(String propertyName) { String hands = getProperty(propertyName); if (hands == null) { return new String[0]; } hands = hands.trim(); int ix = 0; Vector<String> result = new Vector<String>(); while (ix < hands.length()) { int end = ix; while (end < hands.length()) { if (Character.isWhitespace(hands.charAt(end))) { break; } if (hands.charAt(end) == ',') { break; } end++; } String word = hands.substring(ix, end); ix = end+1; word = word.trim(); if (word.length() == 0) { continue; } result.add(word); } return result.toArray(new String[result.size()]); } /** {@collect.stats} * {@description.open} * Reinitialize the logging properties and reread the logging configuration * from the given stream, which should be in java.util.Properties format. * A PropertyChangeEvent will be fired after the properties are read. * <p> * Any log level definitions in the new configuration file will be * applied using Logger.setLevel(), if the target Logger exists. * {@description.close} * * @param ins stream to read properties from * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). * @exception IOException if there are problems reading from the stream. */ public void readConfiguration(InputStream ins) throws IOException, SecurityException { checkAccess(); reset(); // Load the properties props.load(ins); // Instantiate new configuration objects. String names[] = parseClassNames("config"); for (int i = 0; i < names.length; i++) { String word = names[i]; try { Class clz = ClassLoader.getSystemClassLoader().loadClass(word); clz.newInstance(); } catch (Exception ex) { System.err.println("Can't load config class \"" + word + "\""); System.err.println("" + ex); // ex.printStackTrace(); } } // Set levels on any pre-existing loggers, based on the new properties. setLevelsOnExistingLoggers(); // Notify any interested parties that our properties have changed. changes.firePropertyChange(null, null, null); // Note that we need to reinitialize global handles when // they are first referenced. synchronized (this) { initializedGlobalHandlers = false; } } /** {@collect.stats} * {@description.open} * Get the value of a logging property. * The method returns null if the property is not found. * {@description.close} * @param name property name * @return property value */ public String getProperty(String name) { return props.getProperty(name); } // Package private method to get a String property. // If the property is not defined we return the given // default value. String getStringProperty(String name, String defaultValue) { String val = getProperty(name); if (val == null) { return defaultValue; } return val.trim(); } // Package private method to get an integer property. // If the property is not defined or cannot be parsed // we return the given default value. int getIntProperty(String name, int defaultValue) { String val = getProperty(name); if (val == null) { return defaultValue; } try { return Integer.parseInt(val.trim()); } catch (Exception ex) { return defaultValue; } } // Package private method to get a boolean property. // If the property is not defined or cannot be parsed // we return the given default value. boolean getBooleanProperty(String name, boolean defaultValue) { String val = getProperty(name); if (val == null) { return defaultValue; } val = val.toLowerCase(); if (val.equals("true") || val.equals("1")) { return true; } else if (val.equals("false") || val.equals("0")) { return false; } return defaultValue; } // Package private method to get a Level property. // If the property is not defined or cannot be parsed // we return the given default value. Level getLevelProperty(String name, Level defaultValue) { String val = getProperty(name); if (val == null) { return defaultValue; } try { return Level.parse(val.trim()); } catch (Exception ex) { return defaultValue; } } // Package private method to get a filter property. // We return an instance of the class named by the "name" // property. If the property is not defined or has problems // we return the defaultValue. Filter getFilterProperty(String name, Filter defaultValue) { String val = getProperty(name); try { if (val != null) { Class clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } // Package private method to get a formatter property. // We return an instance of the class named by the "name" // property. If the property is not defined or has problems // we return the defaultValue. Formatter getFormatterProperty(String name, Formatter defaultValue) { String val = getProperty(name); try { if (val != null) { Class clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Formatter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } // Private method to load the global handlers. // We do the real work lazily, when the global handlers // are first used. private synchronized void initializeGlobalHandlers() { if (initializedGlobalHandlers) { return; } initializedGlobalHandlers = true; if (deathImminent) { // Aaargh... // The VM is shutting down and our exit hook has been called. // Avoid allocating global handlers. return; } loadLoggerHandlers(rootLogger, null, "handlers"); } private Permission ourPermission = new LoggingPermission("control", null); /** {@collect.stats} * {@description.open} * Check that the current context is trusted to modify the logging * configuration. This requires LoggingPermission("control"). * <p> * If the check fails we throw a SecurityException, otherwise * we return normally. * {@description.close} * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void checkAccess() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm == null) { return; } sm.checkPermission(ourPermission); } // Nested class to represent a node in our tree of named loggers. private static class LogNode { HashMap<String,LogNode> children; LoggerWeakRef loggerRef; LogNode parent; LogNode(LogNode parent) { this.parent = parent; } // Recursive method to walk the tree below a node and set // a new parent logger. void walkAndSetParent(Logger parent) { if (children == null) { return; } Iterator<LogNode> values = children.values().iterator(); while (values.hasNext()) { LogNode node = values.next(); LoggerWeakRef ref = node.loggerRef; Logger logger = (ref == null) ? null : ref.get(); if (logger == null) { node.walkAndSetParent(parent); } else { doSetParent(logger, parent); } } } } // We use a subclass of Logger for the root logger, so // that we only instantiate the global handlers when they // are first needed. private class RootLogger extends Logger { private RootLogger() { super("", null); setLevel(defaultLevel); } public void log(LogRecord record) { // Make sure that the global handlers have been instantiated. initializeGlobalHandlers(); super.log(record); } public void addHandler(Handler h) { initializeGlobalHandlers(); super.addHandler(h); } public void removeHandler(Handler h) { initializeGlobalHandlers(); super.removeHandler(h); } public Handler[] getHandlers() { initializeGlobalHandlers(); return super.getHandlers(); } } // Private method to be called when the configuration has // changed to apply any level settings to any pre-existing loggers. synchronized private void setLevelsOnExistingLoggers() { Enumeration enum_ = props.propertyNames(); while (enum_.hasMoreElements()) { String key = (String)enum_.nextElement(); if (!key.endsWith(".level")) { // Not a level definition. continue; } int ix = key.length() - 6; String name = key.substring(0, ix); Level level = getLevelProperty(key, null); if (level == null) { System.err.println("Bad level value for property: " + key); continue; } Logger l = getLogger(name); if (l == null) { continue; } l.setLevel(level); } } // Management Support private static LoggingMXBean loggingMXBean = null; /** {@collect.stats} * {@description.open} * String representation of the * {@link javax.management.ObjectName} for {@link LoggingMXBean}. * {@description.close} * @since 1.5 */ public final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging"; /** {@collect.stats} * {@description.open} * Returns <tt>LoggingMXBean</tt> for managing loggers. * The <tt>LoggingMXBean</tt> can also obtained from the * {@link java.lang.management.ManagementFactory#getPlatformMBeanServer * platform <tt>MBeanServer</tt>} method. * {@description.close} * * @return a {@link LoggingMXBean} object. * * @see java.lang.management.ManagementFactory * @since 1.5 */ public static synchronized LoggingMXBean getLoggingMXBean() { if (loggingMXBean == null) { loggingMXBean = new Logging(); } return loggingMXBean; } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.io.*; import java.net.*; /** {@collect.stats} * {@description.open} * This <tt>Handler</tt> publishes log records to <tt>System.err</tt>. * By default the <tt>SimpleFormatter</tt> is used to generate brief summaries. * <p> * <b>Configuration:</b> * By default each <tt>ConsoleHandler</tt> is initialized using the following * <tt>LogManager</tt> configuration properties. If properties are not defined * (or have invalid values) then the specified default values are used. * <ul> * <li> java.util.logging.ConsoleHandler.level * specifies the default level for the <tt>Handler</tt> * (defaults to <tt>Level.INFO</tt>). * <li> java.util.logging.ConsoleHandler.filter * specifies the name of a <tt>Filter</tt> class to use * (defaults to no <tt>Filter</tt>). * <li> java.util.logging.ConsoleHandler.formatter * specifies the name of a <tt>Formatter</tt> class to use * (defaults to <tt>java.util.logging.SimpleFormatter</tt>). * <li> java.util.logging.ConsoleHandler.encoding * the name of the character set encoding to use (defaults to * the default platform encoding). * </ul> * <p> * {@description.close} * @since 1.4 */ public class ConsoleHandler extends StreamHandler { // Private method to configure a ConsoleHandler from LogManager // properties and/or default values as specified in the class // javadoc. private void configure() { LogManager manager = LogManager.getLogManager(); String cname = getClass().getName(); setLevel(manager.getLevelProperty(cname +".level", Level.INFO)); setFilter(manager.getFilterProperty(cname +".filter", null)); setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); try { setEncoding(manager.getStringProperty(cname +".encoding", null)); } catch (Exception ex) { try { setEncoding(null); } catch (Exception ex2) { // doing a setEncoding with null should always work. // assert false; } } } /** {@collect.stats} * {@description.open} * Create a <tt>ConsoleHandler</tt> for <tt>System.err</tt>. * <p> * The <tt>ConsoleHandler</tt> is configured based on * <tt>LogManager</tt> properties (or their default values). * * {@description.close} */ public ConsoleHandler() { sealed = false; configure(); setOutputStream(System.err); sealed = true; } /** {@collect.stats} * {@description.open} * Publish a <tt>LogRecord</tt>. * <p> * The logging request was made initially to a <tt>Logger</tt> object, * which initialized the <tt>LogRecord</tt> and forwarded it here. * <p> * {@description.close} * @param record description of the log event. A null record is * silently ignored and is not published */ public void publish(LogRecord record) { super.publish(record); flush(); } /** {@collect.stats} * {@description.open} * Override <tt>StreamHandler.close</tt> to do a flush but not * to close the output stream. That is, we do <b>not</b> * close <tt>System.err</tt>. * {@description.close} */ public void close() { flush(); } }
Java
/* * Copyright (c) 2001, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; /** {@collect.stats} * {@description.open} * ErrorManager objects can be attached to Handlers to process * any error that occur on a Handler during Logging. * <p> * When processing logging output, if a Handler encounters problems * then rather than throwing an Exception back to the issuer of * the logging call (who is unlikely to be interested) the Handler * should call its associated ErrorManager. * {@description.close} */ public class ErrorManager { private boolean reported = false; /* * We declare standard error codes for important categories of errors. */ /** {@collect.stats} * {@description.open} * GENERIC_FAILURE is used for failure that don't fit * into one of the other categories. * {@description.close} */ public final static int GENERIC_FAILURE = 0; /** {@collect.stats} * {@description.open} * WRITE_FAILURE is used when a write to an output stream fails. * {@description.close} */ public final static int WRITE_FAILURE = 1; /** {@collect.stats} * {@description.open} * FLUSH_FAILURE is used when a flush to an output stream fails. * {@description.close} */ public final static int FLUSH_FAILURE = 2; /** {@collect.stats} * {@description.open} * CLOSE_FAILURE is used when a close of an output stream fails. * {@description.close} */ public final static int CLOSE_FAILURE = 3; /** {@collect.stats} * {@description.open} * OPEN_FAILURE is used when an open of an output stream fails. * {@description.close} */ public final static int OPEN_FAILURE = 4; /** {@collect.stats} * {@description.open} * FORMAT_FAILURE is used when formatting fails for any reason. * {@description.close} */ public final static int FORMAT_FAILURE = 5; /** {@collect.stats} * {@description.open} * The error method is called when a Handler failure occurs. * <p> * This method may be overriden in subclasses. The default * behavior in this base class is that the first call is * reported to System.err, and subsequent calls are ignored. * {@description.close} * * @param msg a descriptive string (may be null) * @param ex an exception (may be null) * @param code an error code defined in ErrorManager */ public synchronized void error(String msg, Exception ex, int code) { if (reported) { // We only report the first error, to avoid clogging // the screen. return; } reported = true; String text = "java.util.logging.ErrorManager: " + code; if (msg != null) { text = text + ": " + msg; } System.err.println(text); if (ex != null) { ex.printStackTrace(); } } }
Java
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.logging; import java.util.*; import java.io.*; /** {@collect.stats} * {@description.open} * LogRecord objects are used to pass logging requests between * the logging framework and individual log Handlers. * <p> * When a LogRecord is passed into the logging framework it * logically belongs to the framework and should no longer be * used or updated by the client application. * <p> * Note that if the client application has not specified an * explicit source method name and source class name, then the * LogRecord class will infer them automatically when they are * first accessed (due to a call on getSourceMethodName or * getSourceClassName) by analyzing the call stack. Therefore, * if a logging Handler wants to pass off a LogRecord to another * thread, or to transmit it over RMI, and if it wishes to subsequently * obtain method name or class name information it should call * one of getSourceClassName or getSourceMethodName to force * the values to be filled in. * <p> * <b> Serialization notes:</b> * <ul> * <li>The LogRecord class is serializable. * * <li> Because objects in the parameters array may not be serializable, * during serialization all objects in the parameters array are * written as the corresponding Strings (using Object.toString). * * <li> The ResourceBundle is not transmitted as part of the serialized * form, but the resource bundle name is, and the recipient object's * readObject method will attempt to locate a suitable resource bundle. * * </ul> * {@description.close} * * @since 1.4 */ public class LogRecord implements java.io.Serializable { private static long globalSequenceNumber; private static int nextThreadId=10; private static ThreadLocal<Integer> threadIds = new ThreadLocal<Integer>(); /** {@collect.stats} * @serial Logging message level */ private Level level; /** {@collect.stats} * @serial Sequence number */ private long sequenceNumber; /** {@collect.stats} * @serial Class that issued logging call */ private String sourceClassName; /** {@collect.stats} * @serial Method that issued logging call */ private String sourceMethodName; /** {@collect.stats} * @serial Non-localized raw message text */ private String message; /** {@collect.stats} * @serial Thread ID for thread that issued logging call. */ private int threadID; /** {@collect.stats} * @serial Event time in milliseconds since 1970 */ private long millis; /** {@collect.stats} * @serial The Throwable (if any) associated with log message */ private Throwable thrown; /** {@collect.stats} * @serial Name of the source Logger. */ private String loggerName; /** {@collect.stats} * @serial Resource bundle name to localized log message. */ private String resourceBundleName; private transient boolean needToInferCaller; private transient Object parameters[]; private transient ResourceBundle resourceBundle; /** {@collect.stats} * {@description.open} * Construct a LogRecord with the given level and message values. * <p> * The sequence property will be initialized with a new unique value. * These sequence values are allocated in increasing order within a VM. * <p> * The millis property will be initialized to the current time. * <p> * The thread ID property will be initialized with a unique ID for * the current thread. * <p> * All other properties will be initialized to "null". * {@description.close} * * @param level a logging level value * @param msg the raw non-localized logging message (may be null) */ public LogRecord(Level level, String msg) { // Make sure level isn't null, by calling random method. level.getClass(); this.level = level; message = msg; // Assign a thread ID and a unique sequence number. synchronized (LogRecord.class) { sequenceNumber = globalSequenceNumber++; Integer id = threadIds.get(); if (id == null) { id = new Integer(nextThreadId++); threadIds.set(id); } threadID = id.intValue(); } millis = System.currentTimeMillis(); needToInferCaller = true; } /** {@collect.stats} * {@description.open} * Get the source Logger name's * {@description.close} * * @return source logger name (may be null) */ public String getLoggerName() { return loggerName; } /** {@collect.stats} * {@description.open} * Set the source Logger name. * {@description.close} * * @param name the source logger name (may be null) */ public void setLoggerName(String name) { loggerName = name; } /** {@collect.stats} * {@description.open} * Get the localization resource bundle * <p> * This is the ResourceBundle that should be used to localize * the message string before formatting it. The result may * be null if the message is not localizable, or if no suitable * ResourceBundle is available. * {@description.close} */ public ResourceBundle getResourceBundle() { return resourceBundle; } /** {@collect.stats} * {@description.open} * Set the localization resource bundle. * {@description.close} * * @param bundle localization bundle (may be null) */ public void setResourceBundle(ResourceBundle bundle) { resourceBundle = bundle; } /** {@collect.stats} * {@description.open} * Get the localization resource bundle name * <p> * This is the name for the ResourceBundle that should be * used to localize the message string before formatting it. * The result may be null if the message is not localizable. * {@description.close} */ public String getResourceBundleName() { return resourceBundleName; } /** {@collect.stats} * {@description.open} * Set the localization resource bundle name. * {@description.close} * * @param name localization bundle name (may be null) */ public void setResourceBundleName(String name) { resourceBundleName = name; } /** {@collect.stats} * {@description.open} * Get the logging message level, for example Level.SEVERE. * {@description.close} * @return the logging message level */ public Level getLevel() { return level; } /** {@collect.stats} * {@description.open} * Set the logging message level, for example Level.SEVERE. * {@description.close} * @param level the logging message level */ public void setLevel(Level level) { if (level == null) { throw new NullPointerException(); } this.level = level; } /** {@collect.stats} * {@description.open} * Get the sequence number. * <p> * Sequence numbers are normally assigned in the LogRecord * constructor, which assigns unique sequence numbers to * each new LogRecord in increasing order. * {@description.close} * @return the sequence number */ public long getSequenceNumber() { return sequenceNumber; } /** {@collect.stats} * {@description.open} * Set the sequence number. * <p> * Sequence numbers are normally assigned in the LogRecord constructor, * so it should not normally be necessary to use this method. * {@description.close} */ public void setSequenceNumber(long seq) { sequenceNumber = seq; } /** {@collect.stats} * {@description.open} * Get the name of the class that (allegedly) issued the logging request. * <p> * Note that this sourceClassName is not verified and may be spoofed. * This information may either have been provided as part of the * logging call, or it may have been inferred automatically by the * logging framework. In the latter case, the information may only * be approximate and may in fact describe an earlier call on the * stack frame. * <p> * May be null if no information could be obtained. * {@description.close} * * @return the source class name */ public String getSourceClassName() { if (needToInferCaller) { inferCaller(); } return sourceClassName; } /** {@collect.stats} * {@description.open} * Set the name of the class that (allegedly) issued the logging request. * {@description.close} * * @param sourceClassName the source class name (may be null) */ public void setSourceClassName(String sourceClassName) { this.sourceClassName = sourceClassName; needToInferCaller = false; } /** {@collect.stats} * {@description.open} * Get the name of the method that (allegedly) issued the logging request. * <p> * Note that this sourceMethodName is not verified and may be spoofed. * This information may either have been provided as part of the * logging call, or it may have been inferred automatically by the * logging framework. In the latter case, the information may only * be approximate and may in fact describe an earlier call on the * stack frame. * <p> * May be null if no information could be obtained. * {@description.close} * * @return the source method name */ public String getSourceMethodName() { if (needToInferCaller) { inferCaller(); } return sourceMethodName; } /** {@collect.stats} * {@description.open} * Set the name of the method that (allegedly) issued the logging request. * {@description.close} * * @param sourceMethodName the source method name (may be null) */ public void setSourceMethodName(String sourceMethodName) { this.sourceMethodName = sourceMethodName; needToInferCaller = false; } /** {@collect.stats} * {@description.open} * Get the "raw" log message, before localization or formatting. * <p> * May be null, which is equivalent to the empty string "". * <p> * This message may be either the final text or a localization key. * <p> * During formatting, if the source logger has a localization * ResourceBundle and if that ResourceBundle has an entry for * this message string, then the message string is replaced * with the localized value. * {@description.close} * * @return the raw message string */ public String getMessage() { return message; } /** {@collect.stats} * {@description.open} * Set the "raw" log message, before localization or formatting. * {@description.close} * * @param message the raw message string (may be null) */ public void setMessage(String message) { this.message = message; } /** {@collect.stats} * {@description.open} * Get the parameters to the log message. * {@description.close} * * @return the log message parameters. May be null if * there are no parameters. */ public Object[] getParameters() { return parameters; } /** {@collect.stats} * {@description.open} * Set the parameters to the log message. * {@description.close} * * @param parameters the log message parameters. (may be null) */ public void setParameters(Object parameters[]) { this.parameters = parameters; } /** {@collect.stats} * {@description.open} * Get an identifier for the thread where the message originated. * <p> * This is a thread identifier within the Java VM and may or * may not map to any operating system ID. * {@description.close} * * @return thread ID */ public int getThreadID() { return threadID; } /** {@collect.stats} * {@description.open} * Set an identifier for the thread where the message originated. * {@description.close} * @param threadID the thread ID */ public void setThreadID(int threadID) { this.threadID = threadID; } /** {@collect.stats} * {@description.open} * Get event time in milliseconds since 1970. * {@description.close} * * @return event time in millis since 1970 */ public long getMillis() { return millis; } /** {@collect.stats} * {@description.open} * Set event time. * {@description.close} * * @param millis event time in millis since 1970 */ public void setMillis(long millis) { this.millis = millis; } /** {@collect.stats} * {@description.open} * Get any throwable associated with the log record. * <p> * If the event involved an exception, this will be the * exception object. Otherwise null. * {@description.close} * * @return a throwable */ public Throwable getThrown() { return thrown; } /** {@collect.stats} * {@description.open} * Set a throwable associated with the log event. * {@description.close} * * @param thrown a throwable (may be null) */ public void setThrown(Throwable thrown) { this.thrown = thrown; } private static final long serialVersionUID = 5372048053134512534L; /** {@collect.stats} * @serialData Default fields, followed by a two byte version number * (major byte, followed by minor byte), followed by information on * the log record parameter array. If there is no parameter array, * then -1 is written. If there is a parameter array (possible of zero * length) then the array length is written as an integer, followed * by String values for each parameter. If a parameter is null, then * a null String is written. Otherwise the output of Object.toString() * is written. */ private void writeObject(ObjectOutputStream out) throws IOException { // We have to call defaultWriteObject first. out.defaultWriteObject(); // Write our version number. out.writeByte(1); out.writeByte(0); if (parameters == null) { out.writeInt(-1); return; } out.writeInt(parameters.length); // Write string values for the parameters. for (int i = 0; i < parameters.length; i++) { if (parameters[i] == null) { out.writeObject(null); } else { out.writeObject(parameters[i].toString()); } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // We have to call defaultReadObject first. in.defaultReadObject(); // Read version number. byte major = in.readByte(); byte minor = in.readByte(); if (major != 1) { throw new IOException("LogRecord: bad version: " + major + "." + minor); } int len = in.readInt(); if (len == -1) { parameters = null; } else { parameters = new Object[len]; for (int i = 0; i < parameters.length; i++) { parameters[i] = in.readObject(); } } // If necessary, try to regenerate the resource bundle. if (resourceBundleName != null) { try { resourceBundle = ResourceBundle.getBundle(resourceBundleName); } catch (MissingResourceException ex) { // This is not a good place to throw an exception, // so we simply leave the resourceBundle null. resourceBundle = null; } } needToInferCaller = false; } // Private method to infer the caller's class and method names private void inferCaller() { needToInferCaller = false; // Get the stack trace. StackTraceElement stack[] = (new Throwable()).getStackTrace(); // First, search back to a method in the Logger class. int ix = 0; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (cname.equals("java.util.logging.Logger")) { break; } ix++; } // Now search for the first frame before the "Logger" class. while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (!cname.equals("java.util.logging.Logger")) { // We've found the relevant frame. setSourceClassName(cname); setSourceMethodName(frame.getMethodName()); return; } ix++; } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.FilterInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Map; import java.util.HashMap; import java.util.Iterator; /** {@collect.stats} * {@description.open} * The Manifest class is used to maintain Manifest entry names and their * associated Attributes. There are main Manifest Attributes as well as * per-entry Attributes. For information on the Manifest format, please * see the * <a href="../../../../technotes/guides/jar/jar.html"> * Manifest format specification</a>. * {@description.close} * * @author David Connelly * @see Attributes * @since 1.2 */ public class Manifest implements Cloneable { // manifest main attributes private Attributes attr = new Attributes(); // manifest entries private Map entries = new HashMap(); /** {@collect.stats} * {@description.open} * Constructs a new, empty Manifest. * {@description.close} */ public Manifest() { } /** {@collect.stats} * {@description.open} * Constructs a new Manifest from the specified input stream. * {@description.close} * * @param is the input stream containing manifest data * @throws IOException if an I/O error has occured */ public Manifest(InputStream is) throws IOException { read(is); } /** {@collect.stats} * {@description.open} * Constructs a new Manifest that is a copy of the specified Manifest. * {@description.close} * * @param man the Manifest to copy */ public Manifest(Manifest man) { attr.putAll(man.getMainAttributes()); entries.putAll(man.getEntries()); } /** {@collect.stats} * {@description.open} * Returns the main Attributes for the Manifest. * {@description.close} * @return the main Attributes for the Manifest */ public Attributes getMainAttributes() { return attr; } /** {@collect.stats} * {@description.open} * Returns a Map of the entries contained in this Manifest. Each entry * is represented by a String name (key) and associated Attributes (value). * The Map permits the {@code null} key, but no entry with a null key is * created by {@link #read}, nor is such an entry written by using {@link * #write}. * {@description.close} * * @return a Map of the entries contained in this Manifest */ public Map<String,Attributes> getEntries() { return entries; } /** {@collect.stats} * {@description.open} * Returns the Attributes for the specified entry name. * This method is defined as: * <pre> * return (Attributes)getEntries().get(name) * </pre> * Though {@code null} is a valid {@code name}, when * {@code getAttributes(null)} is invoked on a {@code Manifest} * obtained from a jar file, {@code null} will be returned. While jar * files themselves do not allow {@code null}-named attributes, it is * possible to invoke {@link #getEntries} on a {@code Manifest}, and * on that result, invoke {@code put} with a null key and an * arbitrary value. Subsequent invocations of * {@code getAttributes(null)} will return the just-{@code put} * value. * <p> * Note that this method does not return the manifest's main attributes; * see {@link #getMainAttributes}. * {@description.close} * * @param name entry name * @return the Attributes for the specified entry name */ public Attributes getAttributes(String name) { return getEntries().get(name); } /** {@collect.stats} * {@description.open} * Clears the main Attributes as well as the entries in this Manifest. * {@description.close} */ public void clear() { attr.clear(); entries.clear(); } /** {@collect.stats} * {@description.open} * Writes the Manifest to the specified OutputStream. * Attributes.Name.MANIFEST_VERSION must be set in * MainAttributes prior to invoking this method. * {@description.close} * * @param out the output stream * @exception IOException if an I/O error has occurred * @see #getMainAttributes */ public void write(OutputStream out) throws IOException { DataOutputStream dos = new DataOutputStream(out); // Write out the main attributes for the manifest attr.writeMain(dos); // Now write out the pre-entry attributes Iterator it = entries.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry)it.next(); StringBuffer buffer = new StringBuffer("Name: "); String value = (String)e.getKey(); if (value != null) { byte[] vb = value.getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); } buffer.append(value); buffer.append("\r\n"); make72Safe(buffer); dos.writeBytes(buffer.toString()); ((Attributes)e.getValue()).write(dos); } dos.flush(); } /** {@collect.stats} * {@description.open} * Adds line breaks to enforce a maximum 72 bytes per line. * {@description.close} */ static void make72Safe(StringBuffer line) { int length = line.length(); if (length > 72) { int index = 70; while (index < length - 2) { line.insert(index, "\r\n "); index += 72; length += 3; } } return; } /** {@collect.stats} * {@description.open} * Reads the Manifest from the specified InputStream. The entry * names and attributes read will be merged in with the current * manifest entries. * {@description.close} * * @param is the input stream * @exception IOException if an I/O error has occurred */ public void read(InputStream is) throws IOException { // Buffered input stream for reading manifest data FastInputStream fis = new FastInputStream(is); // Line buffer byte[] lbuf = new byte[512]; // Read the main attributes for the manifest attr.read(fis, lbuf); // Total number of entries, attributes read int ecount = 0, acount = 0; // Average size of entry attributes int asize = 2; // Now parse the manifest entries int len; String name = null; boolean skipEmptyLines = true; byte[] lastline = null; while ((len = fis.readLine(lbuf)) != -1) { if (lbuf[--len] != '\n') { throw new IOException("manifest line too long"); } if (len > 0 && lbuf[len-1] == '\r') { --len; } if (len == 0 && skipEmptyLines) { continue; } skipEmptyLines = false; if (name == null) { name = parseName(lbuf, len); if (name == null) { throw new IOException("invalid manifest format"); } if (fis.peek() == ' ') { // name is wrapped lastline = new byte[len - 6]; System.arraycopy(lbuf, 6, lastline, 0, len - 6); continue; } } else { // continuation line byte[] buf = new byte[lastline.length + len - 1]; System.arraycopy(lastline, 0, buf, 0, lastline.length); System.arraycopy(lbuf, 1, buf, lastline.length, len - 1); if (fis.peek() == ' ') { // name is wrapped lastline = buf; continue; } name = new String(buf, 0, buf.length, "UTF8"); lastline = null; } Attributes attr = getAttributes(name); if (attr == null) { attr = new Attributes(asize); entries.put(name, attr); } attr.read(fis, lbuf); ecount++; acount += attr.size(); //XXX: Fix for when the average is 0. When it is 0, // you get an Attributes object with an initial // capacity of 0, which tickles a bug in HashMap. asize = Math.max(2, acount / ecount); name = null; skipEmptyLines = true; } } private String parseName(byte[] lbuf, int len) { if (toLower(lbuf[0]) == 'n' && toLower(lbuf[1]) == 'a' && toLower(lbuf[2]) == 'm' && toLower(lbuf[3]) == 'e' && lbuf[4] == ':' && lbuf[5] == ' ') { try { return new String(lbuf, 6, len - 6, "UTF8"); } catch (Exception e) { } } return null; } private int toLower(int c) { return (c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c; } /** {@collect.stats} * {@description.open} * Returns true if the specified Object is also a Manifest and has * the same main Attributes and entries. * {@description.close} * * @param o the object to be compared * @return true if the specified Object is also a Manifest and has * the same main Attributes and entries */ public boolean equals(Object o) { if (o instanceof Manifest) { Manifest m = (Manifest)o; return attr.equals(m.getMainAttributes()) && entries.equals(m.getEntries()); } else { return false; } } /** {@collect.stats} * {@description.open} * Returns the hash code for this Manifest. * {@description.close} */ public int hashCode() { return attr.hashCode() + entries.hashCode(); } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this Manifest. The shallow copy is * implemented as follows: * <pre> * public Object clone() { return new Manifest(this); } * </pre> * {@description.close} * @return a shallow copy of this Manifest */ public Object clone() { return new Manifest(this); } /* * A fast buffered input stream for parsing manifest files. */ static class FastInputStream extends FilterInputStream { private byte buf[]; private int count = 0; private int pos = 0; FastInputStream(InputStream in) { this(in, 8192); } FastInputStream(InputStream in, int size) { super(in); buf = new byte[size]; } public int read() throws IOException { if (pos >= count) { fill(); if (pos >= count) { return -1; } } return buf[pos++] & 0xff; } public int read(byte[] b, int off, int len) throws IOException { int avail = count - pos; if (avail <= 0) { if (len >= buf.length) { return in.read(b, off, len); } fill(); avail = count - pos; if (avail <= 0) { return -1; } } if (len > avail) { len = avail; } System.arraycopy(buf, pos, b, off, len); pos += len; return len; } /* * Reads 'len' bytes from the input stream, or until an end-of-line * is reached. Returns the number of bytes read. */ public int readLine(byte[] b, int off, int len) throws IOException { byte[] tbuf = this.buf; int total = 0; while (total < len) { int avail = count - pos; if (avail <= 0) { fill(); avail = count - pos; if (avail <= 0) { return -1; } } int n = len - total; if (n > avail) { n = avail; } int tpos = pos; int maxpos = tpos + n; while (tpos < maxpos && tbuf[tpos++] != '\n') ; n = tpos - pos; System.arraycopy(tbuf, pos, b, off, n); off += n; total += n; pos = tpos; if (tbuf[tpos-1] == '\n') { break; } } return total; } public byte peek() throws IOException { if (pos == count) fill(); return buf[pos]; } public int readLine(byte[] b) throws IOException { return readLine(b, 0, b.length); } public long skip(long n) throws IOException { if (n <= 0) { return 0; } long avail = count - pos; if (avail <= 0) { return in.skip(n); } if (n > avail) { n = avail; } pos += n; return n; } public int available() throws IOException { return (count - pos) + in.available(); } public void close() throws IOException { if (in != null) { in.close(); in = null; buf = null; } } private void fill() throws IOException { count = pos = 0; int n = in.read(buf, 0, buf.length); if (n > 0) { count = n; } } } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.util.SortedMap; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.IOException; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.security.AccessController; import java.security.PrivilegedAction; /** {@collect.stats} * {@description.open} * Transforms a JAR file to or from a packed stream in Pack200 format. * Please refer to Network Transfer Format JSR 200 Specification at * <a href=http://jcp.org/aboutJava/communityprocess/review/jsr200/index.html>http://jcp.org/aboutJava/communityprocess/review/jsr200/index.html</a> * <p> * Typically the packer engine is used by application developers * to deploy or host JAR files on a website. * The unpacker engine is used by deployment applications to * transform the byte-stream back to JAR format. * <p> * Here is an example using packer and unpacker:<p> * <blockquote><pre> * import java.util.jar.Pack200; * import java.util.jar.Pack200.*; * ... * // Create the Packer object * Packer packer = Pack200.newPacker(); * * // Initialize the state by setting the desired properties * Map p = packer.properties(); * // take more time choosing codings for better compression * p.put(Packer.EFFORT, "7"); // default is "5" * // use largest-possible archive segments (>10% better compression). * p.put(Packer.SEGMENT_LIMIT, "-1"); * // reorder files for better compression. * p.put(Packer.KEEP_FILE_ORDER, Packer.FALSE); * // smear modification times to a single value. * p.put(Packer.MODIFICATION_TIME, Packer.LATEST); * // ignore all JAR deflation requests, * // transmitting a single request to use "store" mode. * p.put(Packer.DEFLATE_HINT, Packer.FALSE); * // discard debug attributes * p.put(Packer.CODE_ATTRIBUTE_PFX+"LineNumberTable", Packer.STRIP); * // throw an error if an attribute is unrecognized * p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR); * // pass one class file uncompressed: * p.put(Packer.PASS_FILE_PFX+0, "mutants/Rogue.class"); * try { * JarFile jarFile = new JarFile("/tmp/testref.jar"); * FileOutputStream fos = new FileOutputStream("/tmp/test.pack"); * // Call the packer * packer.pack(jarFile, fos); * jarFile.close(); * fos.close(); * * File f = new File("/tmp/test.pack"); * FileOutputStream fostream = new FileOutputStream("/tmp/test.jar"); * JarOutputStream jostream = new JarOutputStream(fostream); * Unpacker unpacker = Pack200.newUnpacker(); * // Call the unpacker * unpacker.unpack(f, jostream); * // Must explicitly close the output. * jostream.close(); * } catch (IOException ioe) { * ioe.printStackTrace(); * } * </pre></blockquote> * <p> * A Pack200 file compressed with gzip can be hosted on HTTP/1.1 web servers. * The deployment applications can use "Accept-Encoding=pack200-gzip". This * indicates to the server that the client application desires a version of * the file encoded with Pack200 and further compressed with gzip. Please * refer to <a href="{@docRoot}/../technotes/guides/deployment/deployment-guide/pack200.html">Java Deployment Guide</a> for more details and * techniques. * <p> * Unless otherwise noted, passing a <tt>null</tt> argument to a constructor or * method in this class will cause a {@link NullPointerException} to be thrown. * {@description.close} * * @author John Rose * @author Kumar Srinivasan * @since 1.5 */ public abstract class Pack200 { private Pack200() {} //prevent instantiation // Static methods of the Pack200 class. /** {@collect.stats} * {@description.open} * Obtain new instance of a class that implements Packer. * * <li><p>If the system property <tt>java.util.jar.Pack200.Packer</tt> * is defined, then the value is taken to be the fully-qualified name * of a concrete implementation class, which must implement Packer. * This class is loaded and instantiated. If this process fails * then an unspecified error is thrown.</p></li> * * <li><p>If an implementation has not been specified with the system * property, then the system-default implementation class is instantiated, * and the result is returned.</p></li> * {@description.close} * * {@property.open} * <p>Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. * A multi-threaded application should either allocate multiple * packer engines, or else serialize use of one engine with a lock. * {@property.close} * * @return A newly allocated Packer engine. */ public synchronized static Packer newPacker() { return (Packer) newInstance(PACK_PROVIDER); } /** {@collect.stats} * {@description.open} * Obtain new instance of a class that implements Unpacker. * * <li><p>If the system property <tt>java.util.jar.Pack200.Unpacker</tt> * is defined, then the value is taken to be the fully-qualified * name of a concrete implementation class, which must implement Unpacker. * The class is loaded and instantiated. If this process fails * then an unspecified error is thrown.</p></li> * * <li><p>If an implementation has not been specified with the * system property, then the system-default implementation class * is instantiated, and the result is returned.</p></li> * {@description.close} * * {@property.open} * <p>Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. * A multi-threaded application should either allocate multiple * unpacker engines, or else serialize use of one engine with a lock. * {@property.close} * * @return A newly allocated Unpacker engine. */ public static Unpacker newUnpacker() { return (Unpacker) newInstance(UNPACK_PROVIDER); } // Interfaces /** {@collect.stats} * {@description.open} * The packer engine applies various transformations to the input JAR file, * making the pack stream highly compressible by a compressor such as * gzip or zip. An instance of the engine can be obtained * using {@link #newPacker}. * * The high degree of compression is achieved * by using a number of techniques described in the JSR 200 specification. * Some of the techniques are sorting, re-ordering and co-location of the * constant pool. * <p> * The pack engine is initialized to an initial state as described * by their properties below. * The initial state can be manipulated by getting the * engine properties (using {@link #properties}) and storing * the modified properties on the map. * The resource files will be passed through with no changes at all. * The class files will not contain identical bytes, since the unpacker * is free to change minor class file features such as constant pool order. * However, the class files will be semantically identical, * as specified in the Java Virtual Machine Specification * <a href="http://java.sun.com/docs/books/vmspec/html/ClassFile.doc.html">http://java.sun.com/docs/books/vmspec/html/ClassFile.doc.html</a>. * <p> * By default, the packer does not change the order of JAR elements. * Also, the modification time and deflation hint of each * JAR element is passed unchanged. * (Any other ZIP-archive information, such as extra attributes * giving Unix file permissions, are lost.) * <p> * Note that packing and unpacking a JAR will in general alter the * bytewise contents of classfiles in the JAR. This means that packing * and unpacking will in general invalidate any digital signatures * which rely on bytewise images of JAR elements. In order both to sign * and to pack a JAR, you must first pack and unpack the JAR to * "normalize" it, then compute signatures on the unpacked JAR elements, * and finally repack the signed JAR. * Both packing steps should * use precisely the same options, and the segment limit may also * need to be set to "-1", to prevent accidental variation of segment * boundaries as class file sizes change slightly. * <p> * (Here's why this works: Any reordering the packer does * of any classfile structures is idempotent, so the second packing * does not change the orderings produced by the first packing. * Also, the unpacker is guaranteed by the JSR 200 specification * to produce a specific bytewise image for any given transmission * ordering of archive elements.) * <p> * In order to maintain backward compatibility, if the input JAR-files are * solely comprised of 1.5 (or lesser) classfiles, a 1.5 compatible * pack file is produced. Otherwise a 1.6 compatible pack200 file is * produced. * <p> * {@description.close} * @since 1.5 */ public interface Packer { /** {@collect.stats} * {@description.open} * This property is a numeral giving the estimated target size N * (in bytes) of each archive segment. * If a single input file requires more than N bytes, * it will be given its own archive segment. * <p> * As a special case, a value of -1 will produce a single large * segment with all input files, while a value of 0 will * produce one segment for each class. * Larger archive segments result in less fragmentation and * better compression, but processing them requires more memory. * <p> * The size of each segment is estimated by counting the size of each * input file to be transmitted in the segment, along with the size * of its name and other transmitted properties. * <p> * The default is 1000000 (a million bytes). This allows input JAR files * of moderate size to be transmitted in one segment. It also puts * a limit on memory requirements for packers and unpackers. * <p> * A 10Mb JAR packed without this limit will * typically pack about 10% smaller, but the packer may require * a larger Java heap (about ten times the segment limit). * {@description.close} */ String SEGMENT_LIMIT = "pack.segment.limit"; /** {@collect.stats} * {@description.open} * If this property is set to {@link #TRUE}, the packer will transmit * all elements in their original order within the source archive. * <p> * If it is set to {@link #FALSE}, the packer may reorder elements, * and also remove JAR directory entries, which carry no useful * information for Java applications. * (Typically this enables better compression.) * <p> * The default is {@link #TRUE}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. * {@description.close} */ String KEEP_FILE_ORDER = "pack.keep.file.order"; /** {@collect.stats} * {@description.open} * If this property is set to a single decimal digit, the packer will * use the indicated amount of effort in compressing the archive. * Level 1 may produce somewhat larger size and faster compression speed, * while level 9 will take much longer but may produce better compression. * <p> * The special value 0 instructs the packer to copy through the * original JAR file directly, with no compression. The JSR 200 * standard requires any unpacker to understand this special case * as a pass-through of the entire archive. * <p> * The default is 5, investing a modest amount of time to * produce reasonable compression. * {@description.close} */ String EFFORT = "pack.effort"; /** {@collect.stats} * {@description.open} * If this property is set to {@link #TRUE} or {@link #FALSE}, the packer * will set the deflation hint accordingly in the output archive, and * will not transmit the individual deflation hints of archive elements. * <p> * If this property is set to the special string {@link #KEEP}, the packer * will attempt to determine an independent deflation hint for each * available element of the input archive, and transmit this hint separately. * <p> * The default is {@link #KEEP}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. * <p> * It is up to the unpacker implementation * to take action upon the hint to suitably compress the elements of * the resulting unpacked jar. * <p> * The deflation hint of a ZIP or JAR element indicates * whether the element was deflated or stored directly. * {@description.close} */ String DEFLATE_HINT = "pack.deflate.hint"; /** {@collect.stats} * {@description.open} * If this property is set to the special string {@link #LATEST}, * the packer will attempt to determine the latest modification time, * among all the available entries in the original archive or the latest * modification time of all the available entries in each segment. * This single value will be transmitted as part of the segment and applied * to all the entries in each segment, {@link #SEGMENT_LIMIT}. * <p> * This can marginally decrease the transmitted size of the * archive, at the expense of setting all installed files to a single * date. * <p> * If this property is set to the special string {@link #KEEP}, * the packer transmits a separate modification time for each input * element. * <p> * The default is {@link #KEEP}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. * <p> * It is up to the unpacker implementation to take action to suitably * set the modification time of each element of its output file. * {@description.close} * @see #SEGMENT_LIMIT */ String MODIFICATION_TIME = "pack.modification.time"; /** {@collect.stats} * {@description.open} * Indicates that a file should be passed through bytewise, with no * compression. Multiple files may be specified by specifying * additional properties with distinct strings appended, to * make a family of properties with the common prefix. * <p> * There is no pathname transformation, except * that the system file separator is replaced by the JAR file * separator '/'. * <p> * The resulting file names must match exactly as strings with their * occurrences in the JAR file. * <p> * If a property value is a directory name, all files under that * directory will be passed also. * <p> * Examples: * <pre><code> * Map p = packer.properties(); * p.put(PASS_FILE_PFX+0, "mutants/Rogue.class"); * p.put(PASS_FILE_PFX+1, "mutants/Wolverine.class"); * p.put(PASS_FILE_PFX+2, "mutants/Storm.class"); * # Pass all files in an entire directory hierarchy: * p.put(PASS_FILE_PFX+3, "police/"); * </pre></code>. * {@description.close} */ String PASS_FILE_PFX = "pack.pass.file."; /// Attribute control. /** {@collect.stats} * {@description.open} * Indicates the action to take when a class-file containing an unknown * attribute is encountered. Possible values are the strings {@link #ERROR}, * {@link #STRIP}, and {@link #PASS}. * <p> * The string {@link #ERROR} means that the pack operation * as a whole will fail, with an exception of type <code>IOException</code>. * The string * {@link #STRIP} means that the attribute will be dropped. * The string * {@link #PASS} means that the whole class-file will be passed through * (as if it were a resource file) without compression, with a suitable warning. * This is the default value for this property. * <p> * Examples: * <pre><code> * Map p = pack200.getProperties(); * p.put(UNKNOWN_ATTRIBUTE, ERROR); * p.put(UNKNOWN_ATTRIBUTE, STRIP); * p.put(UNKNOWN_ATTRIBUTE, PASS); * </pre></code> * {@description.close} */ String UNKNOWN_ATTRIBUTE = "pack.unknown.attribute"; /** {@collect.stats} * {@description.open} * When concatenated with a class attribute name, * indicates the format of that attribute, * using the layout language specified in the JSR 200 specification. * <p> * For example, the effect of this option is built in: * <code>pack.class.attribute.SourceFile=RUH</code>. * <p> * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} are * also allowed, with the same meaning as {@link #UNKNOWN_ATTRIBUTE}. * This provides a way for users to request that specific attributes be * refused, stripped, or passed bitwise (with no class compression). * <p> * Code like this might be used to support attributes for JCOV: * <pre><code> * Map p = packer.properties(); * p.put(CODE_ATTRIBUTE_PFX+"CoverageTable", "NH[PHHII]"); * p.put(CODE_ATTRIBUTE_PFX+"CharacterRangeTable", "NH[PHPOHIIH]"); * p.put(CLASS_ATTRIBUTE_PFX+"SourceID", "RUH"); * p.put(CLASS_ATTRIBUTE_PFX+"CompilationID", "RUH"); * </code></pre> * <p> * Code like this might be used to strip debugging attributes: * <pre><code> * Map p = packer.properties(); * p.put(CODE_ATTRIBUTE_PFX+"LineNumberTable", STRIP); * p.put(CODE_ATTRIBUTE_PFX+"LocalVariableTable", STRIP); * p.put(CLASS_ATTRIBUTE_PFX+"SourceFile", STRIP); * </code></pre> * {@description.close} */ String CLASS_ATTRIBUTE_PFX = "pack.class.attribute."; /** {@collect.stats} * {@description.open} * When concatenated with a field attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.field.attribute.Deprecated=</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and * {@link #PASS} are also allowed. * {@description.close} * @see #CLASS_ATTRIBUTE_PFX */ String FIELD_ATTRIBUTE_PFX = "pack.field.attribute."; /** {@collect.stats} * {@description.open} * When concatenated with a method attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.method.attribute.Exceptions=NH[RCH]</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} * are also allowed. * {@description.close} * @see #CLASS_ATTRIBUTE_PFX */ String METHOD_ATTRIBUTE_PFX = "pack.method.attribute."; /** {@collect.stats} * {@description.open} * When concatenated with a code attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.code.attribute.LocalVariableTable=NH[PHOHRUHRSHH]</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} * are also allowed. * {@description.close} * @see #CLASS_ATTRIBUTE_PFX */ String CODE_ATTRIBUTE_PFX = "pack.code.attribute."; /** {@collect.stats} * {@description.open} * The unpacker's progress as a percentage, as periodically * updated by the unpacker. * Values of 0 - 100 are normal, and -1 indicates a stall. * Observe this property with a {@link PropertyChangeListener}. * <p> * At a minimum, the unpacker must set progress to 0 * at the beginning of a packing operation, and to 100 * at the end. * {@description.close} * @see #addPropertyChangeListener */ String PROGRESS = "pack.progress"; /** {@collect.stats} * {@description.open} * The string "keep", a possible value for certain properties. * {@description.close} * @see #DEFLATE_HINT * @see #MODIFICATION_TIME */ String KEEP = "keep"; /** {@collect.stats} * {@description.open} * The string "pass", a possible value for certain properties. * {@description.close} * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String PASS = "pass"; /** {@collect.stats} * {@description.open} * The string "strip", a possible value for certain properties. * {@description.close} * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String STRIP = "strip"; /** {@collect.stats} * {@description.open} * The string "error", a possible value for certain properties. * {@description.close} * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String ERROR = "error"; /** {@collect.stats} * {@description.open} * The string "true", a possible value for certain properties. * {@description.close} * @see #KEEP_FILE_ORDER * @see #DEFLATE_HINT */ String TRUE = "true"; /** {@collect.stats} * {@description.open} * The string "false", a possible value for certain properties. * {@description.close} * @see #KEEP_FILE_ORDER * @see #DEFLATE_HINT */ String FALSE = "false"; /** {@collect.stats} * {@description.open} * The string "latest", a possible value for certain properties. * {@description.close} * @see #MODIFICATION_TIME */ String LATEST = "latest"; /** {@collect.stats} * {@description.open} * Get the set of this engine's properties. * This set is a "live view", so that changing its * contents immediately affects the Packer engine, and * changes from the engine (such as progress indications) * are immediately visible in the map. * * <p>The property map may contain pre-defined implementation * specific and default properties. Users are encouraged to * read the information and fully understand the implications, * before modifying pre-existing properties. * <p> * Implementation specific properties are prefixed with a * package name associated with the implementor, beginning * with <tt>com.</tt> or a similar prefix. * All property names beginning with <tt>pack.</tt> and * <tt>unpack.</tt> are reserved for use by this API. * <p> * Unknown properties may be ignored or rejected with an * unspecified error, and invalid entries may cause an * unspecified error to be thrown. * * <p> * The returned map implements all optional {@link SortedMap} operations * {@description.close} * @return A sorted association of property key strings to property * values. */ SortedMap<String,String> properties(); /** {@collect.stats} * {@description.open} * Takes a JarFile and converts it into a Pack200 archive. * <p> * Closes its input but not its output. (Pack200 archives are appendable.) * {@description.close} * @param in a JarFile * @param out an OutputStream * @exception IOException if an error is encountered. */ void pack(JarFile in, OutputStream out) throws IOException ; /** {@collect.stats} * {@description.open} * Takes a JarInputStream and converts it into a Pack200 archive. * <p> * Closes its input but not its output. (Pack200 archives are appendable.) * <p> * The modification time and deflation hint attributes are not available, * for the JAR manifest file and its containing directory. * {@description.close} * * @see #MODIFICATION_TIME * @see #DEFLATE_HINT * @param in a JarInputStream * @param out an OutputStream * @exception IOException if an error is encountered. */ void pack(JarInputStream in, OutputStream out) throws IOException ; /** {@collect.stats} * {@description.open} * Registers a listener for PropertyChange events on the properties map. * This is typically used by applications to update a progress bar. * {@description.close} * * @see #properties * @see #PROGRESS * @param listener An object to be invoked when a property is changed. */ void addPropertyChangeListener(PropertyChangeListener listener) ; /** {@collect.stats} * {@description.open} * Remove a listener for PropertyChange events, added by * the {@link #addPropertyChangeListener}. * {@description.close} * * @see #addPropertyChangeListener * @param listener The PropertyChange listener to be removed. */ void removePropertyChangeListener(PropertyChangeListener listener); } /** {@collect.stats} * {@description.open} * The unpacker engine converts the packed stream to a JAR file. * An instance of the engine can be obtained * using {@link #newUnpacker}. * <p> * Every JAR file produced by this engine will include the string * "<tt>PACK200</tt>" as a zip file comment. * This allows a deployer to detect if a JAR archive was packed and unpacked. * <p> * This version of the unpacker is compatible with all previous versions. * {@description.close} * @since 1.5 */ public interface Unpacker { /** {@collect.stats} * {@description.open} * The string "keep", a possible value for certain properties. * {@description.close} * @see #DEFLATE_HINT */ String KEEP = "keep"; /** {@collect.stats} * {@description.open} * The string "true", a possible value for certain properties. * {@description.close} * @see #DEFLATE_HINT */ String TRUE = "true"; /** {@collect.stats} * {@description.open} * The string "false", a possible value for certain properties. * {@description.close} * @see #DEFLATE_HINT */ String FALSE = "false"; /** {@collect.stats} * {@description.open} * Property indicating that the unpacker should * ignore all transmitted values for DEFLATE_HINT, * replacing them by the given value, {@link #TRUE} or {@link #FALSE}. * The default value is the special string {@link #KEEP}, * which asks the unpacker to preserve all transmitted * deflation hints. * {@description.close} */ String DEFLATE_HINT = "unpack.deflate.hint"; /** {@collect.stats} * {@description.open} * The unpacker's progress as a percentage, as periodically * updated by the unpacker. * Values of 0 - 100 are normal, and -1 indicates a stall. * Observe this property with a {@link PropertyChangeListener}. * <p> * At a minimum, the unpacker must set progress to 0 * at the beginning of a packing operation, and to 100 * at the end. * {@description.close} * @see #addPropertyChangeListener */ String PROGRESS = "unpack.progress"; /** {@collect.stats} * {@description.open} * Get the set of this engine's properties. This set is * a "live view", so that changing its * contents immediately affects the Packer engine, and * changes from the engine (such as progress indications) * are immediately visible in the map. * * <p>The property map may contain pre-defined implementation * specific and default properties. Users are encouraged to * read the information and fully understand the implications, * before modifying pre-existing properties. * <p> * Implementation specific properties are prefixed with a * package name associated with the implementor, beginning * with <tt>com.</tt> or a similar prefix. * All property names beginning with <tt>pack.</tt> and * <tt>unpack.</tt> are reserved for use by this API. * <p> * Unknown properties may be ignored or rejected with an * unspecified error, and invalid entries may cause an * unspecified error to be thrown. * {@description.close} * * @return A sorted association of option key strings to option values. */ SortedMap<String,String> properties(); /** {@collect.stats} * {@description.open} * Read a Pack200 archive, and write the encoded JAR to * a JarOutputStream. * The entire contents of the input stream will be read. * It may be more efficient to read the Pack200 archive * to a file and pass the File object, using the alternate * method described below. * <p> * Closes its input but not its output. (The output can accumulate more elements.) * {@description.close} * @param in an InputStream. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ void unpack(InputStream in, JarOutputStream out) throws IOException; /** {@collect.stats} * {@description.open} * Read a Pack200 archive, and write the encoded JAR to * a JarOutputStream. * <p> * Does not close its output. (The output can accumulate more elements.) * {@description.close} * @param in a File. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ void unpack(File in, JarOutputStream out) throws IOException; /** {@collect.stats} * {@description.open} * Registers a listener for PropertyChange events on the properties map. * This is typically used by applications to update a progress bar. * {@description.close} * * @see #properties * @see #PROGRESS * @param listener An object to be invoked when a property is changed. */ void addPropertyChangeListener(PropertyChangeListener listener) ; /** {@collect.stats} * {@description.open} * Remove a listener for PropertyChange events, added by * the {@link #addPropertyChangeListener}. * {@description.close} * * @see #addPropertyChangeListener * @param listener The PropertyChange listener to be removed. */ void removePropertyChangeListener(PropertyChangeListener listener); } // Private stuff.... private static final String PACK_PROVIDER = "java.util.jar.Pack200.Packer"; private static final String UNPACK_PROVIDER = "java.util.jar.Pack200.Unpacker"; private static Class packerImpl; private static Class unpackerImpl; private synchronized static Object newInstance(String prop) { String implName = "(unknown)"; try { Class impl = (prop == PACK_PROVIDER)? packerImpl: unpackerImpl; if (impl == null) { // The first time, we must decide which class to use. implName = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction(prop,"")); if (implName != null && !implName.equals("")) impl = Class.forName(implName); else if (prop == PACK_PROVIDER) impl = com.sun.java.util.jar.pack.PackerImpl.class; else impl = com.sun.java.util.jar.pack.UnpackerImpl.class; } // We have a class. Now instantiate it. return impl.newInstance(); } catch (ClassNotFoundException e) { throw new Error("Class not found: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } catch (InstantiationException e) { throw new Error("Could not instantiate: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } catch (IllegalAccessException e) { throw new Error("Cannot access class: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.*; import java.lang.ref.SoftReference; import java.util.*; import java.util.zip.*; import java.security.CodeSigner; import java.security.cert.Certificate; import java.security.AccessController; import sun.security.action.GetPropertyAction; import sun.security.util.ManifestEntryVerifier; import sun.misc.SharedSecrets; /** {@collect.stats} * {@description.open} * The <code>JarFile</code> class is used to read the contents of a jar file * from any file that can be opened with <code>java.io.RandomAccessFile</code>. * It extends the class <code>java.util.zip.ZipFile</code> with support * for reading an optional <code>Manifest</code> entry. The * <code>Manifest</code> can be used to specify meta-information about the * jar file and its entries. * * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * {@description.close} * * @author David Connelly * @see Manifest * @see java.util.zip.ZipFile * @see java.util.jar.JarEntry * @since 1.2 */ public class JarFile extends ZipFile { private SoftReference<Manifest> manRef; private JarEntry manEntry; private JarVerifier jv; private boolean jvInitialized; private boolean verify; private boolean computedHasClassPathAttribute; private boolean hasClassPathAttribute; // Set up JavaUtilJarAccess in SharedSecrets static { SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl()); } /** {@collect.stats} * {@description.open} * The JAR manifest file name. * {@description.close} */ public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; /** {@collect.stats} * {@description.open} * Creates a new <code>JarFile</code> to read from the specified * file <code>name</code>. The <code>JarFile</code> will be verified if * it is signed. * {@description.close} * @param name the name of the jar file to be opened for reading * @throws IOException if an I/O error has occurred * @throws SecurityException if access to the file is denied * by the SecurityManager */ public JarFile(String name) throws IOException { this(new File(name), true, ZipFile.OPEN_READ); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarFile</code> to read from the specified * file <code>name</code>. * {@description.close} * @param name the name of the jar file to be opened for reading * @param verify whether or not to verify the jar file if * it is signed. * @throws IOException if an I/O error has occurred * @throws SecurityException if access to the file is denied * by the SecurityManager */ public JarFile(String name, boolean verify) throws IOException { this(new File(name), verify, ZipFile.OPEN_READ); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarFile</code> to read from the specified * <code>File</code> object. The <code>JarFile</code> will be verified if * it is signed. * {@description.close} * @param file the jar file to be opened for reading * @throws IOException if an I/O error has occurred * @throws SecurityException if access to the file is denied * by the SecurityManager */ public JarFile(File file) throws IOException { this(file, true, ZipFile.OPEN_READ); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarFile</code> to read from the specified * <code>File</code> object. * {@description.close} * @param file the jar file to be opened for reading * @param verify whether or not to verify the jar file if * it is signed. * @throws IOException if an I/O error has occurred * @throws SecurityException if access to the file is denied * by the SecurityManager. */ public JarFile(File file, boolean verify) throws IOException { this(file, verify, ZipFile.OPEN_READ); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarFile</code> to read from the specified * <code>File</code> object in the specified mode. The mode argument * must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>. * {@description.close} * * @param file the jar file to be opened for reading * @param verify whether or not to verify the jar file if * it is signed. * @param mode the mode in which the file is to be opened * @throws IOException if an I/O error has occurred * @throws IllegalArgumentException * if the <tt>mode</tt> argument is invalid * @throws SecurityException if access to the file is denied * by the SecurityManager * @since 1.3 */ public JarFile(File file, boolean verify, int mode) throws IOException { super(file, mode); this.verify = verify; } /** {@collect.stats} * {@description.open} * Returns the jar file manifest, or <code>null</code> if none. * {@description.close} * * @return the jar file manifest, or <code>null</code> if none * * @throws IllegalStateException * may be thrown if the jar file has been closed */ public Manifest getManifest() throws IOException { return getManifestFromReference(); } private Manifest getManifestFromReference() throws IOException { Manifest man = manRef != null ? manRef.get() : null; if (man == null) { JarEntry manEntry = getManEntry(); // If found then load the manifest if (manEntry != null) { if (verify) { byte[] b = getBytes(manEntry); man = new Manifest(new ByteArrayInputStream(b)); if (!jvInitialized) { jv = new JarVerifier(b); } } else { man = new Manifest(super.getInputStream(manEntry)); } manRef = new SoftReference(man); } } return man; } private native String[] getMetaInfEntryNames(); /** {@collect.stats} * {@description.open} * Returns the <code>JarEntry</code> for the given entry name or * <code>null</code> if not found. * {@description.close} * * @param name the jar file entry name * @return the <code>JarEntry</code> for the given entry name or * <code>null</code> if not found. * * @throws IllegalStateException * may be thrown if the jar file has been closed * * @see java.util.jar.JarEntry */ public JarEntry getJarEntry(String name) { return (JarEntry)getEntry(name); } /** {@collect.stats} * {@description.open} * Returns the <code>ZipEntry</code> for the given entry name or * <code>null</code> if not found. * {@description.close} * * @param name the jar file entry name * @return the <code>ZipEntry</code> for the given entry name or * <code>null</code> if not found * * @throws IllegalStateException * may be thrown if the jar file has been closed * * @see java.util.zip.ZipEntry */ public ZipEntry getEntry(String name) { ZipEntry ze = super.getEntry(name); if (ze != null) { return new JarFileEntry(ze); } return null; } /** {@collect.stats} * {@description.open} * Returns an enumeration of the zip file entries. * {@description.close} */ public Enumeration<JarEntry> entries() { final Enumeration enum_ = super.entries(); return new Enumeration<JarEntry>() { public boolean hasMoreElements() { return enum_.hasMoreElements(); } public JarFileEntry nextElement() { ZipEntry ze = (ZipEntry)enum_.nextElement(); return new JarFileEntry(ze); } }; } private class JarFileEntry extends JarEntry { JarFileEntry(ZipEntry ze) { super(ze); } public Attributes getAttributes() throws IOException { Manifest man = JarFile.this.getManifest(); if (man != null) { return man.getAttributes(getName()); } else { return null; } } public Certificate[] getCertificates() { try { maybeInstantiateVerifier(); } catch (IOException e) { throw new RuntimeException(e); } if (certs == null && jv != null) { certs = jv.getCerts(getName()); } return certs == null ? null : certs.clone(); } public CodeSigner[] getCodeSigners() { try { maybeInstantiateVerifier(); } catch (IOException e) { throw new RuntimeException(e); } if (signers == null && jv != null) { signers = jv.getCodeSigners(getName()); } return signers == null ? null : signers.clone(); } } /* * Ensures that the JarVerifier has been created if one is * necessary (i.e., the jar appears to be signed.) This is done as * a quick check to avoid processing of the manifest for unsigned * jars. */ private void maybeInstantiateVerifier() throws IOException { if (jv != null) { return; } if (verify) { String[] names = getMetaInfEntryNames(); if (names != null) { for (int i = 0; i < names.length; i++) { String name = names[i].toUpperCase(Locale.ENGLISH); if (name.endsWith(".DSA") || name.endsWith(".RSA") || name.endsWith(".SF")) { // Assume since we found a signature-related file // that the jar is signed and that we therefore // need a JarVerifier and Manifest getManifest(); return; } } } // No signature-related files; don't instantiate a // verifier verify = false; } } /* * Initializes the verifier object by reading all the manifest * entries and passing them to the verifier. */ private void initializeVerifier() { ManifestEntryVerifier mev = null; // Verify "META-INF/" entries... try { String[] names = getMetaInfEntryNames(); if (names != null) { for (int i = 0; i < names.length; i++) { JarEntry e = getJarEntry(names[i]); if (!e.isDirectory()) { if (mev == null) { mev = new ManifestEntryVerifier (getManifestFromReference()); } byte[] b = getBytes(e); if (b != null && b.length > 0) { jv.beginEntry(e, mev); jv.update(b.length, b, 0, b.length, mev); jv.update(-1, null, 0, 0, mev); } } } } } catch (IOException ex) { // if we had an error parsing any blocks, just // treat the jar file as being unsigned jv = null; verify = false; } // if after initializing the verifier we have nothing // signed, we null it out. if (jv != null) { jv.doneWithMeta(); if (JarVerifier.debug != null) { JarVerifier.debug.println("done with meta!"); } if (jv.nothingToVerify()) { if (JarVerifier.debug != null) { JarVerifier.debug.println("nothing to verify!"); } jv = null; verify = false; } } } /* * Reads all the bytes for a given entry. Used to process the * META-INF files. */ private byte[] getBytes(ZipEntry ze) throws IOException { byte[] b = new byte[(int)ze.getSize()]; DataInputStream is = new DataInputStream(super.getInputStream(ze)); is.readFully(b, 0, b.length); is.close(); return b; } /** {@collect.stats} * {@description.open} * Returns an input stream for reading the contents of the specified * zip file entry. * {@description.close} * @param ze the zip file entry * @return an input stream for reading the contents of the specified * zip file entry * @throws ZipException if a zip file format error has occurred * @throws IOException if an I/O error has occurred * @throws SecurityException if any of the jar file entries * are incorrectly signed. * @throws IllegalStateException * may be thrown if the jar file has been closed */ public synchronized InputStream getInputStream(ZipEntry ze) throws IOException { maybeInstantiateVerifier(); if (jv == null) { return super.getInputStream(ze); } if (!jvInitialized) { initializeVerifier(); jvInitialized = true; // could be set to null after a call to // initializeVerifier if we have nothing to // verify if (jv == null) return super.getInputStream(ze); } // wrap a verifier stream around the real stream return new JarVerifier.VerifierStream( getManifestFromReference(), ze instanceof JarFileEntry ? (JarEntry) ze : getJarEntry(ze.getName()), super.getInputStream(ze), jv); } // Statics for hand-coded Boyer-Moore search in hasClassPathAttribute() // The bad character shift for "class-path" private static int[] lastOcc; // The good suffix shift for "class-path" private static int[] optoSft; // Initialize the shift arrays to search for "class-path" private static char[] src = {'c','l','a','s','s','-','p','a','t','h'}; static { lastOcc = new int[128]; optoSft = new int[10]; lastOcc[(int)'c']=1; lastOcc[(int)'l']=2; lastOcc[(int)'s']=5; lastOcc[(int)'-']=6; lastOcc[(int)'p']=7; lastOcc[(int)'a']=8; lastOcc[(int)'t']=9; lastOcc[(int)'h']=10; for (int i=0; i<9; i++) optoSft[i]=10; optoSft[9]=1; } private JarEntry getManEntry() { if (manEntry == null) { // First look up manifest entry using standard name manEntry = getJarEntry(MANIFEST_NAME); if (manEntry == null) { // If not found, then iterate through all the "META-INF/" // entries to find a match. String[] names = getMetaInfEntryNames(); if (names != null) { for (int i = 0; i < names.length; i++) { if (MANIFEST_NAME.equals( names[i].toUpperCase(Locale.ENGLISH))) { manEntry = getJarEntry(names[i]); break; } } } } } return manEntry; } // Returns true iff this jar file has a manifest with a class path // attribute. Returns false if there is no manifest or the manifest // does not contain a "Class-Path" attribute. Currently exported to // core libraries via sun.misc.SharedSecrets. boolean hasClassPathAttribute() throws IOException { if (computedHasClassPathAttribute) { return hasClassPathAttribute; } hasClassPathAttribute = false; if (!isKnownToNotHaveClassPathAttribute()) { JarEntry manEntry = getManEntry(); if (manEntry != null) { byte[] b = new byte[(int)manEntry.getSize()]; DataInputStream dis = new DataInputStream( super.getInputStream(manEntry)); dis.readFully(b, 0, b.length); dis.close(); int last = b.length - src.length; int i = 0; next: while (i<=last) { for (int j=9; j>=0; j--) { char c = (char) b[i+j]; c = (((c-'A')|('Z'-c)) >= 0) ? (char)(c + 32) : c; if (c != src[j]) { i += Math.max(j + 1 - lastOcc[c&0x7F], optoSft[j]); continue next; } } hasClassPathAttribute = true; break; } } } computedHasClassPathAttribute = true; return hasClassPathAttribute; } private static String javaHome; private static String[] jarNames; private boolean isKnownToNotHaveClassPathAttribute() { // Optimize away even scanning of manifest for jar files we // deliver which don't have a class-path attribute. If one of // these jars is changed to include such an attribute this code // must be changed. if (javaHome == null) { javaHome = AccessController.doPrivileged( new GetPropertyAction("java.home")); } if (jarNames == null) { String[] names = new String[10]; String fileSep = File.separator; int i = 0; names[i++] = fileSep + "rt.jar"; names[i++] = fileSep + "sunrsasign.jar"; names[i++] = fileSep + "jsse.jar"; names[i++] = fileSep + "jce.jar"; names[i++] = fileSep + "charsets.jar"; names[i++] = fileSep + "dnsns.jar"; names[i++] = fileSep + "ldapsec.jar"; names[i++] = fileSep + "localedata.jar"; names[i++] = fileSep + "sunjce_provider.jar"; names[i++] = fileSep + "sunpkcs11.jar"; jarNames = names; } String name = getName(); String localJavaHome = javaHome; if (name.startsWith(localJavaHome)) { String[] names = jarNames; for (int i = 0; i < names.length; i++) { if (name.endsWith(names[i])) { return true; } } } return false; } }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; /** {@collect.stats} * {@description.open} * Signals that an error of some sort has occurred while reading from * or writing to a JAR file. * {@description.close} * * @author David Connelly * @since 1.2 */ public class JarException extends java.util.zip.ZipException { /** {@collect.stats} * {@description.open} * Constructs a JarException with no detail message. * {@description.close} */ public JarException() { } /** {@collect.stats} * {@description.open} * Constructs a JarException with the specified detail message. * {@description.close} * @param s the detail message */ public JarException(String s) { super(s); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.util.zip.*; import java.io.*; import sun.security.util.ManifestEntryVerifier; /** {@collect.stats} * {@description.open} * The <code>JarInputStream</code> class is used to read the contents of * a JAR file from any input stream. It extends the class * <code>java.util.zip.ZipInputStream</code> with support for reading * an optional <code>Manifest</code> entry. The <code>Manifest</code> * can be used to store meta-information about the JAR file and its entries. * {@description.close} * * @author David Connelly * @see Manifest * @see java.util.zip.ZipInputStream * @since 1.2 */ public class JarInputStream extends ZipInputStream { private Manifest man; private JarEntry first; private JarVerifier jv; private ManifestEntryVerifier mev; /** {@collect.stats} * {@description.open} * Creates a new <code>JarInputStream</code> and reads the optional * manifest. If a manifest is present, also attempts to verify * the signatures if the JarInputStream is signed. * {@description.close} * @param in the actual input stream * @exception IOException if an I/O error has occurred */ public JarInputStream(InputStream in) throws IOException { this(in, true); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarInputStream</code> and reads the optional * manifest. If a manifest is present and verify is true, also attempts * to verify the signatures if the JarInputStream is signed. * {@description.close} * * @param in the actual input stream * @param verify whether or not to verify the JarInputStream if * it is signed. * @exception IOException if an I/O error has occurred */ public JarInputStream(InputStream in, boolean verify) throws IOException { super(in); JarEntry e = (JarEntry)super.getNextEntry(); if (e != null && e.getName().equalsIgnoreCase("META-INF/")) e = (JarEntry)super.getNextEntry(); if (e != null && JarFile.MANIFEST_NAME.equalsIgnoreCase(e.getName())) { man = new Manifest(); byte bytes[] = getBytes(new BufferedInputStream(this)); man.read(new ByteArrayInputStream(bytes)); //man.read(new BufferedInputStream(this)); closeEntry(); if (verify) { jv = new JarVerifier(bytes); mev = new ManifestEntryVerifier(man); } first = getNextJarEntry(); } else { first = e; } } private byte[] getBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); int n; baos.reset(); while ((n = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, n); } return baos.toByteArray(); } /** {@collect.stats} * {@description.open} * Returns the <code>Manifest</code> for this JAR file, or * <code>null</code> if none. * {@description.close} * * @return the <code>Manifest</code> for this JAR file, or * <code>null</code> if none. */ public Manifest getManifest() { return man; } /** {@collect.stats} * {@description.open} * Reads the next ZIP file entry and positions the stream at the * beginning of the entry data. If verification has been enabled, * any invalid signature detected while positioning the stream for * the next entry will result in an exception. * {@description.close} * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred * @exception SecurityException if any of the jar file entries * are incorrectly signed. */ public ZipEntry getNextEntry() throws IOException { JarEntry e; if (first == null) { e = (JarEntry)super.getNextEntry(); } else { e = first; first = null; } if (jv != null && e != null) { // At this point, we might have parsed all the meta-inf // entries and have nothing to verify. If we have // nothing to verify, get rid of the JarVerifier object. if (jv.nothingToVerify() == true) { jv = null; mev = null; } else { jv.beginEntry(e, mev); } } return e; } /** {@collect.stats} * {@description.open} * Reads the next JAR file entry and positions the stream at the * beginning of the entry data. If verification has been enabled, * any invalid signature detected while positioning the stream for * the next entry will result in an exception. * {@description.close} * @return the next JAR file entry, or null if there are no more entries * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred * @exception SecurityException if any of the jar file entries * are incorrectly signed. */ public JarEntry getNextJarEntry() throws IOException { return (JarEntry)getNextEntry(); } /** {@collect.stats} * {@description.open} * Reads from the current JAR file entry into an array of bytes. * If <code>len</code> is not zero, the method * blocks until some input is available; otherwise, no * bytes are read and <code>0</code> is returned. * If verification has been enabled, any invalid signature * on the current entry will be reported at some point before the * end of the entry is reached. * {@description.close} * @param b the buffer into which the data is read * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes to read * @return the actual number of bytes read, or -1 if the end of the * entry is reached * @exception NullPointerException If <code>b</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>b.length - off</code> * @exception ZipException if a ZIP file error has occurred * @exception IOException if an I/O error has occurred * @exception SecurityException if any of the jar file entries * are incorrectly signed. */ public int read(byte[] b, int off, int len) throws IOException { int n; if (first == null) { n = super.read(b, off, len); } else { n = -1; } if (jv != null) { jv.update(n, b, off, len, mev); } return n; } /** {@collect.stats} * {@description.open} * Creates a new <code>JarEntry</code> (<code>ZipEntry</code>) for the * specified JAR file entry name. The manifest attributes of * the specified JAR file entry name will be copied to the new * <CODE>JarEntry</CODE>. * {@description.close} * * @param name the name of the JAR/ZIP file entry * @return the <code>JarEntry</code> object just created */ protected ZipEntry createZipEntry(String name) { JarEntry e = new JarEntry(name); if (man != null) { e.attr = man.getAttributes(name); } return e; } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.IOException; import java.util.zip.ZipEntry; import java.security.CodeSigner; import java.security.cert.Certificate; /** {@collect.stats} * {@description.open} * This class is used to represent a JAR file entry. * {@description.close} */ public class JarEntry extends ZipEntry { Attributes attr; Certificate[] certs; CodeSigner[] signers; /** {@collect.stats} * {@description.open} * Creates a new <code>JarEntry</code> for the specified JAR file * entry name. * {@description.close} * * @param name the JAR file entry name * @exception NullPointerException if the entry name is <code>null</code> * @exception IllegalArgumentException if the entry name is longer than * 0xFFFF bytes. */ public JarEntry(String name) { super(name); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarEntry</code> with fields taken from the * specified <code>ZipEntry</code> object. * {@description.close} * @param ze the <code>ZipEntry</code> object to create the * <code>JarEntry</code> from */ public JarEntry(ZipEntry ze) { super(ze); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarEntry</code> with fields taken from the * specified <code>JarEntry</code> object. * {@description.close} * * @param je the <code>JarEntry</code> to copy */ public JarEntry(JarEntry je) { this((ZipEntry)je); this.attr = je.attr; this.certs = je.certs; this.signers = je.signers; } /** {@collect.stats} * {@description.open} * Returns the <code>Manifest</code> <code>Attributes</code> for this * entry, or <code>null</code> if none. * {@description.close} * * @return the <code>Manifest</code> <code>Attributes</code> for this * entry, or <code>null</code> if none */ public Attributes getAttributes() throws IOException { return attr; } /** {@collect.stats} * {@description.open} * Returns the <code>Certificate</code> objects for this entry, or * <code>null</code> if none. * {@description.close} * {@property.open formal:java.util.jar.JarEntry_GetCertificatesOnce} * This method can only be called once * the <code>JarEntry</code> has been completely verified by reading * from the entry input stream until the end of the stream has been * reached. Otherwise, this method will return <code>null</code>. * {@property.close} * * {@description.open} * <p>The returned certificate array comprises all the signer certificates * that were used to verify this entry. Each signer certificate is * followed by its supporting certificate chain (which may be empty). * Each signer certificate and its supporting certificate chain are ordered * bottom-to-top (i.e., with the signer certificate first and the (root) * certificate authority last). * {@description.close} * * @return the <code>Certificate</code> objects for this entry, or * <code>null</code> if none. */ public Certificate[] getCertificates() { return certs == null ? null : certs.clone(); } /** {@collect.stats} * {@description.open} * Returns the <code>CodeSigner</code> objects for this entry, or * <code>null</code> if none. * {@description.close} * {@property.open formal:java.util.jar.JarEntry_GetCodeSignersOnce} * This method can only be called once * the <code>JarEntry</code> has been completely verified by reading * from the entry input stream until the end of the stream has been * reached. Otherwise, this method will return <code>null</code>. * {@property.close} * * {@description.open} * <p>The returned array comprises all the code signers that have signed * this entry. * {@description.close} * * @return the <code>CodeSigner</code> objects for this entry, or * <code>null</code> if none. * * @since 1.5 */ public CodeSigner[] getCodeSigners() { return signers == null ? null : signers.clone(); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Collection; import java.util.AbstractSet; import java.util.Iterator; import java.util.logging.Logger; import java.util.Comparator; import sun.misc.ASCIICaseInsensitiveComparator; /** {@collect.stats} * {@description.open} * The Attributes class maps Manifest attribute names to associated string * values. Valid attribute names are case-insensitive, are restricted to * the ASCII characters in the set [0-9a-zA-Z_-], and cannot exceed 70 * characters in length. Attribute values can contain any characters and * will be UTF8-encoded when written to the output stream. See the * <a href="../../../../technotes/guides/jar/jar.html">JAR File Specification</a> * for more information about valid attribute names and values. * {@description.close} * * @author David Connelly * @see Manifest * @since 1.2 */ public class Attributes implements Map<Object,Object>, Cloneable { /** {@collect.stats} * {@description.open} * The attribute name-value mappings. * {@description.close} */ protected Map<Object,Object> map; /** {@collect.stats} * {@description.open} * Constructs a new, empty Attributes object with default size. * {@description.close} */ public Attributes() { this(11); } /** {@collect.stats} * {@description.open} * Constructs a new, empty Attributes object with the specified * initial size. * {@description.close} * * @param size the initial number of attributes */ public Attributes(int size) { map = new HashMap(size); } /** {@collect.stats} * {@description.open} * Constructs a new Attributes object with the same attribute name-value * mappings as in the specified Attributes. * {@description.close} * * @param attr the specified Attributes */ public Attributes(Attributes attr) { map = new HashMap(attr); } /** {@collect.stats} * {@description.open} * Returns the value of the specified attribute name, or null if the * attribute name was not found. * {@description.close} * * @param name the attribute name * @return the value of the specified attribute name, or null if * not found. */ public Object get(Object name) { return map.get(name); } /** {@collect.stats} * {@description.open} * Returns the value of the specified attribute name, specified as * a string, or null if the attribute was not found. The attribute * name is case-insensitive. * <p> * This method is defined as: * <pre> * return (String)get(new Attributes.Name((String)name)); * </pre> * {@description.close} * * @param name the attribute name as a string * @return the String value of the specified attribute name, or null if * not found. * @throws IllegalArgumentException if the attribute name is invalid */ public String getValue(String name) { return (String)get(new Attributes.Name(name)); } /** {@collect.stats} * {@description.open} * Returns the value of the specified Attributes.Name, or null if the * attribute was not found. * <p> * This method is defined as: * <pre> * return (String)get(name); * </pre> * {@description.close} * * @param name the Attributes.Name object * @return the String value of the specified Attribute.Name, or null if * not found. */ public String getValue(Name name) { return (String)get(name); } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified attribute name * (key) in this Map. If the Map previously contained a mapping for * the attribute name, the old value is replaced. * {@description.close} * * @param name the attribute name * @param value the attribute value * @return the previous value of the attribute, or null if none * @exception ClassCastException if the name is not a Attributes.Name * or the value is not a String */ public Object put(Object name, Object value) { return map.put((Attributes.Name)name, (String)value); } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified attribute name, * specified as a String. The attributes name is case-insensitive. * If the Map previously contained a mapping for the attribute name, * the old value is replaced. * <p> * This method is defined as: * <pre> * return (String)put(new Attributes.Name(name), value); * </pre> * {@description.close} * * @param name the attribute name as a string * @param value the attribute value * @return the previous value of the attribute, or null if none * @exception IllegalArgumentException if the attribute name is invalid */ public String putValue(String name, String value) { return (String)put(new Name(name), value); } /** {@collect.stats} * {@description.open} * Removes the attribute with the specified name (key) from this Map. * Returns the previous attribute value, or null if none. * {@description.close} * * @param name attribute name * @return the previous value of the attribute, or null if none */ public Object remove(Object name) { return map.remove(name); } /** {@collect.stats} * {@description.open} * Returns true if this Map maps one or more attribute names (keys) * to the specified value. * {@description.close} * * @param value the attribute value * @return true if this Map maps one or more attribute names to * the specified value */ public boolean containsValue(Object value) { return map.containsValue(value); } /** {@collect.stats} * {@description.open} * Returns true if this Map contains the specified attribute name (key). * {@description.close} * * @param name the attribute name * @return true if this Map contains the specified attribute name */ public boolean containsKey(Object name) { return map.containsKey(name); } /** {@collect.stats} * {@description.open} * Copies all of the attribute name-value mappings from the specified * Attributes to this Map. Duplicate mappings will be replaced. * {@description.close} * * @param attr the Attributes to be stored in this map * @exception ClassCastException if attr is not an Attributes */ public void putAll(Map<?,?> attr) { // ## javac bug? if (!Attributes.class.isInstance(attr)) throw new ClassCastException(); for (Map.Entry<?,?> me : (attr).entrySet()) put(me.getKey(), me.getValue()); } /** {@collect.stats} * {@description.open} * Removes all attributes from this Map. * {@description.close} */ public void clear() { map.clear(); } /** {@collect.stats} * {@description.open} * Returns the number of attributes in this Map. * {@description.close} */ public int size() { return map.size(); } /** {@collect.stats} * {@description.open} * Returns true if this Map contains no attributes. * {@description.close} */ public boolean isEmpty() { return map.isEmpty(); } /** {@collect.stats} * {@description.open} * Returns a Set view of the attribute names (keys) contained in this Map. * {@description.close} */ public Set<Object> keySet() { return map.keySet(); } /** {@collect.stats} * {@description.open} * Returns a Collection view of the attribute values contained in this Map. * {@description.close} */ public Collection<Object> values() { return map.values(); } /** {@collect.stats} * {@description.open} * Returns a Collection view of the attribute name-value mappings * contained in this Map. * {@description.close} */ public Set<Map.Entry<Object,Object>> entrySet() { return map.entrySet(); } /** {@collect.stats} * {@description.open} * Compares the specified Attributes object with this Map for equality. * Returns true if the given object is also an instance of Attributes * and the two Attributes objects represent the same mappings. * {@description.close} * * @param o the Object to be compared * @return true if the specified Object is equal to this Map */ public boolean equals(Object o) { return map.equals(o); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this Map. * {@description.close} */ public int hashCode() { return map.hashCode(); } /** {@collect.stats} * {@description.open} * Returns a copy of the Attributes, implemented as follows: * <pre> * public Object clone() { return new Attributes(this); } * </pre> * Since the attribute names and values are themselves immutable, * the Attributes returned can be safely modified without affecting * the original. * {@description.close} */ public Object clone() { return new Attributes(this); } /* * Writes the current attributes to the specified data output stream. * XXX Need to handle UTF8 values and break up lines longer than 72 bytes */ void write(DataOutputStream os) throws IOException { Iterator it = entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry)it.next(); StringBuffer buffer = new StringBuffer( ((Name)e.getKey()).toString()); buffer.append(": "); String value = (String)e.getValue(); if (value != null) { byte[] vb = value.getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); } buffer.append(value); buffer.append("\r\n"); Manifest.make72Safe(buffer); os.writeBytes(buffer.toString()); } os.writeBytes("\r\n"); } /* * Writes the current attributes to the specified data output stream, * make sure to write out the MANIFEST_VERSION or SIGNATURE_VERSION * attributes first. * * XXX Need to handle UTF8 values and break up lines longer than 72 bytes */ void writeMain(DataOutputStream out) throws IOException { // write out the *-Version header first, if it exists String vername = Name.MANIFEST_VERSION.toString(); String version = getValue(vername); if (version == null) { vername = Name.SIGNATURE_VERSION.toString(); version = getValue(vername); } if (version != null) { out.writeBytes(vername+": "+version+"\r\n"); } // write out all attributes except for the version // we wrote out earlier Iterator it = entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry)it.next(); String name = ((Name)e.getKey()).toString(); if ((version != null) && ! (name.equalsIgnoreCase(vername))) { StringBuffer buffer = new StringBuffer(name); buffer.append(": "); String value = (String)e.getValue(); if (value != null) { byte[] vb = value.getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); } buffer.append(value); buffer.append("\r\n"); Manifest.make72Safe(buffer); out.writeBytes(buffer.toString()); } } out.writeBytes("\r\n"); } /* * Reads attributes from the specified input stream. * XXX Need to handle UTF8 values. */ void read(Manifest.FastInputStream is, byte[] lbuf) throws IOException { String name = null, value = null; byte[] lastline = null; int len; while ((len = is.readLine(lbuf)) != -1) { boolean lineContinued = false; if (lbuf[--len] != '\n') { throw new IOException("line too long"); } if (len > 0 && lbuf[len-1] == '\r') { --len; } if (len == 0) { break; } int i = 0; if (lbuf[0] == ' ') { // continuation of previous line if (name == null) { throw new IOException("misplaced continuation line"); } lineContinued = true; byte[] buf = new byte[lastline.length + len - 1]; System.arraycopy(lastline, 0, buf, 0, lastline.length); System.arraycopy(lbuf, 1, buf, lastline.length, len - 1); if (is.peek() == ' ') { lastline = buf; continue; } value = new String(buf, 0, buf.length, "UTF8"); lastline = null; } else { while (lbuf[i++] != ':') { if (i >= len) { throw new IOException("invalid header field"); } } if (lbuf[i++] != ' ') { throw new IOException("invalid header field"); } name = new String(lbuf, 0, 0, i - 2); if (is.peek() == ' ') { lastline = new byte[len - i]; System.arraycopy(lbuf, i, lastline, 0, len - i); continue; } value = new String(lbuf, i, len - i, "UTF8"); } try { if ((putValue(name, value) != null) && (!lineContinued)) { Logger.getLogger("java.util.jar").warning( "Duplicate name in Manifest: " + name + ".\n" + "Ensure that the manifest does not " + "have duplicate entries, and\n" + "that blank lines separate " + "individual sections in both your\n" + "manifest and in the META-INF/MANIFEST.MF " + "entry in the jar file."); } } catch (IllegalArgumentException e) { throw new IOException("invalid header field name: " + name); } } } /** {@collect.stats} * {@description.open} * The Attributes.Name class represents an attribute name stored in * this Map. Valid attribute names are case-insensitive, are restricted * to the ASCII characters in the set [0-9a-zA-Z_-], and cannot exceed * 70 characters in length. Attribute values can contain any characters * and will be UTF8-encoded when written to the output stream. See the * <a href="../../../../technotes/guides/jar/jar.html">JAR File Specification</a> * for more information about valid attribute names and values. * {@description.close} */ public static class Name { private String name; private int hashCode = -1; /** {@collect.stats} * {@description.open} * Constructs a new attribute name using the given string name. * {@description.close} * * @param name the attribute string name * @exception IllegalArgumentException if the attribute name was * invalid * @exception NullPointerException if the attribute name was null */ public Name(String name) { if (name == null) { throw new NullPointerException("name"); } if (!isValid(name)) { throw new IllegalArgumentException(name); } this.name = name.intern(); } private static boolean isValid(String name) { int len = name.length(); if (len > 70 || len == 0) { return false; } for (int i = 0; i < len; i++) { if (!isValid(name.charAt(i))) { return false; } } return true; } private static boolean isValid(char c) { return isAlpha(c) || isDigit(c) || c == '_' || c == '-'; } private static boolean isAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } private static boolean isDigit(char c) { return c >= '0' && c <= '9'; } /** {@collect.stats} * {@description.open} * Compares this attribute name to another for equality. * {@description.close} * @param o the object to compare * @return true if this attribute name is equal to the * specified attribute object */ public boolean equals(Object o) { if (o instanceof Name) { Comparator c = ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER; return c.compare(name, ((Name)o).name) == 0; } else { return false; } } /** {@collect.stats} * {@description.open} * Computes the hash value for this attribute name. * {@description.close} */ public int hashCode() { if (hashCode == -1) { hashCode = ASCIICaseInsensitiveComparator.lowerCaseHashCode(name); } return hashCode; } /** {@collect.stats} * {@description.open} * Returns the attribute name as a String. * {@description.close} */ public String toString() { return name; } /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Manifest-Version</code> * manifest attribute. This attribute indicates the version number * of the manifest standard to which a JAR file's manifest conforms. * {@description.close} * @see <a href="../../../../technotes/guides/jar/jar.html#JAR Manifest"> * Manifest and Signature Specification</a> */ public static final Name MANIFEST_VERSION = new Name("Manifest-Version"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Signature-Version</code> * manifest attribute used when signing JAR files. * {@description.close} * @see <a href="../../../../technotes/guides/jar/jar.html#JAR Manifest"> * Manifest and Signature Specification</a> */ public static final Name SIGNATURE_VERSION = new Name("Signature-Version"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Content-Type</code> * manifest attribute. * {@description.close} */ public static final Name CONTENT_TYPE = new Name("Content-Type"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Class-Path</code> * manifest attribute. Bundled extensions can use this attribute * to find other JAR files containing needed classes. * {@description.close} * @see <a href="../../../../technotes/guides/extensions/spec.html#bundled"> * Extensions Specification</a> */ public static final Name CLASS_PATH = new Name("Class-Path"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Main-Class</code> manifest * attribute used for launching applications packaged in JAR files. * The <code>Main-Class</code> attribute is used in conjunction * with the <code>-jar</code> command-line option of the * <tt>java</tt> application launcher. * {@description.close} */ public static final Name MAIN_CLASS = new Name("Main-Class"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Sealed</code> manifest attribute * used for sealing. * {@description.close} * @see <a href="../../../../technotes/guides/extensions/spec.html#sealing"> * Extension Sealing</a> */ public static final Name SEALED = new Name("Sealed"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Extension-List</code> manifest attribute * used for declaring dependencies on installed extensions. * {@description.close} * @see <a href="../../../../technotes/guides/extensions/spec.html#dependency"> * Installed extension dependency</a> */ public static final Name EXTENSION_LIST = new Name("Extension-List"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Extension-Name</code> manifest attribute * used for declaring dependencies on installed extensions. * {@description.close} * @see <a href="../../../../technotes/guides/extensions/spec.html#dependency"> * Installed extension dependency</a> */ public static final Name EXTENSION_NAME = new Name("Extension-Name"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Extension-Name</code> manifest attribute * used for declaring dependencies on installed extensions. * {@description.close} * @see <a href="../../../../technotes/guides/extensions/spec.html#dependency"> * Installed extension dependency</a> */ public static final Name EXTENSION_INSTALLATION = new Name("Extension-Installation"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Implementation-Title</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name IMPLEMENTATION_TITLE = new Name("Implementation-Title"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Implementation-Version</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name IMPLEMENTATION_VERSION = new Name("Implementation-Version"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Implementation-Vendor</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name IMPLEMENTATION_VENDOR = new Name("Implementation-Vendor"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Implementation-Vendor-Id</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name IMPLEMENTATION_VENDOR_ID = new Name("Implementation-Vendor-Id"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Implementation-Vendor-URL</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name IMPLEMENTATION_URL = new Name("Implementation-URL"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Specification-Title</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name SPECIFICATION_TITLE = new Name("Specification-Title"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Specification-Version</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name SPECIFICATION_VERSION = new Name("Specification-Version"); /** {@collect.stats} * {@description.open} * <code>Name</code> object for <code>Specification-Vendor</code> * manifest attribute used for package versioning. * {@description.close} * @see <a href="../../../../technotes/guides/versioning/spec/versioning2.html#wp90779"> * Java Product Versioning Specification</a> */ public static final Name SPECIFICATION_VENDOR = new Name("Specification-Vendor"); } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.*; import java.util.*; import java.util.zip.*; import java.security.*; import java.security.cert.CertificateException; import sun.security.util.ManifestDigester; import sun.security.util.ManifestEntryVerifier; import sun.security.util.SignatureFileVerifier; import sun.security.util.Debug; /** {@collect.stats} * * @author Roland Schemers */ class JarVerifier { /* Are we debugging ? */ static final Debug debug = Debug.getInstance("jar"); /* a table mapping names to code signers, for jar entries that have had their actual hashes verified */ private Hashtable verifiedSigners; /* a table mapping names to code signers, for jar entries that have passed the .SF/.DSA -> MANIFEST check */ private Hashtable sigFileSigners; /* a hash table to hold .SF bytes */ private Hashtable sigFileData; /** {@collect.stats} * {@description.open} * "queue" of pending PKCS7 blocks that we couldn't parse * until we parsed the .SF file * {@description.close} */ private ArrayList pendingBlocks; /* cache of CodeSigner objects */ private ArrayList signerCache; /* Are we parsing a block? */ private boolean parsingBlockOrSF = false; /* Are we done parsing META-INF entries? */ private boolean parsingMeta = true; /* Are there are files to verify? */ private boolean anyToVerify = true; /* The output stream to use when keeping track of files we are interested in */ private ByteArrayOutputStream baos; /** {@collect.stats} * {@description.open} * The ManifestDigester object * {@description.close} */ private ManifestDigester manDig; /** {@collect.stats} * {@description.open} * the bytes for the manDig object * {@description.close} */ byte manifestRawBytes[] = null; public JarVerifier(byte rawBytes[]) { manifestRawBytes = rawBytes; sigFileSigners = new Hashtable(); verifiedSigners = new Hashtable(); sigFileData = new Hashtable(11); pendingBlocks = new ArrayList(); baos = new ByteArrayOutputStream(); } /** {@collect.stats} * {@description.open} * This method scans to see which entry we're parsing and * keeps various state information depending on what type of * file is being parsed. * {@description.close} */ public void beginEntry(JarEntry je, ManifestEntryVerifier mev) throws IOException { if (je == null) return; if (debug != null) { debug.println("beginEntry "+je.getName()); } String name = je.getName(); /* * Assumptions: * 1. The manifest should be the first entry in the META-INF directory. * 2. The .SF/.DSA files follow the manifest, before any normal entries * 3. Any of the following will throw a SecurityException: * a. digest mismatch between a manifest section and * the SF section. * b. digest mismatch between the actual jar entry and the manifest */ if (parsingMeta) { String uname = name.toUpperCase(Locale.ENGLISH); if ((uname.startsWith("META-INF/") || uname.startsWith("/META-INF/"))) { if (je.isDirectory()) { mev.setEntry(null, je); return; } if (SignatureFileVerifier.isBlockOrSF(uname)) { /* We parse only DSA or RSA PKCS7 blocks. */ parsingBlockOrSF = true; baos.reset(); mev.setEntry(null, je); } return; } } if (parsingMeta) { doneWithMeta(); } if (je.isDirectory()) { mev.setEntry(null, je); return; } // be liberal in what you accept. If the name starts with ./, remove // it as we internally canonicalize it with out the ./. if (name.startsWith("./")) name = name.substring(2); // be liberal in what you accept. If the name starts with /, remove // it as we internally canonicalize it with out the /. if (name.startsWith("/")) name = name.substring(1); // only set the jev object for entries that have a signature if (sigFileSigners.get(name) != null) { mev.setEntry(name, je); return; } // don't compute the digest for this entry mev.setEntry(null, je); return; } /** {@collect.stats} * {@description.open} * update a single byte. * {@description.close} */ public void update(int b, ManifestEntryVerifier mev) throws IOException { if (b != -1) { if (parsingBlockOrSF) { baos.write(b); } else { mev.update((byte)b); } } else { processEntry(mev); } } /** {@collect.stats} * {@description.open} * update an array of bytes. * {@description.close} */ public void update(int n, byte[] b, int off, int len, ManifestEntryVerifier mev) throws IOException { if (n != -1) { if (parsingBlockOrSF) { baos.write(b, off, n); } else { mev.update(b, off, n); } } else { processEntry(mev); } } /** {@collect.stats} * {@description.open} * called when we reach the end of entry in one of the read() methods. * {@description.close} */ private void processEntry(ManifestEntryVerifier mev) throws IOException { if (!parsingBlockOrSF) { JarEntry je = mev.getEntry(); if ((je != null) && (je.signers == null)) { je.signers = mev.verify(verifiedSigners, sigFileSigners); je.certs = mapSignersToCertArray(je.signers); } } else { try { parsingBlockOrSF = false; if (debug != null) { debug.println("processEntry: processing block"); } String uname = mev.getEntry().getName() .toUpperCase(Locale.ENGLISH); if (uname.endsWith(".SF")) { String key = uname.substring(0, uname.length()-3); byte bytes[] = baos.toByteArray(); // add to sigFileData in case future blocks need it sigFileData.put(key, bytes); // check pending blocks, we can now process // anyone waiting for this .SF file Iterator it = pendingBlocks.iterator(); while (it.hasNext()) { SignatureFileVerifier sfv = (SignatureFileVerifier) it.next(); if (sfv.needSignatureFile(key)) { if (debug != null) { debug.println( "processEntry: processing pending block"); } sfv.setSignatureFile(bytes); sfv.process(sigFileSigners); } } return; } // now we are parsing a signature block file String key = uname.substring(0, uname.lastIndexOf(".")); if (signerCache == null) signerCache = new ArrayList(); if (manDig == null) { synchronized(manifestRawBytes) { if (manDig == null) { manDig = new ManifestDigester(manifestRawBytes); manifestRawBytes = null; } } } SignatureFileVerifier sfv = new SignatureFileVerifier(signerCache, manDig, uname, baos.toByteArray()); if (sfv.needSignatureFileBytes()) { // see if we have already parsed an external .SF file byte[] bytes = (byte[]) sigFileData.get(key); if (bytes == null) { // put this block on queue for later processing // since we don't have the .SF bytes yet // (uname, block); if (debug != null) { debug.println("adding pending block"); } pendingBlocks.add(sfv); return; } else { sfv.setSignatureFile(bytes); } } sfv.process(sigFileSigners); } catch (sun.security.pkcs.ParsingException pe) { if (debug != null) debug.println("processEntry caught: "+pe); // ignore and treat as unsigned } catch (IOException ioe) { if (debug != null) debug.println("processEntry caught: "+ioe); // ignore and treat as unsigned } catch (SignatureException se) { if (debug != null) debug.println("processEntry caught: "+se); // ignore and treat as unsigned } catch (NoSuchAlgorithmException nsae) { if (debug != null) debug.println("processEntry caught: "+nsae); // ignore and treat as unsigned } catch (CertificateException ce) { if (debug != null) debug.println("processEntry caught: "+ce); // ignore and treat as unsigned } } } /** {@collect.stats} * {@description.open} * Return an array of java.security.cert.Certificate objects for * the given file in the jar. * {@description.close} */ public java.security.cert.Certificate[] getCerts(String name) { return mapSignersToCertArray(getCodeSigners(name)); } /** {@collect.stats} * {@description.open} * return an array of CodeSigner objects for * the given file in the jar. this array is not cloned. * * {@description.close} */ public CodeSigner[] getCodeSigners(String name) { return (CodeSigner[])verifiedSigners.get(name); } /* * Convert an array of signers into an array of concatenated certificate * arrays. */ private static java.security.cert.Certificate[] mapSignersToCertArray( CodeSigner[] signers) { if (signers != null) { ArrayList certChains = new ArrayList(); for (int i = 0; i < signers.length; i++) { certChains.addAll( signers[i].getSignerCertPath().getCertificates()); } // Convert into a Certificate[] return (java.security.cert.Certificate[]) certChains.toArray( new java.security.cert.Certificate[certChains.size()]); } return null; } /** {@collect.stats} * {@description.open} * returns true if there no files to verify. * {@description.close} * {@property.open internal} * should only be called after all the META-INF entries * have been processed. * {@property.close} */ boolean nothingToVerify() { return (anyToVerify == false); } /** {@collect.stats} * {@description.open} * called to let us know we have processed all the * META-INF entries, and if we re-read one of them, don't * re-process it. Also gets rid of any data structures * we needed when parsing META-INF entries. * {@description.close} */ void doneWithMeta() { parsingMeta = false; anyToVerify = !sigFileSigners.isEmpty(); baos = null; sigFileData = null; pendingBlocks = null; signerCache = null; manDig = null; } static class VerifierStream extends java.io.InputStream { private InputStream is; private JarVerifier jv; private ManifestEntryVerifier mev; private long numLeft; VerifierStream(Manifest man, JarEntry je, InputStream is, JarVerifier jv) throws IOException { this.is = is; this.jv = jv; this.mev = new ManifestEntryVerifier(man); this.jv.beginEntry(je, mev); this.numLeft = je.getSize(); if (this.numLeft == 0) this.jv.update(-1, this.mev); } public int read() throws IOException { if (numLeft > 0) { int b = is.read(); jv.update(b, mev); numLeft--; if (numLeft == 0) jv.update(-1, mev); return b; } else { return -1; } } public int read(byte b[], int off, int len) throws IOException { if ((numLeft > 0) && (numLeft < len)) { len = (int)numLeft; } if (numLeft > 0) { int n = is.read(b, off, len); jv.update(n, b, off, len, mev); numLeft -= n; if (numLeft == 0) jv.update(-1, b, off, len, mev); return n; } else { return -1; } } public void close() throws IOException { if (is != null) is.close(); is = null; mev = null; jv = null; } public int available() throws IOException { return is.available(); } } }
Java
/* * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.io.IOException; import sun.misc.JavaUtilJarAccess; class JavaUtilJarAccessImpl implements JavaUtilJarAccess { public boolean jarFileHasClassPathAttribute(JarFile jar) throws IOException { return jar.hasClassPathAttribute(); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.jar; import java.util.zip.*; import java.io.*; /** {@collect.stats} * {@description.open} * The <code>JarOutputStream</code> class is used to write the contents * of a JAR file to any output stream. It extends the class * <code>java.util.zip.ZipOutputStream</code> with support * for writing an optional <code>Manifest</code> entry. The * <code>Manifest</code> can be used to specify meta-information about * the JAR file and its entries. * {@description.close} * * @author David Connelly * @see Manifest * @see java.util.zip.ZipOutputStream * @since 1.2 */ public class JarOutputStream extends ZipOutputStream { private static final int JAR_MAGIC = 0xCAFE; /** {@collect.stats} * {@description.open} * Creates a new <code>JarOutputStream</code> with the specified * <code>Manifest</code>. The manifest is written as the first * entry to the output stream. * {@description.close} * * @param out the actual output stream * @param man the optional <code>Manifest</code> * @exception IOException if an I/O error has occurred */ public JarOutputStream(OutputStream out, Manifest man) throws IOException { super(out); if (man == null) { throw new NullPointerException("man"); } ZipEntry e = new ZipEntry(JarFile.MANIFEST_NAME); putNextEntry(e); man.write(new BufferedOutputStream(this)); closeEntry(); } /** {@collect.stats} * {@description.open} * Creates a new <code>JarOutputStream</code> with no manifest. * {@description.close} * @param out the actual output stream * @exception IOException if an I/O error has occurred */ public JarOutputStream(OutputStream out) throws IOException { super(out); } /** {@collect.stats} * {@description.open} * Begins writing a new JAR file entry and positions the stream * to the start of the entry data. This method will also close * any previous entry. The default compression method will be * used if no compression method was specified for the entry. * The current time will be used if the entry has no set modification * time. * {@description.close} * * @param ze the ZIP/JAR entry to be written * @exception ZipException if a ZIP error has occurred * @exception IOException if an I/O error has occurred */ public void putNextEntry(ZipEntry ze) throws IOException { if (firstEntry) { // Make sure that extra field data for first JAR // entry includes JAR magic number id. byte[] edata = ze.getExtra(); if (edata == null || !hasMagic(edata)) { if (edata == null) { edata = new byte[4]; } else { // Prepend magic to existing extra data byte[] tmp = new byte[edata.length + 4]; System.arraycopy(edata, 0, tmp, 4, edata.length); edata = tmp; } set16(edata, 0, JAR_MAGIC); // extra field id set16(edata, 2, 0); // extra field size ze.setExtra(edata); } firstEntry = false; } super.putNextEntry(ze); } private boolean firstEntry = true; /* * Returns true if specified byte array contains the * jar magic extra field id. */ private static boolean hasMagic(byte[] edata) { try { int i = 0; while (i < edata.length) { if (get16(edata, i) == JAR_MAGIC) { return true; } i += get16(edata, i + 2) + 4; } } catch (ArrayIndexOutOfBoundsException e) { // Invalid extra field data } return false; } /* * Fetches unsigned 16-bit value from byte array at specified offset. * The bytes are assumed to be in Intel (little-endian) byte order. */ private static int get16(byte[] b, int off) { return (b[off] & 0xff) | ((b[off+1] & 0xff) << 8); } /* * Sets 16-bit value at specified offset. The bytes are assumed to * be in Intel (little-endian) byte order. */ private static void set16(byte[] b, int off, int value) { b[off+0] = (byte)value; b[off+1] = (byte)(value >> 8); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.*; /** {@collect.stats} * {@description.open} * A bounded {@linkplain BlockingQueue blocking queue} backed by an * array. This queue orders elements FIFO (first-in-first-out). The * <em>head</em> of the queue is that element that has been on the * queue the longest time. The <em>tail</em> of the queue is that * element that has been on the queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * * <p>This is a classic &quot;bounded buffer&quot;, in which a * fixed-sized array holds elements inserted by producers and * extracted by consumers. Once created, the capacity cannot be * increased. Attempts to <tt>put</tt> an element into a full queue * will result in the operation blocking; attempts to <tt>take</tt> an * element from an empty queue will similarly block. * * <p> This class supports an optional fairness policy for ordering * waiting producer and consumer threads. By default, this ordering * is not guaranteed. However, a queue constructed with fairness set * to <tt>true</tt> grants threads access in FIFO order. Fairness * generally decreases throughput but reduces variability and avoids * starvation. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable { /** {@collect.stats} * {@description.open} * Serialization ID. This class relies on default serialization * even for the items array, which is default-serialized, even if * it is empty. Otherwise it could not be declared final, which is * necessary here. * {@description.close} */ private static final long serialVersionUID = -817911632652898426L; /** {@collect.stats} * {@description.open} * The queued items * {@description.close} */ private final E[] items; /** {@collect.stats} * {@description.open} * items index for next take, poll or remove * {@description.close} */ private int takeIndex; /** {@collect.stats} * {@description.open} * items index for next put, offer, or add. * {@description.close} */ private int putIndex; /** {@collect.stats} * {@description.open} * Number of items in the queue * {@description.close} */ private int count; /* * Concurrency control uses the classic two-condition algorithm * found in any textbook. */ /** {@collect.stats} * {@description.open} * Main lock guarding all access * {@description.close} */ private final ReentrantLock lock; /** {@collect.stats} * {@description.open} * Condition for waiting takes * {@description.close} */ private final Condition notEmpty; /** {@collect.stats} * {@description.open} * Condition for waiting puts * {@description.close} */ private final Condition notFull; // Internal helper methods /** {@collect.stats} * {@description.open} * Circularly increment i. * {@description.close} */ final int inc(int i) { return (++i == items.length)? 0 : i; } /** {@collect.stats} * {@description.open} * Inserts element at current put position, advances, and signals. * {@description.close} * {@property.open internal} * Call only when holding lock. * {@property.close} */ private void insert(E x) { items[putIndex] = x; putIndex = inc(putIndex); ++count; notEmpty.signal(); } /** {@collect.stats} * {@description.open} * Extracts element at current take position, advances, and signals. * {@description.close} * {@property.open internal} * Call only when holding lock. * {@property.close} */ private E extract() { final E[] items = this.items; E x = items[takeIndex]; items[takeIndex] = null; takeIndex = inc(takeIndex); --count; notFull.signal(); return x; } /** {@collect.stats} * {@description.open} * Utility for remove and iterator.remove: Delete item at position i. * {@description.close} * {@property.open internal} * Call only when holding lock. * {@property.close} */ void removeAt(int i) { final E[] items = this.items; // if removing front item, just advance if (i == takeIndex) { items[takeIndex] = null; takeIndex = inc(takeIndex); } else { // slide over all others up through putIndex. for (;;) { int nexti = inc(i); if (nexti != putIndex) { items[i] = items[nexti]; i = nexti; } else { items[i] = null; putIndex = i; break; } } } --count; notFull.signal(); } /** {@collect.stats} * {@description.open} * Creates an <tt>ArrayBlockingQueue</tt> with the given (fixed) * capacity and default access policy. * {@description.close} * * @param capacity the capacity of this queue * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1 */ public ArrayBlockingQueue(int capacity) { this(capacity, false); } /** {@collect.stats} * {@description.open} * Creates an <tt>ArrayBlockingQueue</tt> with the given (fixed) * capacity and the specified access policy. * {@description.close} * * @param capacity the capacity of this queue * @param fair if <tt>true</tt> then queue accesses for threads blocked * on insertion or removal, are processed in FIFO order; * if <tt>false</tt> the access order is unspecified. * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1 */ public ArrayBlockingQueue(int capacity, boolean fair) { if (capacity <= 0) throw new IllegalArgumentException(); this.items = (E[]) new Object[capacity]; lock = new ReentrantLock(fair); notEmpty = lock.newCondition(); notFull = lock.newCondition(); } /** {@collect.stats} * {@description.open} * Creates an <tt>ArrayBlockingQueue</tt> with the given (fixed) * capacity, the specified access policy and initially containing the * elements of the given collection, * added in traversal order of the collection's iterator. * {@description.close} * * @param capacity the capacity of this queue * @param fair if <tt>true</tt> then queue accesses for threads blocked * on insertion or removal, are processed in FIFO order; * if <tt>false</tt> the access order is unspecified. * @param c the collection of elements to initially contain * @throws IllegalArgumentException if <tt>capacity</tt> is less than * <tt>c.size()</tt>, or less than 1. * @throws NullPointerException if the specified collection or any * of its elements are null */ public ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c) { this(capacity, fair); if (capacity < c.size()) throw new IllegalArgumentException(); for (Iterator<? extends E> it = c.iterator(); it.hasNext();) add(it.next()); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue if it is * possible to do so immediately without exceeding the queue's capacity, * returning <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if this queue is full. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if this queue is full * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return super.add(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue if it is * possible to do so immediately without exceeding the queue's capacity, * returning <tt>true</tt> upon success and <tt>false</tt> if this queue * is full. This method is generally preferable to method {@link #add}, * which can fail to insert an element only by throwing an exception. * {@description.close} * * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { if (e == null) throw new NullPointerException(); final ReentrantLock lock = this.lock; lock.lock(); try { if (count == items.length) return false; else { insert(e); return true; } } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue, waiting * for space to become available if the queue is full. * {@description.close} * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ 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(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue, waiting * up to the specified wait time for space to become available if * the queue is full. * {@description.close} * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ 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 E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { if (count == 0) return null; E x = extract(); return x; } finally { lock.unlock(); } } 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 E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return (count == 0) ? null : items[takeIndex]; } finally { lock.unlock(); } } // this doc comment is overridden to remove the reference to collections // greater in size than Integer.MAX_VALUE /** {@collect.stats} * {@description.open} * Returns the number of elements in this queue. * {@description.close} * * @return the number of elements in this queue */ public int size() { final ReentrantLock lock = this.lock; lock.lock(); try { return count; } finally { lock.unlock(); } } // this doc comment is a modified copy of the inherited doc comment, // without the reference to unlimited queues. /** {@collect.stats} * {@description.open} * Returns the number of additional elements that this queue can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this queue * less the current <tt>size</tt> of this queue. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting <tt>remainingCapacity</tt> * because it may be the case that another thread is about to * insert or remove an element. * {@description.close} */ public int remainingCapacity() { final ReentrantLock lock = this.lock; lock.lock(); try { return items.length - count; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element <tt>e</tt> such * that <tt>o.equals(e)</tt>, if this queue contains one or more such * elements. * Returns <tt>true</tt> if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call */ public boolean remove(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; for (;;) { if (k++ >= count) return false; if (o.equals(items[i])) { removeAt(i); return true; } i = inc(i); } } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this queue contains the specified element. * More formally, returns <tt>true</tt> if and only if this queue contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this queue * @return <tt>true</tt> if this queue contains the specified element */ 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(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { Object[] a = new Object[count]; int k = 0; int i = takeIndex; while (k < count) { a[k++] = items[i]; i = inc(i); } return a; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { if (a.length < count) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), count ); int k = 0; int i = takeIndex; while (k < count) { a[k++] = (T)items[i]; i = inc(i); } if (a.length > count) a[count] = null; return a; } finally { lock.unlock(); } } public String toString() { final ReentrantLock lock = this.lock; lock.lock(); try { return super.toString(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Atomically removes all of the elements from this queue. * The queue will be empty after this call returns. * {@description.close} */ public void clear() { final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { int i = takeIndex; int k = count; while (k-- > 0) { items[i] = null; i = inc(i); } count = 0; putIndex = 0; takeIndex = 0; notFull.signalAll(); } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { int i = takeIndex; int n = 0; int max = count; while (n < max) { c.add(items[i]); items[i] = null; i = inc(i); ++n; } if (n > 0) { count = 0; putIndex = 0; takeIndex = 0; notFull.signalAll(); } return n; } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final E[] items = this.items; final ReentrantLock lock = this.lock; lock.lock(); try { int i = takeIndex; int n = 0; int sz = count; int max = (maxElements < count)? maxElements : count; while (n < max) { c.add(items[i]); items[i] = null; i = inc(i); ++n; } if (n > 0) { count -= n; takeIndex = i; notFull.signalAll(); } return n; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this queue in proper sequence. * {@description.close} * {@property.open synchronized} * 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. * {@property.close} * * @return an iterator over the elements in this queue in proper sequence */ public Iterator<E> iterator() { final ReentrantLock lock = this.lock; lock.lock(); try { return new Itr(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Iterator for ArrayBlockingQueue * {@description.close} */ private class Itr implements Iterator<E> { /** {@collect.stats} * {@description.open} * Index of element to be returned by next, * or a negative number if no such. * {@description.close} */ private int nextIndex; /** {@collect.stats} * {@description.open} * 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. * {@description.close} */ private E nextItem; /** {@collect.stats} * {@description.open} * Index of element returned by most recent call to next. * Reset to -1 if this element is deleted by a call to remove. * {@description.close} */ 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; } /** {@collect.stats} * {@description.open} * Checks whether nextIndex is valid; if so setting nextItem. * Stops iterator when either hits putIndex or sees null item. * {@description.close} */ 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(); } } } }
Java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group. Adapted and released, under explicit permission, * from JDK ArrayList.java which carries the following copyright: * * Copyright 1997 by Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. */ package java.util.concurrent; import java.util.*; import java.util.concurrent.locks.*; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * A thread-safe variant of {@link java.util.ArrayList} in which all mutative * operations (<tt>add</tt>, <tt>set</tt>, and so on) are implemented by * making a fresh copy of the underlying array. * * <p> This is ordinarily too costly, but may be <em>more</em> efficient * than alternatives when traversal operations vastly outnumber * mutations, and is useful when you cannot or don't want to * synchronize traversals, yet need to preclude interference among * concurrent threads. The "snapshot" style iterator method uses a * reference to the state of the array at the point that the iterator * was created. This array never changes during the lifetime of the * iterator, so interference is impossible and the iterator is * guaranteed not to throw <tt>ConcurrentModificationException</tt>. * The iterator will not reflect additions, removals, or changes to * the list since the iterator was created. Element-changing * operations on iterators themselves (<tt>remove</tt>, <tt>set</tt>, and * <tt>add</tt>) are not supported. These methods throw * <tt>UnsupportedOperationException</tt>. * * <p>All elements are permitted, including <tt>null</tt>. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code CopyOnWriteArrayList} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code CopyOnWriteArrayList} in another thread. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class CopyOnWriteArrayList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8673264195747942595L; /** {@collect.stats} * {@description.open} * The lock protecting all mutators * {@description.close} */ transient final ReentrantLock lock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * The array, accessed only via getArray/setArray. * {@description.close} */ private volatile transient Object[] array; /** {@collect.stats} * {@description.open} * Gets the array. Non-private so as to also be accessible * from CopyOnWriteArraySet class. * {@description.close} */ final Object[] getArray() { return array; } /** {@collect.stats} * {@description.open} * Sets the array. * {@description.close} */ final void setArray(Object[] a) { array = a; } /** {@collect.stats} * {@description.open} * Creates an empty list. * {@description.close} */ public CopyOnWriteArrayList() { setArray(new Object[0]); } /** {@collect.stats} * {@description.open} * Creates a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * {@description.close} * * @param c the collection of initially held elements * @throws NullPointerException if the specified collection is null */ public CopyOnWriteArrayList(Collection<? extends E> c) { Object[] elements = c.toArray(); // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elements.getClass() != Object[].class) elements = Arrays.copyOf(elements, elements.length, Object[].class); setArray(elements); } /** {@collect.stats} * {@description.open} * Creates a list holding a copy of the given array. * {@description.close} * * @param toCopyIn the array (a copy of this array is used as the * internal array) * @throws NullPointerException if the specified array is null */ public CopyOnWriteArrayList(E[] toCopyIn) { setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class)); } /** {@collect.stats} * {@description.open} * Returns the number of elements in this list. * {@description.close} * * @return the number of elements in this list */ public int size() { return getArray().length; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains no elements. * {@description.close} * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size() == 0; } /** {@collect.stats} * {@description.open} * Test for equality, coping with nulls. * {@description.close} */ private static boolean eq(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } /** {@collect.stats} * {@description.open} * static version of indexOf, to allow repeated calls without * needing to re-acquire array each time. * {@description.close} * @param o element to search for * @param elements the array * @param index first index to search * @param fence one past last index to search * @return index of element, or -1 if absent */ private static int indexOf(Object o, Object[] elements, int index, int fence) { if (o == null) { for (int i = index; i < fence; i++) if (elements[i] == null) return i; } else { for (int i = index; i < fence; i++) if (o.equals(elements[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * static version of lastIndexOf. * {@description.close} * @param o element to search for * @param elements the array * @param index first index to search * @return index of element, or -1 if absent */ private static int lastIndexOf(Object o, Object[] elements, int index) { if (o == null) { for (int i = index; i >= 0; i--) if (elements[i] == null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elements[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { Object[] elements = getArray(); return indexOf(o, elements, 0, elements.length) >= 0; } /** {@collect.stats} * {@inheritDoc} */ public int indexOf(Object o) { Object[] elements = getArray(); return indexOf(o, elements, 0, elements.length); } /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element in * this list, searching forwards from <tt>index</tt>, or returns -1 if * the element is not found. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>, * or -1 if there is no such index. * {@description.close} * * @param e element to search for * @param index index to start searching from * @return the index of the first occurrence of the element in * this list at position <tt>index</tt> or later in the list; * <tt>-1</tt> if the element is not found. * @throws IndexOutOfBoundsException if the specified index is negative */ public int indexOf(E e, int index) { Object[] elements = getArray(); return indexOf(e, elements, index, elements.length); } /** {@collect.stats} * {@inheritDoc} */ public int lastIndexOf(Object o) { Object[] elements = getArray(); return lastIndexOf(o, elements, elements.length - 1); } /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element in * this list, searching backwards from <tt>index</tt>, or returns -1 if * the element is not found. * More formally, returns the highest index <tt>i</tt> such that * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>, * or -1 if there is no such index. * {@description.close} * * @param e element to search for * @param index index to start searching backwards from * @return the index of the last occurrence of the element at position * less than or equal to <tt>index</tt> in this list; * -1 if the element is not found. * @throws IndexOutOfBoundsException if the specified index is greater * than or equal to the current size of this list */ public int lastIndexOf(E e, int index) { Object[] elements = getArray(); return lastIndexOf(e, elements, index); } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this list. (The elements themselves * are not copied.) * {@description.close} * * @return a clone of this list */ public Object clone() { try { CopyOnWriteArrayList c = (CopyOnWriteArrayList)(super.clone()); c.resetLock(); return c; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all the elements in this list */ public Object[] toArray() { Object[] elements = getArray(); return Arrays.copyOf(elements, elements.length); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <p>If this list fits in the specified array with room to spare * (i.e., the array has more elements than this list), the element in * the array immediately following the end of the list is set to * <tt>null</tt>. (This is useful in determining the length of this * list <i>only</i> if the caller knows that this list does not contain * any null elements.) * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing all the elements in this list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T a[]) { Object[] elements = getArray(); int len = elements.length; if (a.length < len) return (T[]) Arrays.copyOf(elements, len, a.getClass()); else { System.arraycopy(elements, 0, a, 0, len); if (a.length > len) a[len] = null; return a; } } // Positional Access Operations @SuppressWarnings("unchecked") private E get(Object[] a, int index) { return (E) a[index]; } /** {@collect.stats} * {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { return get(getArray(), index); } /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this list with the * specified element. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); E oldValue = get(elements, index); if (oldValue != element) { int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len); newElements[index] = element; setArray(newElements); } else { // Not quite a no-op; ensures volatile write semantics setArray(elements); } return oldValue; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list. * {@description.close} * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ 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(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (index > len || index < 0) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+len); Object[] newElements; int numMoved = len - index; if (numMoved == 0) newElements = Arrays.copyOf(elements, len + 1); else { newElements = new Object[len + 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index, newElements, index + 1, numMoved); } newElements[index] = element; setArray(newElements); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the list. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; E oldValue = get(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 oldValue; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this list, * if it is present. If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ 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(); } } /** {@collect.stats} * {@description.open} * Removes from this list all of the elements whose index is between * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements. * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.) * {@description.close} * * @param fromIndex index of first element to be removed * @param toIndex index after last element to be removed * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range * (@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex}) */ private void removeRange(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) throw new IndexOutOfBoundsException(); int newlen = len - (toIndex - fromIndex); int numMoved = len - toIndex; if (numMoved == 0) setArray(Arrays.copyOf(elements, newlen)); else { Object[] newElements = new Object[newlen]; System.arraycopy(elements, 0, newElements, 0, fromIndex); System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved); setArray(newElements); } } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Append the element if not present. * {@description.close} * * @param e element to be added to this list, if absent * @return <tt>true</tt> if the element was added */ public boolean addIfAbsent(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { // Copy while checking if already present. // This wins in the most common case where it is not present Object[] elements = getArray(); int len = elements.length; Object[] newElements = new Object[len + 1]; for (int i = 0; i < len; ++i) { if (eq(e, elements[i])) return false; // exit, throwing away copy else newElements[i] = elements[i]; } newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains all of the elements of the * specified collection. * {@description.close} * * @param c collection to be checked for containment in this list * @return <tt>true</tt> if this list contains all of the elements of the * specified collection * @throws NullPointerException if the specified collection is null * @see #contains(Object) */ public boolean containsAll(Collection<?> c) { Object[] elements = getArray(); int len = elements.length; for (Object e : c) { if (indexOf(e, elements, 0, len) < 0) return false; } return true; } /** {@collect.stats} * {@description.open} * Removes from this list all of its elements that are contained in * the specified collection. This is a particularly expensive operation * in this class because of the need for an internal temporary array. * {@description.close} * * @param c collection containing elements to be removed from this list * @return <tt>true</tt> if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean removeAll(Collection<?> c) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (len != 0) { // temp array holds those elements we know we want to keep int newlen = 0; Object[] temp = new Object[len]; for (int i = 0; i < len; ++i) { Object element = elements[i]; if (!c.contains(element)) temp[newlen++] = element; } if (newlen != len) { setArray(Arrays.copyOf(temp, newlen)); return true; } } return false; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all of * its elements that are not contained in the specified collection. * {@description.close} * * @param c collection containing elements to be retained in this list * @return <tt>true</tt> if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection (optional) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean retainAll(Collection<?> c) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (len != 0) { // temp array holds those elements we know we want to keep int newlen = 0; Object[] temp = new Object[len]; for (int i = 0; i < len; ++i) { Object element = elements[i]; if (c.contains(element)) temp[newlen++] = element; } if (newlen != len) { setArray(Arrays.copyOf(temp, newlen)); return true; } } return false; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified collection that * are not already contained in this list, to the end of * this list, in the order that they are returned by the * specified collection's iterator. * {@description.close} * * @param c collection containing elements to be added to this list * @return the number of elements added * @throws NullPointerException if the specified collection is null * @see #addIfAbsent(Object) */ public int addAllAbsent(Collection<? extends E> c) { Object[] cs = c.toArray(); if (cs.length == 0) return 0; Object[] uniq = new Object[cs.length]; final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; int added = 0; for (int i = 0; i < cs.length; ++i) { // scan for duplicates Object e = cs[i]; if (indexOf(e, elements, 0, len) < 0 && indexOf(e, uniq, 0, added) < 0) uniq[added++] = e; } if (added > 0) { Object[] newElements = Arrays.copyOf(elements, len + added); System.arraycopy(uniq, 0, newElements, len, added); setArray(newElements); } return added; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes all of the elements from this list. * The list will be empty after this call returns. * {@description.close} */ public void clear() { final ReentrantLock lock = this.lock; lock.lock(); try { setArray(new Object[0]); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified collection to the end * of this list, in the order that they are returned by the specified * collection's iterator. * {@description.close} * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { Object[] cs = c.toArray(); if (cs.length == 0) return false; final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + cs.length); System.arraycopy(cs, 0, newElements, len, cs.length); setArray(newElements); return true; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in this list in the order that they are returned by the * specified collection's iterator. * {@description.close} * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null * @see #add(int,Object) */ public boolean addAll(int index, Collection<? extends E> c) { Object[] cs = c.toArray(); final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (index > len || index < 0) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+len); if (cs.length == 0) return false; int numMoved = len - index; Object[] newElements; if (numMoved == 0) newElements = Arrays.copyOf(elements, len + cs.length); else { newElements = new Object[len + cs.length]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index, newElements, index + cs.length, numMoved); } System.arraycopy(cs, 0, newElements, index, cs.length); setArray(newElements); return true; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Save the state of the list to a stream (i.e., serialize it). * {@description.close} * * @serialData The length of the array backing the list is emitted * (int), followed by all of its elements (each an Object) * in the proper order. * @param s the stream */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff s.defaultWriteObject(); Object[] elements = getArray(); int len = elements.length; // Write out array length s.writeInt(len); // Write out all elements in the proper order. for (int i = 0; i < len; i++) s.writeObject(elements[i]); } /** {@collect.stats} * {@description.open} * Reconstitute the list from a stream (i.e., deserialize it). * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); // bind to new lock resetLock(); // Read in array length and allocate array int len = s.readInt(); Object[] elements = new Object[len]; // Read in all elements in the proper order. for (int i = 0; i < len; i++) elements[i] = s.readObject(); setArray(elements); } /** {@collect.stats} * {@description.open} * Returns a string representation of this list. The string * representation consists of the string representations of the list's * elements in the order they are returned by its iterator, enclosed in * square brackets (<tt>"[]"</tt>). Adjacent elements are separated by * the characters <tt>", "</tt> (comma and space). Elements are * converted to strings as by {@link String#valueOf(Object)}. * {@description.close} * * @return a string representation of this list */ public String toString() { return Arrays.toString(getArray()); } /** {@collect.stats} * {@description.open} * Compares the specified object with this list for equality. * Returns {@code true} if the specified object is the same object * as this object, or if it is also a {@link List} and the sequence * of elements returned by an {@linkplain List#iterator() iterator} * over the specified list is the same as the sequence returned by * an iterator over this list. The two sequences are considered to * be the same if they have the same length and corresponding * elements at the same position in the sequence are <em>equal</em>. * Two elements {@code e1} and {@code e2} are considered * <em>equal</em> if {@code (e1==null ? e2==null : e1.equals(e2))}. * {@description.close} * * @param o the object to be compared for equality with this list * @return {@code true} if the specified object is equal to this list */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; List<?> list = (List<?>)(o); Iterator<?> it = list.iterator(); Object[] elements = getArray(); int len = elements.length; for (int i = 0; i < len; ++i) if (!it.hasNext() || !eq(elements[i], it.next())) return false; if (it.hasNext()) return false; return true; } /** {@collect.stats} * {@description.open} * Returns the hash code value for this list. * * <p>This implementation uses the definition in {@link List#hashCode}. * {@description.close} * * @return the hash code value for this list */ public int hashCode() { int hashCode = 1; Object[] elements = getArray(); int len = elements.length; for (int i = 0; i < len; ++i) { Object obj = elements[i]; hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); } return hashCode; } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator provides a snapshot of the state of the list * when the iterator was constructed. * {@description.close} * {@property.open synchronized} * No synchronization is needed while * traversing the iterator. * {@property.close} * {@property.open} * The iterator does <em>NOT</em> support the * <tt>remove</tt> method. * {@property.close} * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new COWIterator<E>(getArray(), 0); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>The returned iterator provides a snapshot of the state of the list * when the iterator was constructed. * {@description.close} * {@property.open synchronized} * No synchronization is needed while * traversing the iterator. * {@property.close} * {@property.open} * The iterator does <em>NOT</em> support the * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods. * {@property.close} */ public ListIterator<E> listIterator() { return new COWIterator<E>(getArray(), 0); } /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>The returned iterator provides a snapshot of the state of the list * when the iterator was constructed. * {@description.close} * {@property.open synchronized} * No synchronization is needed while * traversing the iterator. * {@property.close} * {@property.open} * The iterator does <em>NOT</em> support the * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods. * {@property.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(final int index) { Object[] elements = getArray(); int len = elements.length; if (index<0 || index>len) throw new IndexOutOfBoundsException("Index: "+index); return new COWIterator<E>(elements, index); } private static class COWIterator<E> implements ListIterator<E> { /** {@collect.stats} * {@description.open} * Snapshot of the array * {@description.close} */ private final Object[] snapshot; /** {@collect.stats} * {@description.open} * Index of element to be returned by subsequent call to next. * {@description.close} */ 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; } @SuppressWarnings("unchecked") public E next() { if (! hasNext()) throw new NoSuchElementException(); return (E) snapshot[cursor++]; } @SuppressWarnings("unchecked") public E previous() { if (! hasPrevious()) throw new NoSuchElementException(); return (E) snapshot[--cursor]; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } /** {@collect.stats} * {@description.open} * Not supported. Always throws UnsupportedOperationException. * {@description.close} * @throws UnsupportedOperationException always; <tt>remove</tt> * is not supported by this iterator. */ public void remove() { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Not supported. Always throws UnsupportedOperationException. * {@description.close} * @throws UnsupportedOperationException always; <tt>set</tt> * is not supported by this iterator. */ public void set(E e) { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Not supported. Always throws UnsupportedOperationException. * {@description.close} * @throws UnsupportedOperationException always; <tt>add</tt> * is not supported by this iterator. */ public void add(E e) { throw new UnsupportedOperationException(); } } /** {@collect.stats} * {@description.open} * Returns a view of the portion of this list between * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. * The returned list is backed by this list, so changes in the * returned list are reflected in this list, and vice-versa. * While mutative operations are supported, they are probably not * very useful for CopyOnWriteArrayLists. * {@description.close} * * {@property.open} * <p>The semantics of the list returned by this method become * undefined if the backing list (i.e., this list) is * <i>structurally modified</i> in any way other than via the * returned list. (Structural modifications are those that change * the size of the list, or otherwise perturb it in such a fashion * that iterations in progress may yield incorrect results.) * {@property.close} * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public List<E> subList(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; if (fromIndex < 0 || toIndex > len || fromIndex > toIndex) throw new IndexOutOfBoundsException(); return new COWSubList<E>(this, fromIndex, toIndex); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Sublist for CopyOnWriteArrayList. * This class extends AbstractList merely for convenience, to * avoid having to define addAll, etc. This doesn't hurt, but * is wasteful. This class does not need or use modCount * mechanics in AbstractList, but does need to check for * concurrent modification using similar mechanics. On each * operation, the array that we expect the backing list to use * is checked and updated. Since we do this for all of the * base operations invoked by those defined in AbstractList, * all is well. While inefficient, this is not worth * improving. The kinds of list operations inherited from * AbstractList are already so slow on COW sublists that * adding a bit more space/time doesn't seem even noticeable. * {@description.close} */ private static class COWSubList<E> extends AbstractList<E> implements RandomAccess { private final CopyOnWriteArrayList<E> l; private final int offset; private int size; private Object[] expectedArray; // only call this holding l's lock COWSubList(CopyOnWriteArrayList<E> list, int fromIndex, int toIndex) { l = list; expectedArray = l.getArray(); offset = fromIndex; size = toIndex - fromIndex; } // only call this holding l's lock private void checkForComodification() { if (l.getArray() != expectedArray) throw new ConcurrentModificationException(); } // only call this holding l's lock private void rangeCheck(int index) { if (index<0 || index>=size) throw new IndexOutOfBoundsException("Index: "+index+ ",Size: "+size); } public E set(int index, E element) { final ReentrantLock lock = l.lock; lock.lock(); try { rangeCheck(index); checkForComodification(); E x = l.set(index+offset, element); expectedArray = l.getArray(); return x; } finally { lock.unlock(); } } public E get(int index) { final ReentrantLock lock = l.lock; lock.lock(); try { rangeCheck(index); checkForComodification(); return l.get(index+offset); } finally { lock.unlock(); } } public int size() { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); return size; } finally { lock.unlock(); } } public void add(int index, E element) { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); if (index<0 || index>size) throw new IndexOutOfBoundsException(); l.add(index+offset, element); expectedArray = l.getArray(); size++; } finally { lock.unlock(); } } public void clear() { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); l.removeRange(offset, offset+size); expectedArray = l.getArray(); size = 0; } finally { lock.unlock(); } } public E remove(int index) { final ReentrantLock lock = l.lock; lock.lock(); try { rangeCheck(index); checkForComodification(); E result = l.remove(index+offset); expectedArray = l.getArray(); size--; return result; } finally { lock.unlock(); } } public boolean remove(Object o) { int index = indexOf(o); if (index == -1) return false; remove(index); return true; } public Iterator<E> iterator() { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); return new COWSubListIterator<E>(l, 0, offset, size); } finally { lock.unlock(); } } public ListIterator<E> listIterator(final int index) { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); if (index<0 || index>size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); return new COWSubListIterator<E>(l, index, offset, size); } finally { lock.unlock(); } } public List<E> subList(int fromIndex, int toIndex) { final ReentrantLock lock = l.lock; lock.lock(); try { checkForComodification(); if (fromIndex<0 || toIndex>size) throw new IndexOutOfBoundsException(); return new COWSubList<E>(l, fromIndex + offset, toIndex + offset); } finally { lock.unlock(); } } } private static class COWSubListIterator<E> implements ListIterator<E> { private final ListIterator<E> i; private final int index; private final int offset; private final int size; COWSubListIterator(List<E> l, int index, int offset, int size) { this.index = index; this.offset = offset; this.size = size; i = l.listIterator(index+offset); } public boolean hasNext() { return nextIndex() < size; } public E next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public E previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } } // Support for resetting lock while deserializing private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long lockOffset; static { try { lockOffset = unsafe.objectFieldOffset (CopyOnWriteArrayList.class.getDeclaredField("lock")); } catch (Exception ex) { throw new Error(ex); } } private void resetLock() { unsafe.putObjectVolatile(this, lockOffset, new ReentrantLock()); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; /** {@collect.stats} * {@description.open} * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList} * for all of its operations. Thus, it shares the same basic properties: * <ul> * <li>It is best suited for applications in which set sizes generally * stay small, read-only operations * vastly outnumber mutative operations, and you need * to prevent interference among threads during traversal. * <li>It is thread-safe. * <li>Mutative operations (<tt>add</tt>, <tt>set</tt>, <tt>remove</tt>, etc.) * are expensive since they usually entail copying the entire underlying * array. * <li>Iterators do not support the mutative <tt>remove</tt> operation. * <li>Traversal via iterators is fast and cannot encounter * interference from other threads. Iterators rely on * unchanging snapshots of the array at the time the iterators were * constructed. * </ul> * * <p> <b>Sample Usage.</b> The following code sketch uses a * copy-on-write set to maintain a set of Handler objects that * perform some action upon state updates. * * <pre> * class Handler { void handle(); ... } * * class X { * private final CopyOnWriteArraySet&lt;Handler&gt; handlers * = new CopyOnWriteArraySet&lt;Handler&gt;(); * public void addHandler(Handler h) { handlers.add(h); } * * private long internalState; * private synchronized void changeState() { internalState = ...; } * * public void update() { * changeState(); * for (Handler handler : handlers) * handler.handle(); * } * } * </pre> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @see CopyOnWriteArrayList * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements java.io.Serializable { private static final long serialVersionUID = 5457747651344034263L; private final CopyOnWriteArrayList<E> al; /** {@collect.stats} * {@description.open} * Creates an empty set. * {@description.close} */ public CopyOnWriteArraySet() { al = new CopyOnWriteArrayList<E>(); } /** {@collect.stats} * {@description.open} * Creates a set containing all of the elements of the specified * collection. * {@description.close} * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection is null */ public CopyOnWriteArraySet(Collection<? extends E> c) { al = new CopyOnWriteArrayList<E>(); al.addAllAbsent(c); } /** {@collect.stats} * {@description.open} * Returns the number of elements in this set. * {@description.close} * * @return the number of elements in this set */ public int size() { return al.size(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return al.isEmpty(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * More formally, returns <tt>true</tt> if and only if this set * contains an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ public boolean contains(Object o) { return al.contains(o); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this set. * If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * * <p>The returned array will be "safe" in that no references to it * are maintained by this set. (In other words, this method must * allocate a new array even if this set is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all the elements in this set */ public Object[] toArray() { return al.toArray(); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this set; the * runtime type of the returned array is that of the specified array. * If the set fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this set. * * <p>If this set fits in the specified array with room to spare * (i.e., the array has more elements than this set), the element in * the array immediately following the end of the set is set to * <tt>null</tt>. (This is useful in determining the length of this * set <i>only</i> if the caller knows that this set does not contain * any null elements.) * * <p>If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements * in the same order. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a set known to contain only strings. * The following code can be used to dump the set into a newly allocated * array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of this set are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing all the elements in this set * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in this * set * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { return al.toArray(a); } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * The set will be empty after this call returns. * {@description.close} */ public void clear() { al.clear(); } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * More formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, * if this set contains such an element. Returns <tt>true</tt> if * this set contained the element (or equivalently, if this set * changed as a result of the call). (This set will not contain the * element once the call returns.) * {@description.close} * * @param o object to be removed from this set, if present * @return <tt>true</tt> if this set contained the specified element */ public boolean remove(Object o) { return al.remove(o); } /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * the set contains no element <tt>e2</tt> such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return al.addIfAbsent(e); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains all of the elements of the * specified collection. If the specified collection is also a set, this * method returns <tt>true</tt> if it is a <i>subset</i> of this set. * {@description.close} * * @param c collection to be checked for containment in this set * @return <tt>true</tt> if this set contains all of the elements of the * specified collection * @throws NullPointerException if the specified collection is null * @see #contains(Object) */ public boolean containsAll(Collection<?> c) { return al.containsAll(c); } /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this set if * they're not already present. If the specified collection is also a * set, the <tt>addAll</tt> operation effectively modifies this set so * that its value is the <i>union</i> of the two sets. * {@description.close} * {@property.open synchronized} * The behavior of * this operation is undefined if the specified collection is modified * while the operation is in progress. * {@property.close} * * @param c collection containing elements to be added to this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { return al.addAllAbsent(c) > 0; } /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in the * specified collection. If the specified collection is also a set, * this operation effectively modifies this set so that its value is the * <i>asymmetric set difference</i> of the two sets. * {@description.close} * * @param c collection containing elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean removeAll(Collection<?> c) { return al.removeAll(c); } /** {@collect.stats} * {@description.open} * Retains only the elements in this set that are contained in the * specified collection. In other words, removes from this set all of * its elements that are not contained in the specified collection. If * the specified collection is also a set, this operation effectively * modifies this set so that its value is the <i>intersection</i> of the * two sets. * {@description.close} * * @param c collection containing elements to be retained in this set * @return <tt>true</tt> if this set changed as a result of the call * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ public boolean retainAll(Collection<?> c) { return al.retainAll(c); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements contained in this set * in the order in which these elements were added. * * <p>The returned iterator provides a snapshot of the state of the set * when the iterator was constructed. No synchronization is needed while * traversing the iterator. * {@description.close} * {@property.open} * The iterator does <em>NOT</em> support the * <tt>remove</tt> method. * {@property.close} * * @return an iterator over the elements in this set */ public Iterator<E> iterator() { return al.iterator(); } /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. * Returns {@code true} if the specified object is the same object * as this object, or if it is also a {@link Set} and the elements * returned by an {@linkplain List#iterator() iterator} over the * specified set are the same as the elements returned by an * iterator over this set. More formally, the two iterators are * considered to return the same elements if they return the same * number of elements and for every element {@code e1} returned by * the iterator over the specified set, there is an element * {@code e2} returned by the iterator over this set such that * {@code (e1==null ? e2==null : e1.equals(e2))}. * {@description.close} * * @param o object to be compared for equality with this set * @return {@code true} if the specified object is equal to this set */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> set = (Set<?>)(o); Iterator<?> it = set.iterator(); // Uses O(n^2) algorithm that is only appropriate // for small sets, which CopyOnWriteArraySets should be. // Use a single snapshot of underlying array Object[] elements = al.getArray(); int len = elements.length; // Mark matched elements to avoid re-checking boolean[] matched = new boolean[len]; int k = 0; outer: while (it.hasNext()) { if (++k > len) return false; Object x = it.next(); for (int i = 0; i < len; ++i) { if (!matched[i] && eq(x, elements[i])) { matched[i] = true; continue outer; } } return false; } return k == len; } /** {@collect.stats} * {@description.open} * Test for equality, coping with nulls. * {@description.close} */ private static boolean eq(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A {@link Future} that is {@link Runnable}. Successful execution of * the <tt>run</tt> method causes completion of the <tt>Future</tt> * and allows access to its results. * {@description.close} * @see FutureTask * @see Executor * @since 1.6 * @author Doug Lea * @param <V> The result type returned by this Future's <tt>get</tt> method */ public interface RunnableFuture<V> extends Runnable, Future<V> { /** {@collect.stats} * {@description.open} * Sets this Future to the result of its computation * unless it has been cancelled. * {@description.close} */ void run(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A <tt>TimeUnit</tt> represents time durations at a given unit of * granularity and provides utility methods to convert across units, * and to perform timing and delay operations in these units. A * <tt>TimeUnit</tt> does not maintain time information, but only * helps organize and use time representations that may be maintained * separately across various contexts. A nanosecond is defined as one * thousandth of a microsecond, a microsecond as one thousandth of a * millisecond, a millisecond as one thousandth of a second, a minute * as sixty seconds, an hour as sixty minutes, and a day as twenty four * hours. * * <p>A <tt>TimeUnit</tt> is mainly used to inform time-based methods * how a given timing parameter should be interpreted. For example, * the following code will timeout in 50 milliseconds if the {@link * java.util.concurrent.locks.Lock lock} is not available: * * <pre> Lock lock = ...; * if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ... * </pre> * while this code will timeout in 50 seconds: * <pre> * Lock lock = ...; * if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ... * </pre> * * Note however, that there is no guarantee that a particular timeout * implementation will be able to notice the passage of time at the * same granularity as the given <tt>TimeUnit</tt>. * {@description.close} * * @since 1.5 * @author Doug Lea */ public enum TimeUnit { NANOSECONDS { public long toNanos(long d) { return d; } public long toMicros(long d) { return d/(C1/C0); } public long toMillis(long d) { return d/(C2/C0); } public long toSeconds(long d) { return d/(C3/C0); } public long toMinutes(long d) { return d/(C4/C0); } public long toHours(long d) { return d/(C5/C0); } public long toDays(long d) { return d/(C6/C0); } public long convert(long d, TimeUnit u) { return u.toNanos(d); } int excessNanos(long d, long m) { return (int)(d - (m*C2)); } }, MICROSECONDS { public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); } public long toMicros(long d) { return d; } public long toMillis(long d) { return d/(C2/C1); } public long toSeconds(long d) { return d/(C3/C1); } public long toMinutes(long d) { return d/(C4/C1); } public long toHours(long d) { return d/(C5/C1); } public long toDays(long d) { return d/(C6/C1); } public long convert(long d, TimeUnit u) { return u.toMicros(d); } int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); } }, MILLISECONDS { public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); } public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); } public long toMillis(long d) { return d; } public long toSeconds(long d) { return d/(C3/C2); } public long toMinutes(long d) { return d/(C4/C2); } public long toHours(long d) { return d/(C5/C2); } public long toDays(long d) { return d/(C6/C2); } public long convert(long d, TimeUnit u) { return u.toMillis(d); } int excessNanos(long d, long m) { return 0; } }, SECONDS { public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); } public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); } public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); } public long toSeconds(long d) { return d; } public long toMinutes(long d) { return d/(C4/C3); } public long toHours(long d) { return d/(C5/C3); } public long toDays(long d) { return d/(C6/C3); } public long convert(long d, TimeUnit u) { return u.toSeconds(d); } int excessNanos(long d, long m) { return 0; } }, MINUTES { public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); } public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); } public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); } public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); } public long toMinutes(long d) { return d; } public long toHours(long d) { return d/(C5/C4); } public long toDays(long d) { return d/(C6/C4); } public long convert(long d, TimeUnit u) { return u.toMinutes(d); } int excessNanos(long d, long m) { return 0; } }, HOURS { public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); } public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); } public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); } public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); } public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); } public long toHours(long d) { return d; } public long toDays(long d) { return d/(C6/C5); } public long convert(long d, TimeUnit u) { return u.toHours(d); } int excessNanos(long d, long m) { return 0; } }, DAYS { public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); } public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); } public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); } public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); } public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); } public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); } public long toDays(long d) { return d; } public long convert(long d, TimeUnit u) { return u.toDays(d); } int excessNanos(long d, long m) { return 0; } }; // Handy constants for conversion methods static final long C0 = 1L; static final long C1 = C0 * 1000L; static final long C2 = C1 * 1000L; static final long C3 = C2 * 1000L; static final long C4 = C3 * 60L; static final long C5 = C4 * 60L; static final long C6 = C5 * 24L; static final long MAX = Long.MAX_VALUE; /** {@collect.stats} * {@description.open} * Scale d by m, checking for overflow. * This has a short name to make above code more readable. * {@description.close} */ static long x(long d, long m, long over) { if (d > over) return Long.MAX_VALUE; if (d < -over) return Long.MIN_VALUE; return d * m; } // To maintain full signature compatibility with 1.5, and to improve the // clarity of the generated javadoc (see 6287639: Abstract methods in // enum classes should not be listed as abstract), method convert // etc. are not declared abstract but otherwise act as abstract methods. /** {@collect.stats} * {@description.open} * Convert the given time duration in the given unit to this * unit. Conversions from finer to coarser granularities * truncate, so lose precision. For example converting * <tt>999</tt> milliseconds to seconds results in * <tt>0</tt>. Conversions from coarser to finer granularities * with arguments that would numerically overflow saturate to * <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt> * if positive. * * <p>For example, to convert 10 minutes to milliseconds, use: * <tt>TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)</tt> * {@description.close} * * @param sourceDuration the time duration in the given <tt>sourceUnit</tt> * @param sourceUnit the unit of the <tt>sourceDuration</tt> argument * @return the converted duration in this unit, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. */ public long convert(long sourceDuration, TimeUnit sourceUnit) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>NANOSECONDS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert */ public long toNanos(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>MICROSECONDS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert */ public long toMicros(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>MILLISECONDS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert */ public long toMillis(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>SECONDS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert */ public long toSeconds(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>MINUTES.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert * @since 1.6 */ public long toMinutes(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>HOURS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration, * or <tt>Long.MIN_VALUE</tt> if conversion would negatively * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow. * @see #convert * @since 1.6 */ public long toHours(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Equivalent to <tt>DAYS.convert(duration, this)</tt>. * {@description.close} * @param duration the duration * @return the converted duration * @see #convert * @since 1.6 */ public long toDays(long duration) { throw new AbstractMethodError(); } /** {@collect.stats} * {@description.open} * Utility to compute the excess-nanosecond argument to wait, * sleep, join. * {@description.close} * @param d the duration * @param m the number of milliseconds * @return the number of nanoseconds */ abstract int excessNanos(long d, long m); /** {@collect.stats} * {@description.open} * Performs a timed <tt>Object.wait</tt> using this time unit. * This is a convenience method that converts timeout arguments * into the form required by the <tt>Object.wait</tt> method. * * <p>For example, you could implement a blocking <tt>poll</tt> * method (see {@link BlockingQueue#poll BlockingQueue.poll}) * using: * * <pre> public synchronized Object poll(long timeout, TimeUnit unit) throws InterruptedException { * while (empty) { * unit.timedWait(this, timeout); * ... * } * }</pre> * {@description.close} * * @param obj the object to wait on * @param timeout the maximum time to wait. If less than * or equal to zero, do not wait at all. * @throws InterruptedException if interrupted while waiting. * @see Object#wait(long, int) */ public void timedWait(Object obj, long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); obj.wait(ms, ns); } } /** {@collect.stats} * {@description.open} * Performs a timed <tt>Thread.join</tt> using this time unit. * This is a convenience method that converts time arguments into the * form required by the <tt>Thread.join</tt> method. * {@description.close} * @param thread the thread to wait for * @param timeout the maximum time to wait. If less than * or equal to zero, do not wait at all. * @throws InterruptedException if interrupted while waiting. * @see Thread#join(long, int) */ public void timedJoin(Thread thread, long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); thread.join(ms, ns); } } /** {@collect.stats} * {@description.open} * Performs a <tt>Thread.sleep</tt> using this unit. * This is a convenience method that converts time arguments into the * form required by the <tt>Thread.sleep</tt> method. * {@description.close} * @param timeout the minimum time to sleep. If less than * or equal to zero, do not sleep at all. * @throws InterruptedException if interrupted while sleeping. * @see Thread#sleep */ public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}. * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface RejectedExecutionHandler { /** {@collect.stats} * {@description.open} * Method that may be invoked by a {@link ThreadPoolExecutor} when * {@link ThreadPoolExecutor#execute execute} cannot accept a * task. This may occur when no more threads or queue slots are * available because their bounds would be exceeded, or upon * shutdown of the Executor. * * <p>In the absence of other alternatives, the method may throw * an unchecked {@link RejectedExecutionException}, which will be * propagated to the caller of {@code execute}. * {@description.close} * * @param r the runnable task requested to be executed * @param executor the executor attempting to execute this task * @throws RejectedExecutionException if there is no remedy */ void rejectedExecution(Runnable r, ThreadPoolExecutor executor); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import java.util.concurrent.locks.*; /** {@collect.stats} * {@description.open} * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on * linked nodes. * * <p> The optional capacity bound constructor argument serves as a * way to prevent excessive expansion. The capacity, if unspecified, * is equal to {@link Integer#MAX_VALUE}. Linked nodes are * dynamically created upon each insertion unless this would bring the * deque above capacity. * * <p>Most operations run in constant time (ignoring time spent * blocking). Exceptions include {@link #remove(Object) remove}, * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link * #removeLastOccurrence removeLastOccurrence}, {@link #contains * contains}, {@link #iterator iterator.remove()}, and the bulk * operations, all of which run in linear time. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.6 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class LinkedBlockingDeque<E> extends AbstractQueue<E> implements BlockingDeque<E>, java.io.Serializable { /* * Implemented as a simple doubly-linked list protected by a * single lock and using conditions to manage blocking. */ /* * We have "diamond" multiple interface/abstract class inheritance * here, and that introduces ambiguities. Often we want the * BlockingDeque javadoc combined with the AbstractQueue * implementation, so a lot of method specs are duplicated here. */ private static final long serialVersionUID = -387911632671998426L; /** {@collect.stats} * {@description.open} * Doubly-linked list node class * {@description.close} */ static final class Node<E> { E item; Node<E> prev; Node<E> next; Node(E x, Node<E> p, Node<E> n) { item = x; prev = p; next = n; } } /** {@collect.stats} * {@description.open} * Pointer to first node * {@description.close} */ private transient Node<E> first; /** {@collect.stats} * {@description.open} * Pointer to last node * {@description.close} */ private transient Node<E> last; /** {@collect.stats} * {@description.open} * Number of items in the deque * {@description.close} */ private transient int count; /** {@collect.stats} * {@description.open} * Maximum number of items in the deque * {@description.close} */ private final int capacity; /** {@collect.stats} * {@description.open} * Main lock guarding all access * {@description.close} */ private final ReentrantLock lock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * Condition for waiting takes * {@description.close} */ private final Condition notEmpty = lock.newCondition(); /** {@collect.stats} * {@description.open} * Condition for waiting puts * {@description.close} */ private final Condition notFull = lock.newCondition(); /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingDeque</tt> with a capacity of * {@link Integer#MAX_VALUE}. * {@description.close} */ public LinkedBlockingDeque() { this(Integer.MAX_VALUE); } /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingDeque</tt> with the given (fixed) capacity. * {@description.close} * * @param capacity the capacity of this deque * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1 */ public LinkedBlockingDeque(int capacity) { if (capacity <= 0) throw new IllegalArgumentException(); this.capacity = capacity; } /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingDeque</tt> with a capacity of * {@link Integer#MAX_VALUE}, initially containing the elements of * the given collection, added in traversal order of the * collection's iterator. * {@description.close} * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedBlockingDeque(Collection<? extends E> c) { this(Integer.MAX_VALUE); for (E e : c) add(e); } // Basic linking and unlinking operations, called only while holding lock /** {@collect.stats} * {@description.open} * Links e as first element, or returns false if full. * {@description.close} */ private boolean linkFirst(E e) { if (count >= capacity) return false; ++count; Node<E> f = first; Node<E> x = new Node<E>(e, null, f); first = x; if (last == null) last = x; else f.prev = x; notEmpty.signal(); return true; } /** {@collect.stats} * {@description.open} * Links e as last element, or returns false if full. * {@description.close} */ private boolean linkLast(E e) { if (count >= capacity) return false; ++count; Node<E> l = last; Node<E> x = new Node<E>(e, l, null); last = x; if (first == null) first = x; else l.next = x; notEmpty.signal(); return true; } /** {@collect.stats} * {@description.open} * Removes and returns first element, or null if empty. * {@description.close} */ private E unlinkFirst() { Node<E> f = first; if (f == null) return null; Node<E> n = f.next; first = n; if (n == null) last = null; else n.prev = null; --count; notFull.signal(); return f.item; } /** {@collect.stats} * {@description.open} * Removes and returns last element, or null if empty. * {@description.close} */ private E unlinkLast() { Node<E> l = last; if (l == null) return null; Node<E> p = l.prev; last = p; if (p == null) first = null; else p.next = null; --count; notFull.signal(); return l.item; } /** {@collect.stats} * {@description.open} * Unlink e * {@description.close} */ private void unlink(Node<E> x) { Node<E> p = x.prev; Node<E> n = x.next; if (p == null) { if (n == null) first = last = null; else { n.prev = null; first = n; } } else if (n == null) { p.next = null; last = p; } else { p.next = n; n.prev = p; } --count; notFull.signalAll(); } // BlockingDeque methods /** {@collect.stats} * @throws IllegalStateException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public void addFirst(E e) { if (!offerFirst(e)) throw new IllegalStateException("Deque full"); } /** {@collect.stats} * @throws IllegalStateException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public void addLast(E e) { if (!offerLast(e)) throw new IllegalStateException("Deque full"); } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} */ public boolean offerFirst(E e) { if (e == null) throw new NullPointerException(); lock.lock(); try { return linkFirst(e); } finally { lock.unlock(); } } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} */ public boolean offerLast(E e) { if (e == null) throw new NullPointerException(); lock.lock(); try { return linkLast(e); } finally { lock.unlock(); } } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public void putFirst(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); lock.lock(); try { while (!linkFirst(e)) notFull.await(); } finally { lock.unlock(); } } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public void putLast(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); lock.lock(); try { while (!linkLast(e)) notFull.await(); } finally { lock.unlock(); } } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) throw new NullPointerException(); long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { for (;;) { if (linkFirst(e)) return true; if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); } } finally { lock.unlock(); } } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) throw new NullPointerException(); long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { for (;;) { if (linkLast(e)) return true; if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); } } finally { lock.unlock(); } } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E removeFirst() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E removeLast() { E x = pollLast(); if (x == null) throw new NoSuchElementException(); return x; } public E pollFirst() { lock.lock(); try { return unlinkFirst(); } finally { lock.unlock(); } } public E pollLast() { lock.lock(); try { return unlinkLast(); } finally { lock.unlock(); } } public E takeFirst() throws InterruptedException { lock.lock(); try { E x; while ( (x = unlinkFirst()) == null) notEmpty.await(); return x; } finally { lock.unlock(); } } public E takeLast() throws InterruptedException { lock.lock(); try { E x; while ( (x = unlinkLast()) == null) notEmpty.await(); return x; } finally { lock.unlock(); } } public E pollFirst(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { for (;;) { E x = unlinkFirst(); if (x != null) return x; if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } } finally { lock.unlock(); } } public E pollLast(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { for (;;) { E x = unlinkLast(); if (x != null) return x; if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } } finally { lock.unlock(); } } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E getFirst() { E x = peekFirst(); if (x == null) throw new NoSuchElementException(); return x; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E getLast() { E x = peekLast(); if (x == null) throw new NoSuchElementException(); return x; } public E peekFirst() { lock.lock(); try { return (first == null) ? null : first.item; } finally { lock.unlock(); } } public E peekLast() { lock.lock(); try { return (last == null) ? null : last.item; } finally { lock.unlock(); } } public boolean removeFirstOccurrence(Object o) { if (o == null) return false; lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) { if (o.equals(p.item)) { unlink(p); return true; } } return false; } finally { lock.unlock(); } } public boolean removeLastOccurrence(Object o) { if (o == null) return false; lock.lock(); try { for (Node<E> p = last; p != null; p = p.prev) { if (o.equals(p.item)) { unlink(p); return true; } } return false; } finally { lock.unlock(); } } // BlockingQueue methods /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque unless it would * violate capacity restrictions. When using a capacity-restricted deque, * it is generally preferable to use method {@link #offer(Object) offer}. * * <p>This method is equivalent to {@link #addLast}. * {@description.close} * * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws NullPointerException if the specified element is null */ public boolean add(E e) { addLast(e); return true; } /** {@collect.stats} * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { return offerLast(e); } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public void put(E e) throws InterruptedException { putLast(e); } /** {@collect.stats} * @throws NullPointerException {@inheritDoc} * @throws InterruptedException {@inheritDoc} */ public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return offerLast(e, timeout, unit); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque. * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst() removeFirst}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ public E remove() { return removeFirst(); } public E poll() { return pollFirst(); } public E take() throws InterruptedException { return takeFirst(); } public E poll(long timeout, TimeUnit unit) throws InterruptedException { return pollFirst(timeout, unit); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque. This method differs from {@link #peek peek} only in that * it throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst() getFirst}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ public E element() { return getFirst(); } public E peek() { return peekFirst(); } /** {@collect.stats} * {@description.open} * Returns the number of additional elements that this deque can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this deque * less the current <tt>size</tt> of this deque. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting <tt>remainingCapacity</tt> * because it may be the case that another thread is about to * insert or remove an element. * {@description.close} */ public int remainingCapacity() { lock.lock(); try { return capacity - count; } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) c.add(p.item); int n = count; count = 0; first = last = null; notFull.signalAll(); return n; } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); lock.lock(); try { int n = 0; while (n < maxElements && first != null) { c.add(first.item); first.prev = null; first = first.next; --count; ++n; } if (first == null) last = null; notFull.signalAll(); return n; } finally { lock.unlock(); } } // Stack methods /** {@collect.stats} * @throws IllegalStateException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public void push(E e) { addFirst(e); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E pop() { return removeFirst(); } // Collection methods /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}. * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if this deque changed as a result of the call */ public boolean remove(Object o) { return removeFirstOccurrence(o); } /** {@collect.stats} * {@description.open} * Returns the number of elements in this deque. * {@description.close} * * @return the number of elements in this deque */ public int size() { lock.lock(); try { return count; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this deque * @return <tt>true</tt> if this deque contains the specified element */ public boolean contains(Object o) { if (o == null) return false; lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) if (o.equals(p.item)) return true; return false; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Variant of removeFirstOccurrence needed by iterator.remove. * Searches for the node, not its contents. * {@description.close} */ boolean removeNode(Node<E> e) { lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) { if (p == e) { unlink(p); return true; } } return false; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this deque, in * proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this deque */ public Object[] toArray() { lock.lock(); try { Object[] a = new Object[count]; int k = 0; for (Node<E> p = first; p != null; p = p.next) a[k++] = p.item; return a; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this deque, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the deque fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this deque. * * <p>If this deque fits in the specified array with room to spare * (i.e., the array has more elements than this deque), the element in * the array immediately following the end of the deque is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a deque known to contain only strings. * The following code can be used to dump the deque into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the deque are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this deque * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this deque * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { lock.lock(); try { if (a.length < count) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), count ); int k = 0; for (Node<E> p = first; p != null; p = p.next) a[k++] = (T)p.item; if (a.length > k) a[k] = null; return a; } finally { lock.unlock(); } } public String toString() { lock.lock(); try { return super.toString(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Atomically removes all of the elements from this deque. * The deque will be empty after this call returns. * {@description.close} */ public void clear() { lock.lock(); try { first = last = null; count = 0; notFull.signalAll(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * {@description.close} * {@property.open synchronized} * 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. * {@property.close} * * @return an iterator over the elements in this deque in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque in reverse * sequential order. The elements will be returned in order from * last (tail) to first (head). * {@description.close} * {@property.open synchronized} * 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. * {@property.close} */ public Iterator<E> descendingIterator() { return new DescendingItr(); } /** {@collect.stats} * {@description.open} * Base class for Iterators for LinkedBlockingDeque * {@description.close} */ private abstract class AbstractItr implements Iterator<E> { /** {@collect.stats} * {@description.open} * The next node to return in next * {@description.close} */ Node<E> next; /** {@collect.stats} * {@description.open} * nextItem holds on to item fields because once we claim that * an element exists in hasNext(), we must return item read * under lock (in advance()) even if it was in the process of * being removed when hasNext() was called. * {@description.close} */ E nextItem; /** {@collect.stats} * {@description.open} * Node returned by most recent call to next. Needed by remove. * Reset to null if this element is deleted by a call to remove. * {@description.close} */ private Node<E> lastRet; AbstractItr() { advance(); // set to initial position } /** {@collect.stats} * {@description.open} * Advances next, or if not yet initialized, sets to first node. * Implemented to move forward vs backward in the two subclasses. * {@description.close} */ abstract void advance(); public boolean hasNext() { return next != null; } public E next() { if (next == null) throw new NoSuchElementException(); lastRet = next; E x = nextItem; advance(); return x; } public void remove() { Node<E> n = lastRet; if (n == null) throw new IllegalStateException(); lastRet = null; // Note: removeNode rescans looking for this node to make // sure it was not already removed. Otherwise, trying to // re-remove could corrupt list. removeNode(n); } } /** {@collect.stats} * {@description.open} * Forward iterator * {@description.close} */ private class Itr extends AbstractItr { void advance() { final ReentrantLock lock = LinkedBlockingDeque.this.lock; lock.lock(); try { next = (next == null)? first : next.next; nextItem = (next == null)? null : next.item; } finally { lock.unlock(); } } } /** {@collect.stats} * {@description.open} * Descending iterator for LinkedBlockingDeque * {@description.close} */ private class DescendingItr extends AbstractItr { void advance() { final ReentrantLock lock = LinkedBlockingDeque.this.lock; lock.lock(); try { next = (next == null)? last : next.prev; nextItem = (next == null)? null : next.item; } finally { lock.unlock(); } } } /** {@collect.stats} * {@description.open} * Save the state of this deque to a stream (that is, serialize it). * {@description.close} * * @serialData The capacity (int), followed by elements (each an * <tt>Object</tt>) in the proper order, followed by a null * @param s the stream */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { lock.lock(); try { // Write out capacity and any hidden stuff s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = first; p != null; p = p.next) s.writeObject(p.item); // Use trailing null as sentinel s.writeObject(null); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Reconstitute this deque from a stream (that is, * deserialize it). * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); count = 0; first = null; last = null; // Read in all elements and place in queue for (;;) { E item = (E)s.readObject(); if (item == null) break; add(item); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; /** {@collect.stats} * {@description.open} * A cancellable asynchronous computation. This class provides a base * implementation of {@link Future}, with methods to start and cancel * a computation, query to see if the computation is complete, and * retrieve the result of the computation. The result can only be * retrieved when the computation has completed; the <tt>get</tt> * method will block if the computation has not yet completed. Once * the computation has completed, the computation cannot be restarted * or cancelled. * * <p>A <tt>FutureTask</tt> can be used to wrap a {@link Callable} or * {@link java.lang.Runnable} object. Because <tt>FutureTask</tt> * implements <tt>Runnable</tt>, a <tt>FutureTask</tt> can be * submitted to an {@link Executor} for execution. * * <p>In addition to serving as a standalone class, this class provides * <tt>protected</tt> functionality that may be useful when creating * customized task classes. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this FutureTask's <tt>get</tt> method */ public class FutureTask<V> implements RunnableFuture<V> { /** {@collect.stats} * {@description.open} * Synchronization control for FutureTask * {@description.close} */ private final Sync sync; /** {@collect.stats} * {@description.open} * Creates a <tt>FutureTask</tt> that will, upon running, execute the * given <tt>Callable</tt>. * {@description.close} * * @param callable the callable task * @throws NullPointerException if callable is null */ public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); sync = new Sync(callable); } /** {@collect.stats} * {@description.open} * Creates a <tt>FutureTask</tt> that will, upon running, execute the * given <tt>Runnable</tt>, and arrange that <tt>get</tt> will return the * given result on successful completion. * {@description.close} * * @param runnable the runnable task * @param result the result to return on successful completion. If * you don't need a particular result, consider using * constructions of the form: * <tt>Future&lt;?&gt; f = new FutureTask&lt;Object&gt;(runnable, null)</tt> * @throws NullPointerException if runnable is null */ public FutureTask(Runnable runnable, V result) { sync = new Sync(Executors.callable(runnable, result)); } public boolean isCancelled() { return sync.innerIsCancelled(); } public boolean isDone() { return sync.innerIsDone(); } public boolean cancel(boolean mayInterruptIfRunning) { return sync.innerCancel(mayInterruptIfRunning); } /** {@collect.stats} * @throws CancellationException {@inheritDoc} */ public V get() throws InterruptedException, ExecutionException { return sync.innerGet(); } /** {@collect.stats} * @throws CancellationException {@inheritDoc} */ public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return sync.innerGet(unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Protected method invoked when this task transitions to state * <tt>isDone</tt> (whether normally or via cancellation). The * default implementation does nothing. Subclasses may override * this method to invoke completion callbacks or perform * bookkeeping. Note that you can query status inside the * implementation of this method to determine whether this task * has been cancelled. * {@description.close} */ protected void done() { } /** {@collect.stats} * {@description.open} * Sets the result of this Future to the given value unless * this future has already been set or has been cancelled. * This method is invoked internally by the <tt>run</tt> method * upon successful completion of the computation. * {@description.close} * @param v the value */ protected void set(V v) { sync.innerSet(v); } /** {@collect.stats} * {@description.open} * Causes this future to report an <tt>ExecutionException</tt> * with the given throwable as its cause, unless this Future has * already been set or has been cancelled. * This method is invoked internally by the <tt>run</tt> method * upon failure of the computation. * {@description.close} * @param t the cause of failure */ protected void setException(Throwable t) { sync.innerSetException(t); } // The following (duplicated) doc comment can be removed once // // 6270645: Javadoc comments should be inherited from most derived // superinterface or superclass // is fixed. /** {@collect.stats} * {@description.open} * Sets this Future to the result of its computation * unless it has been cancelled. * {@description.close} */ public void run() { sync.innerRun(); } /** {@collect.stats} * {@description.open} * Executes the computation without setting its result, and then * resets this Future to initial state, failing to do so if the * computation encounters an exception or is cancelled. This is * designed for use with tasks that intrinsically execute more * than once. * {@description.close} * @return true if successfully run and reset */ protected boolean runAndReset() { return sync.innerRunAndReset(); } /** {@collect.stats} * {@description.open} * Synchronization control for FutureTask. Note that this must be * a non-static inner class in order to invoke the protected * <tt>done</tt> method. For clarity, all inner class support * methods are same as outer, prefixed with "inner". * * Uses AQS sync state to represent run status * {@description.close} */ private final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -7828117401763700385L; /** {@collect.stats} * {@description.open} * State value representing that task is ready to run * {@description.close} */ private static final int READY = 0; /** {@collect.stats} * {@description.open} * State value representing that task is running * {@description.close} */ private static final int RUNNING = 1; /** {@collect.stats} * {@description.open} * State value representing that task ran * {@description.close} */ private static final int RAN = 2; /** {@collect.stats} * {@description.open} * State value representing that task was cancelled * {@description.close} */ private static final int CANCELLED = 4; /** {@collect.stats} * {@description.open} * The underlying callable * {@description.close} */ private final Callable<V> callable; /** {@collect.stats} * {@description.open} * The result to return from get() * {@description.close} */ private V result; /** {@collect.stats} * {@description.open} * The exception to throw from get() * {@description.close} */ private Throwable exception; /** {@collect.stats} * {@description.open} * The thread running task. When nulled after set/cancel, this * indicates that the results are accessible. Must be * volatile, to ensure visibility upon completion. * {@description.close} */ private volatile Thread runner; Sync(Callable<V> callable) { this.callable = callable; } private boolean ranOrCancelled(int state) { return (state & (RAN | CANCELLED)) != 0; } /** {@collect.stats} * {@description.open} * Implements AQS base acquire to succeed if ran or cancelled * {@description.close} */ protected int tryAcquireShared(int ignore) { return innerIsDone() ? 1 : -1; } /** {@collect.stats} * {@description.open} * Implements AQS base release to always signal after setting * final done status by nulling runner thread. * {@description.close} */ protected boolean tryReleaseShared(int ignore) { runner = null; return true; } boolean innerIsCancelled() { return getState() == CANCELLED; } boolean innerIsDone() { return ranOrCancelled(getState()) && runner == null; } V innerGet() throws InterruptedException, ExecutionException { acquireSharedInterruptibly(0); if (getState() == CANCELLED) throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; } V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException { if (!tryAcquireSharedNanos(0, nanosTimeout)) throw new TimeoutException(); if (getState() == CANCELLED) throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; } void innerSet(V v) { for (;;) { int s = getState(); if (s == RAN) return; if (s == CANCELLED) { // aggressively release to set runner to null, // in case we are racing with a cancel request // that will try to interrupt runner releaseShared(0); return; } if (compareAndSetState(s, RAN)) { result = v; releaseShared(0); done(); return; } } } void innerSetException(Throwable t) { for (;;) { int s = getState(); if (s == RAN) return; if (s == CANCELLED) { // aggressively release to set runner to null, // in case we are racing with a cancel request // that will try to interrupt runner releaseShared(0); return; } if (compareAndSetState(s, RAN)) { exception = t; releaseShared(0); done(); return; } } } boolean innerCancel(boolean mayInterruptIfRunning) { for (;;) { int s = getState(); if (ranOrCancelled(s)) return false; if (compareAndSetState(s, CANCELLED)) break; } if (mayInterruptIfRunning) { Thread r = runner; if (r != null) r.interrupt(); } releaseShared(0); done(); return true; } void innerRun() { if (!compareAndSetState(READY, RUNNING)) return; runner = Thread.currentThread(); if (getState() == RUNNING) { // recheck after setting thread V result; try { result = callable.call(); } catch (Throwable ex) { setException(ex); return; } set(result); } else { releaseShared(0); // cancel } } boolean innerRunAndReset() { if (!compareAndSetState(READY, RUNNING)) return false; try { runner = Thread.currentThread(); if (getState() == RUNNING) callable.call(); // don't set result runner = null; return compareAndSetState(RUNNING, READY); } catch (Throwable ex) { setException(ex); return false; } } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A {@link CompletionService} that uses a supplied {@link Executor} * to execute tasks. This class arranges that submitted tasks are, * upon completion, placed on a queue accessible using {@code take}. * The class is lightweight enough to be suitable for transient use * when processing groups of tasks. * * <p> * * <b>Usage Examples.</b> * * Suppose you have a set of solvers for a certain problem, each * returning a value of some type {@code Result}, and would like to * run them concurrently, processing the results of each of them that * return a non-null value, in some method {@code use(Result r)}. You * could write this as: * * <pre> {@code * void solve(Executor e, * Collection<Callable<Result>> solvers) * throws InterruptedException, ExecutionException { * CompletionService<Result> ecs * = new ExecutorCompletionService<Result>(e); * for (Callable<Result> s : solvers) * ecs.submit(s); * int n = solvers.size(); * for (int i = 0; i < n; ++i) { * Result r = ecs.take().get(); * if (r != null) * use(r); * } * }}</pre> * * Suppose instead that you would like to use the first non-null result * of the set of tasks, ignoring any that encounter exceptions, * and cancelling all other tasks when the first one is ready: * * <pre> {@code * void solve(Executor e, * Collection<Callable<Result>> solvers) * throws InterruptedException { * CompletionService<Result> ecs * = new ExecutorCompletionService<Result>(e); * int n = solvers.size(); * List<Future<Result>> futures * = new ArrayList<Future<Result>>(n); * Result result = null; * try { * for (Callable<Result> s : solvers) * futures.add(ecs.submit(s)); * for (int i = 0; i < n; ++i) { * try { * Result r = ecs.take().get(); * if (r != null) { * result = r; * break; * } * } catch (ExecutionException ignore) {} * } * } * finally { * for (Future<Result> f : futures) * f.cancel(true); * } * * if (result != null) * use(result); * }}</pre> * {@description.close} */ public class ExecutorCompletionService<V> implements CompletionService<V> { private final Executor executor; private final AbstractExecutorService aes; private final BlockingQueue<Future<V>> completionQueue; /** {@collect.stats} * {@description.open} * FutureTask extension to enqueue upon completion * {@description.close} */ 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); } /** {@collect.stats} * {@description.open} * Creates an ExecutorCompletionService using the supplied * executor for base task execution and a * {@link LinkedBlockingQueue} as a completion queue. * {@description.close} * * @param executor the executor to use * @throws NullPointerException if executor is {@code null} */ public ExecutorCompletionService(Executor executor) { if (executor == null) throw new NullPointerException(); this.executor = executor; this.aes = (executor instanceof AbstractExecutorService) ? (AbstractExecutorService) executor : null; this.completionQueue = new LinkedBlockingQueue<Future<V>>(); } /** {@collect.stats} * {@description.open} * Creates an ExecutorCompletionService using the supplied * executor for base task execution and the supplied queue as its * completion queue. * {@description.close} * * @param executor the executor to use * @param completionQueue the queue to use as the completion queue * normally one dedicated for use by this service. This * queue is treated as unbounded -- failed attempted * {@code Queue.add} operations for completed taskes cause * them not to be retrievable. * @throws NullPointerException if executor or completionQueue are {@code null} */ 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); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ /** {@collect.stats} * {@description.open} * Utility classes commonly useful in concurrent programming. This * package includes a few small standardized extensible frameworks, as * well as some classes that provide useful functionality and are * otherwise tedious or difficult to implement. Here are brief * descriptions of the main components. See also the * {@link java.util.concurrent.locks} and * {@link java.util.concurrent.atomic} packages. * * <h2>Executors</h2> * * <b>Interfaces.</b> * * {@link java.util.concurrent.Executor} is a simple standardized * interface for defining custom thread-like subsystems, including * thread pools, asynchronous IO, and lightweight task frameworks. * Depending on which concrete Executor class is being used, tasks may * execute in a newly created thread, an existing task-execution thread, * or the thread calling {@link java.util.concurrent.Executor#execute * execute}, and may execute sequentially or concurrently. * * {@link java.util.concurrent.ExecutorService} provides a more * complete asynchronous task execution framework. An * ExecutorService manages queuing and scheduling of tasks, * and allows controlled shutdown. * * The {@link java.util.concurrent.ScheduledExecutorService} * subinterface and associated interfaces add support for * delayed and periodic task execution. ExecutorServices * provide methods arranging asynchronous execution of any * function expressed as {@link java.util.concurrent.Callable}, * the result-bearing analog of {@link java.lang.Runnable}. * * A {@link java.util.concurrent.Future} returns the results of * a function, allows determination of whether execution has * completed, and provides a means to cancel execution. * * A {@link java.util.concurrent.RunnableFuture} is a {@code Future} * that possesses a {@code run} method that upon execution, * sets its results. * * <p> * * <b>Implementations.</b> * * Classes {@link java.util.concurrent.ThreadPoolExecutor} and * {@link java.util.concurrent.ScheduledThreadPoolExecutor} * provide tunable, flexible thread pools. * * The {@link java.util.concurrent.Executors} class provides * factory methods for the most common kinds and configurations * of Executors, as well as a few utility methods for using * them. Other utilities based on {@code Executors} include the * concrete class {@link java.util.concurrent.FutureTask} * providing a common extensible implementation of Futures, and * {@link java.util.concurrent.ExecutorCompletionService}, that * assists in coordinating the processing of groups of * asynchronous tasks. * * <h2>Queues</h2> * * The {@link java.util.concurrent.ConcurrentLinkedQueue} class * supplies an efficient scalable thread-safe non-blocking FIFO * queue. * * <p>Five implementations in {@code java.util.concurrent} support * the extended {@link java.util.concurrent.BlockingQueue} * interface, that defines blocking versions of put and take: * {@link java.util.concurrent.LinkedBlockingQueue}, * {@link java.util.concurrent.ArrayBlockingQueue}, * {@link java.util.concurrent.SynchronousQueue}, * {@link java.util.concurrent.PriorityBlockingQueue}, and * {@link java.util.concurrent.DelayQueue}. * The different classes cover the most common usage contexts * for producer-consumer, messaging, parallel tasking, and * related concurrent designs. * * <p>The {@link java.util.concurrent.BlockingDeque} interface * extends {@code BlockingQueue} to support both FIFO and LIFO * (stack-based) operations. * Class {@link java.util.concurrent.LinkedBlockingDeque} * provides an implementation. * * <h2>Timing</h2> * * The {@link java.util.concurrent.TimeUnit} class provides * multiple granularities (including nanoseconds) for * specifying and controlling time-out based operations. Most * classes in the package contain operations based on time-outs * in addition to indefinite waits. In all cases that * time-outs are used, the time-out specifies the minimum time * that the method should wait before indicating that it * timed-out. Implementations make a &quot;best effort&quot; * to detect time-outs as soon as possible after they occur. * However, an indefinite amount of time may elapse between a * time-out being detected and a thread actually executing * again after that time-out. All methods that accept timeout * parameters treat values less than or equal to zero to mean * not to wait at all. To wait "forever", you can use a value * of {@code Long.MAX_VALUE}. * * <h2>Synchronizers</h2> * * Four classes aid common special-purpose synchronization idioms. * {@link java.util.concurrent.Semaphore} is a classic concurrency tool. * {@link java.util.concurrent.CountDownLatch} is a very simple yet very * common utility for blocking until a given number of signals, events, * or conditions hold. A {@link java.util.concurrent.CyclicBarrier} is a * resettable multiway synchronization point useful in some styles of * parallel programming. An {@link java.util.concurrent.Exchanger} allows * two threads to exchange objects at a rendezvous point, and is useful * in several pipeline designs. * * <h2>Concurrent Collections</h2> * * Besides Queues, this package supplies Collection implementations * designed for use in multithreaded contexts: * {@link java.util.concurrent.ConcurrentHashMap}, * {@link java.util.concurrent.ConcurrentSkipListMap}, * {@link java.util.concurrent.ConcurrentSkipListSet}, * {@link java.util.concurrent.CopyOnWriteArrayList}, and * {@link java.util.concurrent.CopyOnWriteArraySet}. * When many threads are expected to access a given collection, a * {@code ConcurrentHashMap} is normally preferable to a synchronized * {@code HashMap}, and a {@code ConcurrentSkipListMap} is normally * preferable to a synchronized {@code TreeMap}. * A {@code CopyOnWriteArrayList} is preferable to a synchronized * {@code ArrayList} when the expected number of reads and traversals * greatly outnumber the number of updates to a list. * <p>The "Concurrent" prefix used with some classes in this package * is a shorthand indicating several differences from similar * "synchronized" classes. For example {@code java.util.Hashtable} and * {@code Collections.synchronizedMap(new HashMap())} are * synchronized. But {@link * java.util.concurrent.ConcurrentHashMap} is "concurrent". A * concurrent collection is thread-safe, but not governed by a * single exclusion lock. In the particular case of * ConcurrentHashMap, it safely permits any number of * concurrent reads as well as a tunable number of concurrent * writes. "Synchronized" classes can be useful when you need * to prevent all access to a collection via a single lock, at * the expense of poorer scalability. In other cases in which * multiple threads are expected to access a common collection, * "concurrent" versions are normally preferable. And * unsynchronized collections are preferable when either * collections are unshared, or are accessible only when * holding other locks. * * <p>Most concurrent Collection implementations (including most * Queues) also differ from the usual java.util conventions in that * their Iterators provide <em>weakly consistent</em> rather than * fast-fail traversal. A weakly consistent iterator is thread-safe, * but does not necessarily freeze the collection while iterating, so * it may (or may not) reflect any updates since the iterator was * created. * * <h2><a name="MemoryVisibility">Memory Consistency Properties</a></h2> * * <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html"> * Chapter 17 of the Java Language Specification</a> defines the * <i>happens-before</i> relation on memory operations such as reads and * writes of shared variables. The results of a write by one thread are * guaranteed to be visible to a read by another thread only if the write * operation <i>happens-before</i> the read operation. The * {@code synchronized} and {@code volatile} constructs, as well as the * {@code Thread.start()} and {@code Thread.join()} methods, can form * <i>happens-before</i> relationships. In particular: * * <ul> * <li>Each action in a thread <i>happens-before</i> every action in that * thread that comes later in the program's order. * * <li>An unlock ({@code synchronized} block or method exit) of a * monitor <i>happens-before</i> every subsequent lock ({@code synchronized} * block or method entry) of that same monitor. And because * the <i>happens-before</i> relation is transitive, all actions * of a thread prior to unlocking <i>happen-before</i> all actions * subsequent to any thread locking that monitor. * * <li>A write to a {@code volatile} field <i>happens-before</i> every * subsequent read of that same field. Writes and reads of * {@code volatile} fields have similar memory consistency effects * as entering and exiting monitors, but do <em>not</em> entail * mutual exclusion locking. * * <li>A call to {@code start} on a thread <i>happens-before</i> any * action in the started thread. * * <li>All actions in a thread <i>happen-before</i> any other thread * successfully returns from a {@code join} on that thread. * * </ul> * * * The methods of all classes in {@code java.util.concurrent} and its * subpackages extend these guarantees to higher-level * synchronization. In particular: * * <ul> * * <li>Actions in a thread prior to placing an object into any concurrent * collection <i>happen-before</i> actions subsequent to the access or * removal of that element from the collection in another thread. * * <li>Actions in a thread prior to the submission of a {@code Runnable} * to an {@code Executor} <i>happen-before</i> its execution begins. * Similarly for {@code Callables} submitted to an {@code ExecutorService}. * * <li>Actions taken by the asynchronous computation represented by a * {@code Future} <i>happen-before</i> actions subsequent to the * retrieval of the result via {@code Future.get()} in another thread. * * <li>Actions prior to "releasing" synchronizer methods such as * {@code Lock.unlock}, {@code Semaphore.release}, and * {@code CountDownLatch.countDown} <i>happen-before</i> actions * subsequent to a successful "acquiring" method such as * {@code Lock.lock}, {@code Semaphore.acquire}, * {@code Condition.await}, and {@code CountDownLatch.await} on the * same synchronizer object in another thread. * * <li>For each pair of threads that successfully exchange objects via * an {@code Exchanger}, actions prior to the {@code exchange()} * in each thread <i>happen-before</i> those subsequent to the * corresponding {@code exchange()} in another thread. * * <li>Actions prior to calling {@code CyclicBarrier.await} * <i>happen-before</i> actions performed by the barrier action, and * actions performed by the barrier action <i>happen-before</i> actions * subsequent to a successful return from the corresponding {@code await} * in other threads. * * </ul> * {@description.close} * * @since 1.5 */ package java.util.concurrent;
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.Collection; import java.util.Queue; /** {@collect.stats} * {@description.open} * A {@link java.util.Queue} that additionally supports operations * that wait for the queue to become non-empty when retrieving an * element, and wait for space to become available in the queue when * storing an element. * * <p><tt>BlockingQueue</tt> methods come in four forms, with different ways * of handling operations that cannot be satisfied immediately, but may be * satisfied at some point in the future: * one throws an exception, the second returns a special value (either * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third * blocks the current thread indefinitely until the operation can succeed, * and the fourth blocks for only a given maximum time limit before giving * up. These methods are summarized in the following table: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * <td ALIGN=CENTER><em>Blocks</em></td> * <td ALIGN=CENTER><em>Times out</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link #add add(e)}</td> * <td>{@link #offer offer(e)}</td> * <td>{@link #put put(e)}</td> * <td>{@link #offer(Object, long, TimeUnit) offer(e, time, unit)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link #remove remove()}</td> * <td>{@link #poll poll()}</td> * <td>{@link #take take()}</td> * <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link #element element()}</td> * <td>{@link #peek peek()}</td> * <td><em>not applicable</em></td> * <td><em>not applicable</em></td> * </tr> * </table> * * <p>A <tt>BlockingQueue</tt> does not accept <tt>null</tt> elements. * Implementations throw <tt>NullPointerException</tt> on attempts * to <tt>add</tt>, <tt>put</tt> or <tt>offer</tt> a <tt>null</tt>. A * <tt>null</tt> is used as a sentinel value to indicate failure of * <tt>poll</tt> operations. * * <p>A <tt>BlockingQueue</tt> may be capacity bounded. At any given * time it may have a <tt>remainingCapacity</tt> beyond which no * additional elements can be <tt>put</tt> without blocking. * A <tt>BlockingQueue</tt> without any intrinsic capacity constraints always * reports a remaining capacity of <tt>Integer.MAX_VALUE</tt>. * * <p> <tt>BlockingQueue</tt> implementations are designed to be used * primarily for producer-consumer queues, but additionally support * the {@link java.util.Collection} interface. So, for example, it is * possible to remove an arbitrary element from a queue using * <tt>remove(x)</tt>. However, such operations are in general * <em>not</em> performed very efficiently, and are intended for only * occasional use, such as when a queued message is cancelled. * * <p> <tt>BlockingQueue</tt> implementations are thread-safe. All * queuing methods achieve their effects atomically using internal * locks or other forms of concurrency control. However, the * <em>bulk</em> Collection operations <tt>addAll</tt>, * <tt>containsAll</tt>, <tt>retainAll</tt> and <tt>removeAll</tt> are * <em>not</em> necessarily performed atomically unless specified * otherwise in an implementation. So it is possible, for example, for * <tt>addAll(c)</tt> to fail (throwing an exception) after adding * only some of the elements in <tt>c</tt>. * * <p>A <tt>BlockingQueue</tt> does <em>not</em> intrinsically support * any kind of &quot;close&quot; or &quot;shutdown&quot; operation to * indicate that no more items will be added. The needs and usage of * such features tend to be implementation-dependent. For example, a * common tactic is for producers to insert special * <em>end-of-stream</em> or <em>poison</em> objects, that are * interpreted accordingly when taken by consumers. * * <p> * Usage example, based on a typical producer-consumer scenario. * Note that a <tt>BlockingQueue</tt> can safely be used with multiple * producers and multiple consumers. * <pre> * class Producer implements Runnable { * private final BlockingQueue queue; * Producer(BlockingQueue q) { queue = q; } * public void run() { * try { * while (true) { queue.put(produce()); } * } catch (InterruptedException ex) { ... handle ...} * } * Object produce() { ... } * } * * class Consumer implements Runnable { * private final BlockingQueue queue; * Consumer(BlockingQueue q) { queue = q; } * public void run() { * try { * while (true) { consume(queue.take()); } * } catch (InterruptedException ex) { ... handle ...} * } * void consume(Object x) { ... } * } * * class Setup { * void main() { * BlockingQueue q = new SomeQueueImplementation(); * Producer p = new Producer(q); * Consumer c1 = new Consumer(q); * Consumer c2 = new Consumer(q); * new Thread(p).start(); * new Thread(c1).start(); * new Thread(c2).start(); * } * } * </pre> * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code BlockingQueue} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code BlockingQueue} in another thread. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public interface BlockingQueue<E> extends Queue<E> { /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue if it is possible to do * so immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if no space is currently available. * When using a capacity-restricted queue, it is generally preferable to * use {@link #offer(Object) offer}. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this queue */ boolean add(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue if it is possible to do * so immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and <tt>false</tt> if no space is currently * available. When using a capacity-restricted queue, this method is * generally preferable to {@link #add}, which can fail to insert an * element only by throwing an exception. * {@description.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this queue, else * <tt>false</tt> * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this queue */ boolean offer(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue, waiting if necessary * for space to become available. * {@description.close} * * @param e the element to add * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this queue */ void put(E e) throws InterruptedException; /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue, waiting up to the * specified wait time if necessary for space to become available. * {@description.close} * * @param e the element to add * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return <tt>true</tt> if successful, or <tt>false</tt> if * the specified waiting time elapses before space is available * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this queue */ boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, waiting if necessary * until an element becomes available. * {@description.close} * * @return the head of this queue * @throws InterruptedException if interrupted while waiting */ E take() throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, waiting up to the * specified wait time if necessary for an element to become available. * {@description.close} * * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return the head of this queue, or <tt>null</tt> if the * specified waiting time elapses before an element is available * @throws InterruptedException if interrupted while waiting */ E poll(long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Returns the number of additional elements that this queue can ideally * (in the absence of memory or resource constraints) accept without * blocking, or <tt>Integer.MAX_VALUE</tt> if there is no intrinsic * limit. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting <tt>remainingCapacity</tt> * because it may be the case that another thread is about to * insert or remove an element. * {@description.close} * * @return the remaining capacity */ int remainingCapacity(); /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element <tt>e</tt> such * that <tt>o.equals(e)</tt>, if this queue contains one or more such * elements. * Returns <tt>true</tt> if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call * @throws ClassCastException if the class of the specified element * is incompatible with this queue (optional) * @throws NullPointerException if the specified element is null (optional) */ boolean remove(Object o); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this queue contains the specified element. * More formally, returns <tt>true</tt> if and only if this queue contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this queue * @return <tt>true</tt> if this queue contains the specified element * @throws ClassCastException if the class of the specified element * is incompatible with this queue (optional) * @throws NullPointerException if the specified element is null (optional) */ public boolean contains(Object o); /** {@collect.stats} * {@description.open} * Removes all available elements from this queue and adds them * to the given collection. This operation may be more * efficient than repeatedly polling this queue. A failure * encountered while attempting to add elements to * collection <tt>c</tt> may result in elements being in neither, * either or both collections when the associated exception is * thrown. * {@description.close} * {@property.open formal:java.util.concurrent.BlockingQueue_SelfDrain} * Attempts to drain a queue to itself result in * <tt>IllegalArgumentException</tt>. * {@property.close} * {@property.open synchronized} * Further, the behavior of * this operation is undefined if the specified collection is * modified while the operation is in progress. * {@property.close} * * @param c the collection to transfer elements into * @return the number of elements transferred * @throws UnsupportedOperationException if addition of elements * is not supported by the specified collection * @throws ClassCastException if the class of an element of this queue * prevents it from being added to the specified collection * @throws NullPointerException if the specified collection is null * @throws IllegalArgumentException if the specified collection is this * queue, or some property of an element of this queue prevents * it from being added to the specified collection */ int drainTo(Collection<? super E> c); /** {@collect.stats} * {@description.open} * Removes at most the given number of available elements from * this queue and adds them to the given collection. A failure * encountered while attempting to add elements to * collection <tt>c</tt> may result in elements being in neither, * either or both collections when the associated exception is * thrown. * {@description.close} * {@property.open formal:java.util.concurrent.BlockingQueue_SelfDrain} * Attempts to drain a queue to itself result in * <tt>IllegalArgumentException</tt>. * {@property.close} * {@property.open synchronized} * Further, the behavior of * this operation is undefined if the specified collection is * modified while the operation is in progress. * {@property.close} * * @param c the collection to transfer elements into * @param maxElements the maximum number of elements to transfer * @return the number of elements transferred * @throws UnsupportedOperationException if addition of elements * is not supported by the specified collection * @throws ClassCastException if the class of an element of this queue * prevents it from being added to the specified collection * @throws NullPointerException if the specified collection is null * @throws IllegalArgumentException if the specified collection is this * queue, or some property of an element of this queue prevents * it from being added to the specified collection */ int drainTo(Collection<? super E> c, int maxElements); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * A scalable concurrent {@link NavigableSet} implementation based on * a {@link ConcurrentSkipListMap}. The elements of the set are kept * sorted according to their {@linkplain Comparable natural ordering}, * or by a {@link Comparator} provided at set creation time, depending * on which constructor is used. * * <p>This implementation provides expected average <i>log(n)</i> time * cost for the <tt>contains</tt>, <tt>add</tt>, and <tt>remove</tt> * operations and their variants. Insertion, removal, and access * operations safely execute concurrently by multiple threads. * {@description.close} * {@property.open synchronized} * Iterators are <i>weakly consistent</i>, returning elements * reflecting the state of the set at some point at or since the * creation of the iterator. They do <em>not</em> throw {@link * ConcurrentModificationException}, and may proceed concurrently with * other operations. * {@property.close} * {@description.open} * Ascending ordered views and their iterators are * faster than descending ones. * * <p>Beware that, unlike in most collections, the <tt>size</tt> * method is <em>not</em> a constant-time operation. Because of the * asynchronous nature of these sets, determining the current number * of elements requires a traversal of the elements. Additionally, the * bulk operations <tt>addAll</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt>, and <tt>containsAll</tt> are <em>not</em> * guaranteed to be performed atomically. For example, an iterator * operating concurrently with an <tt>addAll</tt> operation might view * only some of the added elements. * * <p>This class and its iterators implement all of the * <em>optional</em> methods of the {@link Set} and {@link Iterator} * interfaces. Like most other concurrent collection implementations, * this class does not permit the use of <tt>null</tt> elements, * because <tt>null</tt> arguments and return values cannot be reliably * distinguished from the absence of elements. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Doug Lea * @param <E> the type of elements maintained by this set * @since 1.6 */ public class ConcurrentSkipListSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable { private static final long serialVersionUID = -2479143111061671589L; /** {@collect.stats} * {@description.open} * The underlying map. Uses Boolean.TRUE as value for each * element. This field is declared final for the sake of thread * safety, which entails some ugliness in clone() * {@description.close} */ private final ConcurrentNavigableMap<E,Object> m; /** {@collect.stats} * {@description.open} * Constructs a new, empty set that orders its elements according to * their {@linkplain Comparable natural ordering}. * {@description.close} */ public ConcurrentSkipListSet() { m = new ConcurrentSkipListMap<E,Object>(); } /** {@collect.stats} * {@description.open} * Constructs a new, empty set that orders its elements according to * the specified comparator. * {@description.close} * * @param comparator the comparator that will be used to order this set. * If <tt>null</tt>, the {@linkplain Comparable natural * ordering} of the elements will be used. */ public ConcurrentSkipListSet(Comparator<? super E> comparator) { m = new ConcurrentSkipListMap<E,Object>(comparator); } /** {@collect.stats} * {@description.open} * Constructs a new set containing the elements in the specified * collection, that orders its elements according to their * {@linkplain Comparable natural ordering}. * {@description.close} * * @param c The elements that will comprise the new set * @throws ClassCastException if the elements in <tt>c</tt> are * not {@link Comparable}, or are not mutually comparable * @throws NullPointerException if the specified collection or any * of its elements are null */ public ConcurrentSkipListSet(Collection<? extends E> c) { m = new ConcurrentSkipListMap<E,Object>(); addAll(c); } /** {@collect.stats} * {@description.open} * Constructs a new set containing the same elements and using the * same ordering as the specified sorted set. * {@description.close} * * @param s sorted set whose elements will comprise the new set * @throws NullPointerException if the specified sorted set or any * of its elements are null */ public ConcurrentSkipListSet(SortedSet<E> s) { m = new ConcurrentSkipListMap<E,Object>(s.comparator()); addAll(s); } /** {@collect.stats} * {@description.open} * For use by submaps * {@description.close} */ ConcurrentSkipListSet(ConcurrentNavigableMap<E,Object> m) { this.m = m; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>ConcurrentSkipListSet</tt> * instance. (The elements themselves are not cloned.) * {@description.close} * * @return a shallow copy of this set */ public ConcurrentSkipListSet<E> clone() { ConcurrentSkipListSet<E> clone = null; try { clone = (ConcurrentSkipListSet<E>) super.clone(); clone.setMap(new ConcurrentSkipListMap(m)); } catch (CloneNotSupportedException e) { throw new InternalError(); } return clone; } /* ---------------- Set operations -------------- */ /** {@collect.stats} * {@description.open} * Returns the number of elements in this set. If this set * contains more than <tt>Integer.MAX_VALUE</tt> elements, it * returns <tt>Integer.MAX_VALUE</tt>. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these sets, determining the current * number of elements requires traversing them all to count them. * Additionally, it is possible for the size to change during * execution of this method, in which case the returned result * will be inaccurate. Thus, this method is typically not very * useful in concurrent applications. * {@description.close} * * @return the number of elements in this set */ public int size() { return m.size(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return m.isEmpty(); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * More formally, returns <tt>true</tt> if and only if this set * contains an element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this set * @return <tt>true</tt> if this set contains the specified element * @throws ClassCastException if the specified element cannot be * compared with the elements currently in this set * @throws NullPointerException if the specified element is null */ public boolean contains(Object o) { return m.containsKey(o); } /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * the set contains no element <tt>e2</tt> such that <tt>e.equals(e2)</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the * specified element * @throws ClassCastException if <tt>e</tt> cannot be compared * with the elements currently in this set * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return m.putIfAbsent(e, Boolean.TRUE) == null; } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * More formally, removes an element <tt>e</tt> such that * <tt>o.equals(e)</tt>, if this set contains such an element. * Returns <tt>true</tt> if this set contained the element (or * equivalently, if this set changed as a result of the call). * (This set will not contain the element once the call returns.) * {@description.close} * * @param o object to be removed from this set, if present * @return <tt>true</tt> if this set contained the specified element * @throws ClassCastException if <tt>o</tt> cannot be compared * with the elements currently in this set * @throws NullPointerException if the specified element is null */ public boolean remove(Object o) { return m.remove(o, Boolean.TRUE); } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * {@description.close} */ public void clear() { m.clear(); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set in ascending order. * {@description.close} * * @return an iterator over the elements in this set in ascending order */ public Iterator<E> iterator() { return m.navigableKeySet().iterator(); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set in descending order. * {@description.close} * * @return an iterator over the elements in this set in descending order */ public Iterator<E> descendingIterator() { return m.descendingKeySet().iterator(); } /* ---------------- AbstractSet Overrides -------------- */ /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. Returns * <tt>true</tt> if the specified object is also a set, the two sets * have the same size, and every member of the specified set is * contained in this set (or equivalently, every member of this set is * contained in the specified set). This definition ensures that the * equals method works properly across different implementations of the * set interface. * {@description.close} * * @param o the object to be compared for equality with this set * @return <tt>true</tt> if the specified object is equal to this set */ public boolean equals(Object o) { // Override AbstractSet version to avoid calling size() if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; try { return containsAll(c) && c.containsAll(this); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in * the specified collection. If the specified collection is also * a set, this operation effectively modifies this set so that its * value is the <i>asymmetric set difference</i> of the two sets. * {@description.close} * * @param c collection containing elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws ClassCastException if the types of one or more elements in this * set are incompatible with the specified collection * @throws NullPointerException if the specified collection or any * of its elements are null */ public boolean removeAll(Collection<?> c) { // Override AbstractSet version to avoid unnecessary call to size() boolean modified = false; for (Iterator<?> i = c.iterator(); i.hasNext(); ) if (remove(i.next())) modified = true; return modified; } /* ---------------- Relational operations -------------- */ /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null */ public E lower(E e) { return m.lowerKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null */ public E floor(E e) { return m.floorKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null */ public E ceiling(E e) { return m.ceilingKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null */ public E higher(E e) { return m.higherKey(e); } public E pollFirst() { Map.Entry<E,Object> e = m.pollFirstEntry(); return e == null? null : e.getKey(); } public E pollLast() { Map.Entry<E,Object> e = m.pollLastEntry(); return e == null? null : e.getKey(); } /* ---------------- SortedSet operations -------------- */ public Comparator<? super E> comparator() { return m.comparator(); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E first() { return m.firstKey(); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E last() { return m.lastKey(); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} or * {@code toElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new ConcurrentSkipListSet<E> (m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new ConcurrentSkipListSet<E>(m.headMap(toElement, inclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new ConcurrentSkipListSet<E>(m.tailMap(fromElement, inclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} or * {@code toElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> headSet(E toElement) { return headSet(toElement, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} is null * @throws IllegalArgumentException {@inheritDoc} */ public NavigableSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } /** {@collect.stats} * {@description.open} * Returns a reverse order view of the elements contained in this set. * The descending set is backed by this set, so changes to the set are * reflected in the descending set, and vice-versa. * * <p>The returned set has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. * The expression {@code s.descendingSet().descendingSet()} returns a * view of {@code s} essentially equivalent to {@code s}. * {@description.close} * * @return a reverse order view of this set */ public NavigableSet<E> descendingSet() { return new ConcurrentSkipListSet(m.descendingMap()); } // Support for resetting map in clone private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long mapOffset; static { try { mapOffset = unsafe.objectFieldOffset (ConcurrentSkipListSet.class.getDeclaredField("m")); } catch (Exception ex) { throw new Error(ex); } } private void setMap(ConcurrentNavigableMap<E,Object> map) { unsafe.putObjectVolatile(this, mapOffset, map); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; /** {@collect.stats} * {@description.open} * Provides default implementations of {@link ExecutorService} * execution methods. This class implements the <tt>submit</tt>, * <tt>invokeAny</tt> and <tt>invokeAll</tt> methods using a * {@link RunnableFuture} returned by <tt>newTaskFor</tt>, which defaults * to the {@link FutureTask} class provided in this package. For example, * the implementation of <tt>submit(Runnable)</tt> creates an * associated <tt>RunnableFuture</tt> that is executed and * returned. Subclasses may override the <tt>newTaskFor</tt> methods * to return <tt>RunnableFuture</tt> implementations other than * <tt>FutureTask</tt>. * * <p> <b>Extension example</b>. Here is a sketch of a class * that customizes {@link ThreadPoolExecutor} to use * a <tt>CustomTask</tt> class instead of the default <tt>FutureTask</tt>: * <pre> * public class CustomThreadPoolExecutor extends ThreadPoolExecutor { * * static class CustomTask&lt;V&gt; implements RunnableFuture&lt;V&gt; {...} * * protected &lt;V&gt; RunnableFuture&lt;V&gt; newTaskFor(Callable&lt;V&gt; c) { * return new CustomTask&lt;V&gt;(c); * } * protected &lt;V&gt; RunnableFuture&lt;V&gt; newTaskFor(Runnable r, V v) { * return new CustomTask&lt;V&gt;(r, v); * } * // ... add constructors, etc. * } * </pre> * {@description.close} * @since 1.5 * @author Doug Lea */ public abstract class AbstractExecutorService implements ExecutorService { /** {@collect.stats} * {@description.open} * Returns a <tt>RunnableFuture</tt> for the given runnable and default * value. * {@description.close} * * @param runnable the runnable task being wrapped * @param value the default value for the returned future * @return a <tt>RunnableFuture</tt> which when run will run the * underlying runnable and which, as a <tt>Future</tt>, will yield * the given value as its result and provide for cancellation of * the underlying task. * @since 1.6 */ protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { return new FutureTask<T>(runnable, value); } /** {@collect.stats} * {@description.open} * Returns a <tt>RunnableFuture</tt> for the given callable task. * {@description.close} * * @param callable the callable task being wrapped * @return a <tt>RunnableFuture</tt> which when run will call the * underlying callable and which, as a <tt>Future</tt>, will yield * the callable's result as its result and provide for * cancellation of the underlying task. * @since 1.6 */ protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { return new FutureTask<T>(callable); } public Future<?> submit(Runnable task) { if (task == null) throw new NullPointerException(); RunnableFuture<Object> ftask = newTaskFor(task, null); execute(ftask); return ftask; } public <T> Future<T> submit(Runnable task, T result) { if (task == null) throw new NullPointerException(); RunnableFuture<T> ftask = newTaskFor(task, result); execute(ftask); return ftask; } public <T> Future<T> submit(Callable<T> task) { if (task == null) throw new NullPointerException(); RunnableFuture<T> ftask = newTaskFor(task); execute(ftask); return ftask; } /** {@collect.stats} * {@description.open} * the main mechanics of invokeAny. * {@description.close} */ private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks, boolean timed, long nanos) throws InterruptedException, ExecutionException, TimeoutException { if (tasks == null) throw new NullPointerException(); int ntasks = tasks.size(); if (ntasks == 0) throw new IllegalArgumentException(); List<Future<T>> futures= new ArrayList<Future<T>>(ntasks); ExecutorCompletionService<T> ecs = new ExecutorCompletionService<T>(this); // For efficiency, especially in executors with limited // parallelism, check to see if previously submitted tasks are // done before submitting more of them. This interleaving // plus the exception mechanics account for messiness of main // loop. try { // Record exceptions so that if we fail to obtain any // result, we can throw the last exception we got. ExecutionException ee = null; long lastTime = (timed)? System.nanoTime() : 0; Iterator<? extends Callable<T>> it = tasks.iterator(); // Start one task for sure; the rest incrementally futures.add(ecs.submit(it.next())); --ntasks; int active = 1; for (;;) { Future<T> f = ecs.poll(); if (f == null) { if (ntasks > 0) { --ntasks; futures.add(ecs.submit(it.next())); ++active; } else if (active == 0) break; else if (timed) { f = ecs.poll(nanos, TimeUnit.NANOSECONDS); if (f == null) throw new TimeoutException(); long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; } else f = ecs.take(); } if (f != null) { --active; try { return f.get(); } catch (InterruptedException ie) { throw ie; } catch (ExecutionException eex) { ee = eex; } catch (RuntimeException rex) { ee = new ExecutionException(rex); } } } if (ee == null) ee = new ExecutionException(); throw ee; } finally { for (Future<T> f : futures) f.cancel(true); } } public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { try { return doInvokeAny(tasks, false, 0); } catch (TimeoutException cannotHappen) { assert false; return null; } } public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return doInvokeAny(tasks, true, unit.toNanos(timeout)); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { if (tasks == null) throw new NullPointerException(); List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size()); boolean done = false; try { for (Callable<T> t : tasks) { RunnableFuture<T> f = newTaskFor(t); futures.add(f); execute(f); } for (Future<T> f : futures) { if (!f.isDone()) { try { f.get(); } catch (CancellationException ignore) { } catch (ExecutionException ignore) { } } } done = true; return futures; } finally { if (!done) for (Future<T> f : futures) f.cancel(true); } } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { if (tasks == null || unit == null) throw new NullPointerException(); long nanos = unit.toNanos(timeout); List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size()); boolean done = false; try { for (Callable<T> t : tasks) futures.add(newTaskFor(t)); long lastTime = System.nanoTime(); // Interleave time checks and calls to execute in case // executor doesn't have any/much parallelism. Iterator<Future<T>> it = futures.iterator(); while (it.hasNext()) { execute((Runnable)(it.next())); long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) return futures; } for (Future<T> f : futures) { if (!f.isDone()) { if (nanos <= 0) return futures; try { f.get(nanos, TimeUnit.NANOSECONDS); } catch (CancellationException ignore) { } catch (ExecutionException ignore) { } catch (TimeoutException toe) { return futures; } long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; } } done = true; return futures; } finally { if (!done) for (Future<T> f : futures) f.cancel(true); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * Exception thrown when attempting to retrieve the result of a task * that aborted by throwing an exception. This exception can be * inspected using the {@link #getCause()} method. * {@description.close} * * @see Future * @since 1.5 * @author Doug Lea */ public class ExecutionException extends Exception { private static final long serialVersionUID = 7830266012832686185L; /** {@collect.stats} * {@description.open} * Constructs an <tt>ExecutionException</tt> with no detail message. * The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause(Throwable) initCause}. * {@description.close} */ protected ExecutionException() { } /** {@collect.stats} * {@description.open} * Constructs an <tt>ExecutionException</tt> with the specified detail * message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause(Throwable) initCause}. * {@description.close} * * @param message the detail message */ protected ExecutionException(String message) { super(message); } /** {@collect.stats} * {@description.open} * Constructs an <tt>ExecutionException</tt> with the specified detail * message and cause. * {@description.close} * * @param message the detail message * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method) */ public ExecutionException(String message, Throwable cause) { super(message, cause); } /** {@collect.stats} * {@description.open} * Constructs an <tt>ExecutionException</tt> with the specified cause. * The detail message is set to: * <pre> * (cause == null ? null : cause.toString())</pre> * (which typically contains the class and detail message of * <tt>cause</tt>). * {@description.close} * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method) */ public ExecutionException(Throwable cause) { super(cause); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; /** {@collect.stats} * {@description.open} * A synchronization aid that allows a set of threads to all wait for * each other to reach a common barrier point. CyclicBarriers are * useful in programs involving a fixed sized party of threads that * must occasionally wait for each other. The barrier is called * <em>cyclic</em> because it can be re-used after the waiting threads * are released. * * <p>A <tt>CyclicBarrier</tt> supports an optional {@link Runnable} command * that is run once per barrier point, after the last thread in the party * arrives, but before any threads are released. * This <em>barrier action</em> is useful * for updating shared-state before any of the parties continue. * * <p><b>Sample usage:</b> Here is an example of * using a barrier in a parallel decomposition design: * <pre> * class Solver { * final int N; * final float[][] data; * final CyclicBarrier barrier; * * class Worker implements Runnable { * int myRow; * Worker(int row) { myRow = row; } * public void run() { * while (!done()) { * processRow(myRow); * * try { * barrier.await(); * } catch (InterruptedException ex) { * return; * } catch (BrokenBarrierException ex) { * return; * } * } * } * } * * public Solver(float[][] matrix) { * data = matrix; * N = matrix.length; * barrier = new CyclicBarrier(N, * new Runnable() { * public void run() { * mergeRows(...); * } * }); * for (int i = 0; i < N; ++i) * new Thread(new Worker(i)).start(); * * waitUntilDone(); * } * } * </pre> * Here, each worker thread processes a row of the matrix then waits at the * barrier until all rows have been processed. When all rows are processed * the supplied {@link Runnable} barrier action is executed and merges the * rows. If the merger * determines that a solution has been found then <tt>done()</tt> will return * <tt>true</tt> and each worker will terminate. * * <p>If the barrier action does not rely on the parties being suspended when * it is executed, then any of the threads in the party could execute that * action when it is released. To facilitate this, each invocation of * {@link #await} returns the arrival index of that thread at the barrier. * You can then choose which thread should execute the barrier action, for * example: * <pre> if (barrier.await() == 0) { * // log the completion of this iteration * }</pre> * * <p>The <tt>CyclicBarrier</tt> uses an all-or-none breakage model * for failed synchronization attempts: If a thread leaves a barrier * point prematurely because of interruption, failure, or timeout, all * other threads waiting at that barrier point will also leave * abnormally via {@link BrokenBarrierException} (or * {@link InterruptedException} if they too were interrupted at about * the same time). * * <p>Memory consistency effects: Actions in a thread prior to calling * {@code await()} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions that are part of the barrier action, which in turn * <i>happen-before</i> actions following a successful return from the * corresponding {@code await()} in other threads. * {@description.close} * * @since 1.5 * @see CountDownLatch * * @author Doug Lea */ public class CyclicBarrier { /** {@collect.stats} * {@description.open} * Each use of the barrier is represented as a generation instance. * The generation changes whenever the barrier is tripped, or * is reset. There can be many generations associated with threads * using the barrier - due to the non-deterministic way the lock * may be allocated to waiting threads - but only one of these * can be active at a time (the one to which <tt>count</tt> applies) * and all the rest are either broken or tripped. * There need not be an active generation if there has been a break * but no subsequent reset. * {@description.close} */ private static class Generation { boolean broken = false; } /** {@collect.stats} * {@description.open} * The lock for guarding barrier entry * {@description.close} */ private final ReentrantLock lock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * Condition to wait on until tripped * {@description.close} */ private final Condition trip = lock.newCondition(); /** {@collect.stats} * {@description.open} * The number of parties * {@description.close} */ private final int parties; /* The command to run when tripped */ private final Runnable barrierCommand; /** {@collect.stats} * {@description.open} * The current generation * {@description.close} */ private Generation generation = new Generation(); /** {@collect.stats} * {@description.open} * Number of parties still waiting. Counts down from parties to 0 * on each generation. It is reset to parties on each new * generation or when broken. * {@description.close} */ private int count; /** {@collect.stats} * {@description.open} * Updates state on barrier trip and wakes up everyone. * Called only while holding lock. * {@description.close} */ private void nextGeneration() { // signal completion of last generation trip.signalAll(); // set up next generation count = parties; generation = new Generation(); } /** {@collect.stats} * {@description.open} * Sets current barrier generation as broken and wakes up everyone. * Called only while holding lock. * {@description.close} */ private void breakBarrier() { generation.broken = true; count = parties; trip.signalAll(); } /** {@collect.stats} * {@description.open} * Main barrier code, covering the various policies. * {@description.close} */ private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this.lock; lock.lock(); try { final Generation g = generation; if (g.broken) throw new BrokenBarrierException(); if (Thread.interrupted()) { breakBarrier(); throw new InterruptedException(); } int index = --count; if (index == 0) { // tripped boolean ranAction = false; try { final Runnable command = barrierCommand; if (command != null) command.run(); ranAction = true; nextGeneration(); return 0; } finally { if (!ranAction) breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out for (;;) { try { if (!timed) trip.await(); else if (nanos > 0L) nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { if (g == generation && ! g.broken) { breakBarrier(); throw ie; } else { // We're about to finish waiting even if we had not // been interrupted, so this interrupt is deemed to // "belong" to subsequent execution. Thread.currentThread().interrupt(); } } if (g.broken) throw new BrokenBarrierException(); if (g != generation) return index; if (timed && nanos <= 0L) { breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Creates a new <tt>CyclicBarrier</tt> that will trip when the * given number of parties (threads) are waiting upon it, and which * will execute the given barrier action when the barrier is tripped, * performed by the last thread entering the barrier. * {@description.close} * * @param parties the number of threads that must invoke {@link #await} * before the barrier is tripped * @param barrierAction the command to execute when the barrier is * tripped, or {@code null} if there is no action * @throws IllegalArgumentException if {@code parties} is less than 1 */ public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; } /** {@collect.stats} * {@description.open} * Creates a new <tt>CyclicBarrier</tt> that will trip when the * given number of parties (threads) are waiting upon it, and * does not perform a predefined action when the barrier is tripped. * {@description.close} * * @param parties the number of threads that must invoke {@link #await} * before the barrier is tripped * @throws IllegalArgumentException if {@code parties} is less than 1 */ public CyclicBarrier(int parties) { this(parties, null); } /** {@collect.stats} * {@description.open} * Returns the number of parties required to trip this barrier. * {@description.close} * * @return the number of parties required to trip this barrier */ public int getParties() { return parties; } /** {@collect.stats} * {@description.open} * Waits until all {@linkplain #getParties parties} have invoked * <tt>await</tt> on this barrier. * * <p>If the current thread is not the last to arrive then it is * disabled for thread scheduling purposes and lies dormant until * one of the following things happens: * <ul> * <li>The last thread arrives; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * one of the other waiting threads; or * <li>Some other thread times out while waiting for barrier; or * <li>Some other thread invokes {@link #reset} on this barrier. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when * <tt>await</tt> is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting, * then all other waiting threads will throw * {@link BrokenBarrierException} and the barrier is placed in the broken * state. * * <p>If the current thread is the last thread to arrive, and a * non-null barrier action was supplied in the constructor, then the * current thread runs the action before allowing the other threads to * continue. * If an exception occurs during the barrier action then that exception * will be propagated in the current thread and the barrier is placed in * the broken state. * {@description.close} * * @return the arrival index of the current thread, where index * <tt>{@link #getParties()} - 1</tt> indicates the first * to arrive and zero indicates the last to arrive * @throws InterruptedException if the current thread was interrupted * while waiting * @throws BrokenBarrierException if <em>another</em> thread was * interrupted or timed out while the current thread was * waiting, or the barrier was reset, or the barrier was * broken when {@code await} was called, or the barrier * action (if present) failed due an exception. */ public int await() throws InterruptedException, BrokenBarrierException { try { return dowait(false, 0L); } catch (TimeoutException toe) { throw new Error(toe); // cannot happen; } } /** {@collect.stats} * {@description.open} * Waits until all {@linkplain #getParties parties} have invoked * <tt>await</tt> on this barrier, or the specified waiting time elapses. * * <p>If the current thread is not the last to arrive then it is * disabled for thread scheduling purposes and lies dormant until * one of the following things happens: * <ul> * <li>The last thread arrives; or * <li>The specified timeout elapses; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * one of the other waiting threads; or * <li>Some other thread times out while waiting for barrier; or * <li>Some other thread invokes {@link #reset} on this barrier. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then {@link TimeoutException} * is thrown. If the time is less than or equal to zero, the * method will not wait at all. * * <p>If the barrier is {@link #reset} while any thread is waiting, * or if the barrier {@linkplain #isBroken is broken} when * <tt>await</tt> is invoked, or while any thread is waiting, then * {@link BrokenBarrierException} is thrown. * * <p>If any thread is {@linkplain Thread#interrupt interrupted} while * waiting, then all other waiting threads will throw {@link * BrokenBarrierException} and the barrier is placed in the broken * state. * * <p>If the current thread is the last thread to arrive, and a * non-null barrier action was supplied in the constructor, then the * current thread runs the action before allowing the other threads to * continue. * If an exception occurs during the barrier action then that exception * will be propagated in the current thread and the barrier is placed in * the broken state. * {@description.close} * * @param timeout the time to wait for the barrier * @param unit the time unit of the timeout parameter * @return the arrival index of the current thread, where index * <tt>{@link #getParties()} - 1</tt> indicates the first * to arrive and zero indicates the last to arrive * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the specified timeout elapses * @throws BrokenBarrierException if <em>another</em> thread was * interrupted or timed out while the current thread was * waiting, or the barrier was reset, or the barrier was broken * when {@code await} was called, or the barrier action (if * present) failed due an exception */ public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException { return dowait(true, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Queries if this barrier is in a broken state. * {@description.close} * * @return {@code true} if one or more parties broke out of this * barrier due to interruption or timeout since * construction or the last reset, or a barrier action * failed due to an exception; {@code false} otherwise. */ public boolean isBroken() { final ReentrantLock lock = this.lock; lock.lock(); try { return generation.broken; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Resets the barrier to its initial state. If any parties are * currently waiting at the barrier, they will return with a * {@link BrokenBarrierException}. Note that resets <em>after</em> * a breakage has occurred for other reasons can be complicated to * carry out; threads need to re-synchronize in some other way, * and choose one to perform the reset. It may be preferable to * instead create a new barrier for subsequent use. * {@description.close} */ public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); // break the current generation nextGeneration(); // start a new generation } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the number of parties currently waiting at the barrier. * This method is primarily useful for debugging and assertions. * {@description.close} * * @return the number of parties currently blocked in {@link #await} */ public int getNumberWaiting() { final ReentrantLock lock = this.lock; lock.lock(); try { return parties - count; } finally { lock.unlock(); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * An object that executes submitted {@link Runnable} tasks. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, etc. An <tt>Executor</tt> is normally used * instead of explicitly creating threads. For example, rather than * invoking <tt>new Thread(new(RunnableTask())).start()</tt> for each * of a set of tasks, you might use: * * <pre> * Executor executor = <em>anExecutor</em>; * executor.execute(new RunnableTask1()); * executor.execute(new RunnableTask2()); * ... * </pre> * * However, the <tt>Executor</tt> interface does not strictly * require that execution be asynchronous. In the simplest case, an * executor can run the submitted task immediately in the caller's * thread: * * <pre> * class DirectExecutor implements Executor { * public void execute(Runnable r) { * r.run(); * } * }</pre> * * More typically, tasks are executed in some thread other * than the caller's thread. The executor below spawns a new thread * for each task. * * <pre> * class ThreadPerTaskExecutor implements Executor { * public void execute(Runnable r) { * new Thread(r).start(); * } * }</pre> * * Many <tt>Executor</tt> implementations impose some sort of * limitation on how and when tasks are scheduled. The executor below * serializes the submission of tasks to a second executor, * illustrating a composite executor. * * <pre> * class SerialExecutor implements Executor { * final Queue&lt;Runnable&gt; tasks = new ArrayDeque&lt;Runnable&gt;(); * final Executor executor; * Runnable active; * * SerialExecutor(Executor executor) { * this.executor = executor; * } * * public synchronized void execute(final Runnable r) { * tasks.offer(new Runnable() { * public void run() { * try { * r.run(); * } finally { * scheduleNext(); * } * } * }); * if (active == null) { * scheduleNext(); * } * } * * protected synchronized void scheduleNext() { * if ((active = tasks.poll()) != null) { * executor.execute(active); * } * } * }</pre> * * The <tt>Executor</tt> implementations provided in this package * implement {@link ExecutorService}, which is a more extensive * interface. The {@link ThreadPoolExecutor} class provides an * extensible thread pool implementation. The {@link Executors} class * provides convenient factory methods for these Executors. * * <p>Memory consistency effects: Actions in a thread prior to * submitting a {@code Runnable} object to an {@code Executor} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * its execution begins, perhaps in another thread. * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface Executor { /** {@collect.stats} * {@description.open} * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the <tt>Executor</tt> implementation. * {@description.close} * * @param command the runnable task * @throws RejectedExecutionException if this task cannot be * accepted for execution. * @throws NullPointerException if command is null */ void execute(Runnable command); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import java.util.*; /** {@collect.stats} * {@description.open} * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on * linked nodes. * This queue orders elements FIFO (first-in-first-out). * The <em>head</em> of the queue is that element that has been on the * queue the longest time. * The <em>tail</em> of the queue is that element that has been on the * queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * Linked queues typically have higher throughput than array-based queues but * less predictable performance in most concurrent applications. * * <p> The optional capacity bound constructor argument serves as a * way to prevent excessive queue expansion. The capacity, if unspecified, * is equal to {@link Integer#MAX_VALUE}. Linked nodes are * dynamically created upon each insertion unless this would bring the * queue above capacity. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection * */ public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable { private static final long serialVersionUID = -6903933977591709194L; /* * A variant of the "two lock queue" algorithm. The putLock gates * entry to put (and offer), and has an associated condition for * waiting puts. Similarly for the takeLock. The "count" field * that they both rely on is maintained as an atomic to avoid * needing to get both locks in most cases. Also, to minimize need * for puts to get takeLock and vice-versa, cascading notifies are * used. When a put notices that it has enabled at least one take, * it signals taker. That taker in turn signals others if more * items have been entered since the signal. And symmetrically for * takes signalling puts. Operations such as remove(Object) and * iterators acquire both locks. */ /** {@collect.stats} * {@description.open} * Linked list node class * {@description.close} */ static class Node<E> { /** {@collect.stats} * {@description.open} * The item, volatile to ensure barrier separating write and read * {@description.close} */ volatile E item; Node<E> next; Node(E x) { item = x; } } /** {@collect.stats} * {@description.open} * The capacity bound, or Integer.MAX_VALUE if none * {@description.close} */ private final int capacity; /** {@collect.stats} * {@description.open} * Current number of elements * {@description.close} */ private final AtomicInteger count = new AtomicInteger(0); /** {@collect.stats} * {@description.open} * Head of linked list * {@description.close} */ private transient Node<E> head; /** {@collect.stats} * {@description.open} * Tail of linked list * {@description.close} */ private transient Node<E> last; /** {@collect.stats} * {@description.open} * Lock held by take, poll, etc * {@description.close} */ private final ReentrantLock takeLock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * Wait queue for waiting takes * {@description.close} */ private final Condition notEmpty = takeLock.newCondition(); /** {@collect.stats} * {@description.open} * Lock held by put, offer, etc * {@description.close} */ private final ReentrantLock putLock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * Wait queue for waiting puts * {@description.close} */ private final Condition notFull = putLock.newCondition(); /** {@collect.stats} * {@description.open} * Signals a waiting take. Called only from put/offer (which do not * otherwise ordinarily lock takeLock.) * {@description.close} */ private void signalNotEmpty() { final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { notEmpty.signal(); } finally { takeLock.unlock(); } } /** {@collect.stats} * {@description.open} * Signals a waiting put. Called only from take/poll. * {@description.close} */ private void signalNotFull() { final ReentrantLock putLock = this.putLock; putLock.lock(); try { notFull.signal(); } finally { putLock.unlock(); } } /** {@collect.stats} * {@description.open} * Creates a node and links it at end of queue. * {@description.close} * @param x the item */ private void insert(E x) { last = last.next = new Node<E>(x); } /** {@collect.stats} * {@description.open} * Removes a node from head of queue, * {@description.close} * @return the node */ private E extract() { Node<E> first = head.next; head = first; E x = first.item; first.item = null; return x; } /** {@collect.stats} * {@description.open} * Lock to prevent both puts and takes. * {@description.close} */ private void fullyLock() { putLock.lock(); takeLock.lock(); } /** {@collect.stats} * {@description.open} * Unlock to allow both puts and takes. * {@description.close} */ private void fullyUnlock() { takeLock.unlock(); putLock.unlock(); } /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of * {@link Integer#MAX_VALUE}. * {@description.close} */ public LinkedBlockingQueue() { this(Integer.MAX_VALUE); } /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingQueue</tt> with the given (fixed) capacity. * {@description.close} * * @param capacity the capacity of this queue * @throws IllegalArgumentException if <tt>capacity</tt> is not greater * than zero */ public LinkedBlockingQueue(int capacity) { if (capacity <= 0) throw new IllegalArgumentException(); this.capacity = capacity; last = head = new Node<E>(null); } /** {@collect.stats} * {@description.open} * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of * {@link Integer#MAX_VALUE}, initially containing the elements of the * given collection, * added in traversal order of the collection's iterator. * {@description.close} * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedBlockingQueue(Collection<? extends E> c) { this(Integer.MAX_VALUE); for (E e : c) add(e); } // this doc comment is overridden to remove the reference to collections // greater in size than Integer.MAX_VALUE /** {@collect.stats} * {@description.open} * Returns the number of elements in this queue. * {@description.close} * * @return the number of elements in this queue */ public int size() { return count.get(); } // this doc comment is a modified copy of the inherited doc comment, // without the reference to unlimited queues. /** {@collect.stats} * {@description.open} * Returns the number of additional elements that this queue can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this queue * less the current <tt>size</tt> of this queue. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting <tt>remainingCapacity</tt> * because it may be the case that another thread is about to * insert or remove an element. * {@description.close} */ public int remainingCapacity() { return capacity - count.get(); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue, waiting if * necessary for space to become available. * {@description.close} * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ 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. */ try { while (count.get() == capacity) notFull.await(); } catch (InterruptedException ie) { notFull.signal(); // propagate to a non-interrupted thread throw ie; } insert(e); c = count.getAndIncrement(); if (c + 1 < capacity) notFull.signal(); } finally { putLock.unlock(); } if (c == 0) signalNotEmpty(); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue, waiting if * necessary up to the specified wait time for space to become available. * {@description.close} * * @return <tt>true</tt> if successful, or <tt>false</tt> if * the specified waiting time elapses before space is available. * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ 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 { for (;;) { if (count.get() < capacity) { insert(e); c = count.getAndIncrement(); if (c + 1 < capacity) notFull.signal(); break; } if (nanos <= 0) return false; try { nanos = notFull.awaitNanos(nanos); } catch (InterruptedException ie) { notFull.signal(); // propagate to a non-interrupted thread throw ie; } } } finally { putLock.unlock(); } if (c == 0) signalNotEmpty(); return true; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the tail of this queue if it is * possible to do so immediately without exceeding the queue's capacity, * returning <tt>true</tt> upon success and <tt>false</tt> if this queue * is full. * When using a capacity-restricted queue, this method is generally * preferable to method {@link BlockingQueue#add add}, which can fail to * insert an element only by throwing an exception. * {@description.close} * * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { if (e == null) throw new NullPointerException(); final AtomicInteger count = this.count; if (count.get() == capacity) return false; int c = -1; final ReentrantLock putLock = this.putLock; putLock.lock(); try { if (count.get() < capacity) { insert(e); c = count.getAndIncrement(); if (c + 1 < capacity) notFull.signal(); } } finally { putLock.unlock(); } if (c == 0) signalNotEmpty(); return c >= 0; } public E take() throws InterruptedException { E x; int c = -1; final AtomicInteger count = this.count; final ReentrantLock takeLock = this.takeLock; takeLock.lockInterruptibly(); try { try { while (count.get() == 0) notEmpty.await(); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to a non-interrupted thread throw ie; } x = extract(); c = count.getAndDecrement(); if (c > 1) notEmpty.signal(); } finally { takeLock.unlock(); } if (c == capacity) signalNotFull(); return x; } 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 { for (;;) { if (count.get() > 0) { x = extract(); c = count.getAndDecrement(); if (c > 1) notEmpty.signal(); break; } if (nanos <= 0) return null; try { nanos = notEmpty.awaitNanos(nanos); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to a non-interrupted thread throw ie; } } } finally { takeLock.unlock(); } if (c == capacity) signalNotFull(); return x; } public E poll() { final AtomicInteger count = this.count; if (count.get() == 0) return null; E x = null; int c = -1; final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { if (count.get() > 0) { x = extract(); c = count.getAndDecrement(); if (c > 1) notEmpty.signal(); } } finally { takeLock.unlock(); } if (c == capacity) signalNotFull(); return x; } public E peek() { if (count.get() == 0) return null; final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { Node<E> first = head.next; if (first == null) return null; else return first.item; } finally { takeLock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element <tt>e</tt> such * that <tt>o.equals(e)</tt>, if this queue contains one or more such * elements. * Returns <tt>true</tt> if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call */ public boolean remove(Object o) { if (o == null) return false; boolean removed = false; fullyLock(); try { Node<E> trail = head; Node<E> p = head.next; while (p != null) { if (o.equals(p.item)) { removed = true; break; } trail = p; p = p.next; } if (removed) { p.item = null; trail.next = p.next; if (last == p) last = trail; if (count.getAndDecrement() == capacity) notFull.signalAll(); } } finally { fullyUnlock(); } return removed; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { fullyLock(); try { int size = count.get(); Object[] a = new Object[size]; int k = 0; for (Node<E> p = head.next; p != null; p = p.next) a[k++] = p.item; return a; } finally { fullyUnlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { fullyLock(); try { int size = count.get(); if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance (a.getClass().getComponentType(), size); int k = 0; for (Node p = head.next; p != null; p = p.next) a[k++] = (T)p.item; if (a.length > k) a[k] = null; return a; } finally { fullyUnlock(); } } public String toString() { fullyLock(); try { return super.toString(); } finally { fullyUnlock(); } } /** {@collect.stats} * {@description.open} * Atomically removes all of the elements from this queue. * The queue will be empty after this call returns. * {@description.close} */ public void clear() { fullyLock(); try { head.next = null; assert head.item == null; last = head; if (count.getAndSet(0) == capacity) notFull.signalAll(); } finally { fullyUnlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); Node<E> first; fullyLock(); try { first = head.next; head.next = null; assert head.item == null; last = head; if (count.getAndSet(0) == capacity) notFull.signalAll(); } finally { fullyUnlock(); } // Transfer the elements outside of locks int n = 0; for (Node<E> p = first; p != null; p = p.next) { c.add(p.item); p.item = null; ++n; } return n; } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); fullyLock(); try { int n = 0; Node<E> p = head.next; while (p != null && n < maxElements) { c.add(p.item); p.item = null; p = p.next; ++n; } if (n != 0) { head.next = p; assert head.item == null; if (p == null) last = head; if (count.getAndAdd(-n) == capacity) notFull.signalAll(); } return n; } finally { fullyUnlock(); } } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this queue in proper sequence. * {@description.close} * {@property.open} * 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. * {@property.close} * * @return an iterator over the elements in this queue in proper sequence */ public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { /* * Basic weak-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() { final ReentrantLock putLock = LinkedBlockingQueue.this.putLock; final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock; putLock.lock(); takeLock.lock(); try { current = head.next; if (current != null) currentElement = current.item; } finally { takeLock.unlock(); putLock.unlock(); } } public boolean hasNext() { return current != null; } public E next() { final ReentrantLock putLock = LinkedBlockingQueue.this.putLock; final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock; putLock.lock(); takeLock.lock(); try { if (current == null) throw new NoSuchElementException(); E x = currentElement; lastRet = current; current = current.next; if (current != null) currentElement = current.item; return x; } finally { takeLock.unlock(); putLock.unlock(); } } public void remove() { if (lastRet == null) throw new IllegalStateException(); final ReentrantLock putLock = LinkedBlockingQueue.this.putLock; final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock; putLock.lock(); takeLock.lock(); try { Node<E> node = lastRet; lastRet = null; Node<E> trail = head; Node<E> p = head.next; while (p != null && p != node) { trail = p; p = p.next; } if (p == node) { p.item = null; trail.next = p.next; if (last == p) last = trail; int c = count.getAndDecrement(); if (c == capacity) notFull.signalAll(); } } finally { takeLock.unlock(); putLock.unlock(); } } } /** {@collect.stats} * {@description.open} * Save the state to a stream (that is, serialize it). * {@description.close} * * @serialData The capacity is emitted (int), followed by all of * its elements (each an <tt>Object</tt>) in the proper order, * followed by a null * @param s the stream */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { fullyLock(); try { // Write out any hidden stuff, plus capacity s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = head.next; p != null; p = p.next) s.writeObject(p.item); // Use trailing null as sentinel s.writeObject(null); } finally { fullyUnlock(); } } /** {@collect.stats} * {@description.open} * Reconstitute this queue instance from a stream (that is, * deserialize it). * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in capacity, and any hidden stuff s.defaultReadObject(); count.set(0); last = head = new Node<E>(null); // Read in all elements and place in queue for (;;) { E item = (E)s.readObject(); if (item == null) break; add(item); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea, Bill Scherer, and Michael Scott with * assistance from members of JCP JSR-166 Expert Group and released to * the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.LockSupport; /** {@collect.stats} * {@description.open} * A synchronization point at which threads can pair and swap elements * within pairs. Each thread presents some object on entry to the * {@link #exchange exchange} method, matches with a partner thread, * and receives its partner's object on return. An Exchanger may be * viewed as a bidirectional form of a {@link SynchronousQueue}. * Exchangers may be useful in applications such as genetic algorithms * and pipeline designs. * * <p><b>Sample Usage:</b> * Here are the highlights of a class that uses an {@code Exchanger} * to swap buffers between threads so that the thread filling the * buffer gets a freshly emptied one when it needs it, handing off the * filled one to the thread emptying the buffer. * <pre>{@code * class FillAndEmpty { * Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>(); * DataBuffer initialEmptyBuffer = ... a made-up type * DataBuffer initialFullBuffer = ... * * class FillingLoop implements Runnable { * public void run() { * DataBuffer currentBuffer = initialEmptyBuffer; * try { * while (currentBuffer != null) { * addToBuffer(currentBuffer); * if (currentBuffer.isFull()) * currentBuffer = exchanger.exchange(currentBuffer); * } * } catch (InterruptedException ex) { ... handle ... } * } * } * * class EmptyingLoop implements Runnable { * public void run() { * DataBuffer currentBuffer = initialFullBuffer; * try { * while (currentBuffer != null) { * takeFromBuffer(currentBuffer); * if (currentBuffer.isEmpty()) * currentBuffer = exchanger.exchange(currentBuffer); * } * } catch (InterruptedException ex) { ... handle ...} * } * } * * void start() { * new Thread(new FillingLoop()).start(); * new Thread(new EmptyingLoop()).start(); * } * } * }</pre> * * <p>Memory consistency effects: For each pair of threads that * successfully exchange objects via an {@code Exchanger}, actions * prior to the {@code exchange()} in each thread * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * those subsequent to a return from the corresponding {@code exchange()} * in the other thread. * {@description.close} * * @since 1.5 * @author Doug Lea and Bill Scherer and Michael Scott * @param <V> The type of objects that may be exchanged */ public class Exchanger<V> { /* * Algorithm Description: * * The basic idea is to maintain a "slot", which is a reference to * a Node containing both an Item to offer and a "hole" waiting to * get filled in. If an incoming "occupying" thread sees that the * slot is null, it CAS'es (compareAndSets) a Node there and waits * for another to invoke exchange. That second "fulfilling" thread * sees that the slot is non-null, and so CASes it back to null, * also exchanging items by CASing the hole, plus waking up the * occupying thread if it is blocked. In each case CAS'es may * fail because a slot at first appears non-null but is null upon * CAS, or vice-versa. So threads may need to retry these * actions. * * This simple approach works great when there are only a few * threads using an Exchanger, but performance rapidly * deteriorates due to CAS contention on the single slot when * there are lots of threads using an exchanger. So instead we use * an "arena"; basically a kind of hash table with a dynamically * varying number of slots, any one of which can be used by * threads performing an exchange. Incoming threads pick slots * based on a hash of their Thread ids. If an incoming thread * fails to CAS in its chosen slot, it picks an alternative slot * instead. And similarly from there. If a thread successfully * CASes into a slot but no other thread arrives, it tries * another, heading toward the zero slot, which always exists even * if the table shrinks. The particular mechanics controlling this * are as follows: * * Waiting: Slot zero is special in that it is the only slot that * exists when there is no contention. A thread occupying slot * zero will block if no thread fulfills it after a short spin. * In other cases, occupying threads eventually give up and try * another slot. Waiting threads spin for a while (a period that * should be a little less than a typical context-switch time) * before either blocking (if slot zero) or giving up (if other * slots) and restarting. There is no reason for threads to block * unless there are unlikely to be any other threads present. * Occupants are mainly avoiding memory contention so sit there * quietly polling for a shorter period than it would take to * block and then unblock them. Non-slot-zero waits that elapse * because of lack of other threads waste around one extra * context-switch time per try, which is still on average much * faster than alternative approaches. * * Sizing: Usually, using only a few slots suffices to reduce * contention. Especially with small numbers of threads, using * too many slots can lead to just as poor performance as using * too few of them, and there's not much room for error. The * variable "max" maintains the number of slots actually in * use. It is increased when a thread sees too many CAS * failures. (This is analogous to resizing a regular hash table * based on a target load factor, except here, growth steps are * just one-by-one rather than proportional.) Growth requires * contention failures in each of three tried slots. Requiring * multiple failures for expansion copes with the fact that some * failed CASes are not due to contention but instead to simple * races between two threads or thread pre-emptions occurring * between reading and CASing. Also, very transient peak * contention can be much higher than the average sustainable * levels. The max limit is decreased on average 50% of the times * that a non-slot-zero wait elapses without being fulfilled. * Threads experiencing elapsed waits move closer to zero, so * eventually find existing (or future) threads even if the table * has been shrunk due to inactivity. The chosen mechanics and * thresholds for growing and shrinking are intrinsically * entangled with indexing and hashing inside the exchange code, * and can't be nicely abstracted out. * * Hashing: Each thread picks its initial slot to use in accord * with a simple hashcode. The sequence is the same on each * encounter by any given thread, but effectively random across * threads. Using arenas encounters the classic cost vs quality * tradeoffs of all hash tables. Here, we use a one-step FNV-1a * hash code based on the current thread's Thread.getId(), along * with a cheap approximation to a mod operation to select an * index. The downside of optimizing index selection in this way * is that the code is hardwired to use a maximum table size of * 32. But this value more than suffices for known platforms and * applications. * * Probing: On sensed contention of a selected slot, we probe * sequentially through the table, analogously to linear probing * after collision in a hash table. (We move circularly, in * reverse order, to mesh best with table growth and shrinkage * rules.) Except that to minimize the effects of false-alarms * and cache thrashing, we try the first selected slot twice * before moving. * * Padding: Even with contention management, slots are heavily * contended, so use cache-padding to avoid poor memory * performance. Because of this, slots are lazily constructed * only when used, to avoid wasting this space unnecessarily. * While isolation of locations is not much of an issue at first * in an application, as time goes on and garbage-collectors * perform compaction, slots are very likely to be moved adjacent * to each other, which can cause much thrashing of cache lines on * MPs unless padding is employed. * * This is an improvement of the algorithm described in the paper * "A Scalable Elimination-based Exchange Channel" by William * Scherer, Doug Lea, and Michael Scott in Proceedings of SCOOL05 * workshop. Available at: http://hdl.handle.net/1802/2104 */ /** {@collect.stats} * {@description.open} * The number of CPUs, for sizing and spin control * {@description.close} */ private static final int NCPU = Runtime.getRuntime().availableProcessors(); /** {@collect.stats} * {@description.open} * The capacity of the arena. Set to a value that provides more * than enough space to handle contention. On small machines * most slots won't be used, but it is still not wasted because * the extra space provides some machine-level address padding * to minimize interference with heavily CAS'ed Slot locations. * And on very large machines, performance eventually becomes * bounded by memory bandwidth, not numbers of threads/CPUs. * This constant cannot be changed without also modifying * indexing and hashing algorithms. * {@description.close} */ private static final int CAPACITY = 32; /** {@collect.stats} * {@description.open} * The value of "max" that will hold all threads without * contention. When this value is less than CAPACITY, some * otherwise wasted expansion can be avoided. * {@description.close} */ private static final int FULL = Math.max(0, Math.min(CAPACITY, NCPU / 2) - 1); /** {@collect.stats} * {@description.open} * The number of times to spin (doing nothing except polling a * memory location) before blocking or giving up while waiting to * be fulfilled. Should be zero on uniprocessors. On * multiprocessors, this value should be large enough so that two * threads exchanging items as fast as possible block only when * one of them is stalled (due to GC or preemption), but not much * longer, to avoid wasting CPU resources. Seen differently, this * value is a little over half the number of cycles of an average * context switch time on most systems. The value here is * approximately the average of those across a range of tested * systems. * {@description.close} */ private static final int SPINS = (NCPU == 1) ? 0 : 2000; /** {@collect.stats} * {@description.open} * The number of times to spin before blocking in timed waits. * Timed waits spin more slowly because checking the time takes * time. The best value relies mainly on the relative rate of * System.nanoTime vs memory accesses. The value is empirically * derived to work well across a variety of systems. * {@description.close} */ private static final int TIMED_SPINS = SPINS / 20; /** {@collect.stats} * {@description.open} * Sentinel item representing cancellation of a wait due to * interruption, timeout, or elapsed spin-waits. This value is * placed in holes on cancellation, and used as a return value * from waiting methods to indicate failure to set or get hole. * {@description.close} */ private static final Object CANCEL = new Object(); /** {@collect.stats} * {@description.open} * Value representing null arguments/returns from public * methods. This disambiguates from internal requirement that * holes start out as null to mean they are not yet set. * {@description.close} */ private static final Object NULL_ITEM = new Object(); /** {@collect.stats} * {@description.open} * Nodes hold partially exchanged data. This class * opportunistically subclasses AtomicReference to represent the * hole. So get() returns hole, and compareAndSet CAS'es value * into hole. This class cannot be parameterized as "V" because * of the use of non-V CANCEL sentinels. * {@description.close} */ private static final class Node extends AtomicReference<Object> { /** {@collect.stats} * {@description.open} * The element offered by the Thread creating this node. * {@description.close} */ public final Object item; /** {@collect.stats} * {@description.open} * The Thread waiting to be signalled; null until waiting. * {@description.close} */ public volatile Thread waiter; /** {@collect.stats} * {@description.open} * Creates node with given item and empty hole. * {@description.close} * @param item the item */ public Node(Object item) { this.item = item; } } /** {@collect.stats} * {@description.open} * A Slot is an AtomicReference with heuristic padding to lessen * cache effects of this heavily CAS'ed location. While the * padding adds noticeable space, all slots are created only on * demand, and there will be more than one of them only when it * would improve throughput more than enough to outweigh using * extra space. * {@description.close} */ private static final class Slot extends AtomicReference<Object> { // Improve likelihood of isolation on <= 64 byte cache lines long q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe; } /** {@collect.stats} * {@description.open} * Slot array. Elements are lazily initialized when needed. * Declared volatile to enable double-checked lazy construction. * {@description.close} */ private volatile Slot[] arena = new Slot[CAPACITY]; /** {@collect.stats} * {@description.open} * The maximum slot index being used. The value sometimes * increases when a thread experiences too many CAS contentions, * and sometimes decreases when a spin-wait elapses. Changes * are performed only via compareAndSet, to avoid stale values * when a thread happens to stall right before setting. * {@description.close} */ private final AtomicInteger max = new AtomicInteger(); /** {@collect.stats} * {@description.open} * Main exchange function, handling the different policy variants. * Uses Object, not "V" as argument and return value to simplify * handling of sentinel values. Callers from public methods decode * and cast accordingly. * {@description.close} * * @param item the (non-null) item to exchange * @param timed true if the wait is timed * @param nanos if timed, the maximum wait time * @return the other thread's item, or CANCEL if interrupted or timed out */ private Object doExchange(Object item, boolean timed, long nanos) { Node me = new Node(item); // Create in case occupying int index = hashIndex(); // Index of current slot int fails = 0; // Number of CAS failures for (;;) { Object y; // Contents of current slot Slot slot = arena[index]; if (slot == null) // Lazily initialize slots createSlot(index); // Continue loop to reread else if ((y = slot.get()) != null && // Try to fulfill slot.compareAndSet(y, null)) { Node you = (Node)y; // Transfer item if (you.compareAndSet(null, item)) { LockSupport.unpark(you.waiter); return you.item; } // Else cancelled; continue } else if (y == null && // Try to occupy slot.compareAndSet(null, me)) { if (index == 0) // Blocking wait for slot 0 return timed? awaitNanos(me, slot, nanos): await(me, slot); Object v = spinWait(me, slot); // Spin wait for non-0 if (v != CANCEL) return v; me = new Node(item); // Throw away cancelled node int m = max.get(); if (m > (index >>>= 1)) // Decrease index max.compareAndSet(m, m - 1); // Maybe shrink table } else if (++fails > 1) { // Allow 2 fails on 1st slot int m = max.get(); if (fails > 3 && m < FULL && max.compareAndSet(m, m + 1)) index = m + 1; // Grow on 3rd failed slot else if (--index < 0) index = m; // Circularly traverse } } } /** {@collect.stats} * {@description.open} * Returns a hash index for the current thread. Uses a one-step * FNV-1a hash code (http://www.isthe.com/chongo/tech/comp/fnv/) * based on the current thread's Thread.getId(). These hash codes * have more uniform distribution properties with respect to small * moduli (here 1-31) than do other simple hashing functions. * * <p>To return an index between 0 and max, we use a cheap * approximation to a mod operation, that also corrects for bias * due to non-power-of-2 remaindering (see {@link * java.util.Random#nextInt}). Bits of the hashcode are masked * with "nbits", the ceiling power of two of table size (looked up * in a table packed into three ints). If too large, this is * retried after rotating the hash by nbits bits, while forcing new * top bit to 0, which guarantees eventual termination (although * with a non-random-bias). This requires an average of less than * 2 tries for all table sizes, and has a maximum 2% difference * from perfectly uniform slot probabilities when applied to all * possible hash codes for sizes less than 32. * {@description.close} * * @return a per-thread-random index, 0 <= index < max */ private final int hashIndex() { long id = Thread.currentThread().getId(); int hash = (((int)(id ^ (id >>> 32))) ^ 0x811c9dc5) * 0x01000193; int m = max.get(); int nbits = (((0xfffffc00 >> m) & 4) | // Compute ceil(log2(m+1)) ((0x000001f8 >>> m) & 2) | // The constants hold ((0xffff00f2 >>> m) & 1)); // a lookup table int index; while ((index = hash & ((1 << nbits) - 1)) > m) // May retry on hash = (hash >>> nbits) | (hash << (33 - nbits)); // non-power-2 m return index; } /** {@collect.stats} * {@description.open} * Creates a new slot at given index. Called only when the slot * appears to be null. Relies on double-check using builtin * locks, since they rarely contend. This in turn relies on the * arena array being declared volatile. * {@description.close} * * @param index the index to add slot at */ private void createSlot(int index) { // Create slot outside of lock to narrow sync region Slot newSlot = new Slot(); Slot[] a = arena; synchronized (a) { if (a[index] == null) a[index] = newSlot; } } /** {@collect.stats} * {@description.open} * Tries to cancel a wait for the given node waiting in the given * slot, if so, helping clear the node from its slot to avoid * garbage retention. * {@description.close} * * @param node the waiting node * @param the slot it is waiting in * @return true if successfully cancelled */ private static boolean tryCancel(Node node, Slot slot) { if (!node.compareAndSet(null, CANCEL)) return false; if (slot.get() == node) // pre-check to minimize contention slot.compareAndSet(node, null); return true; } // Three forms of waiting. Each just different enough not to merge // code with others. /** {@collect.stats} * {@description.open} * Spin-waits for hole for a non-0 slot. Fails if spin elapses * before hole filled. Does not check interrupt, relying on check * in public exchange method to abort if interrupted on entry. * {@description.close} * * @param node the waiting node * @return on success, the hole; on failure, CANCEL */ private static Object spinWait(Node node, Slot slot) { int spins = SPINS; for (;;) { Object v = node.get(); if (v != null) return v; else if (spins > 0) --spins; else tryCancel(node, slot); } } /** {@collect.stats} * {@description.open} * Waits for (by spinning and/or blocking) and gets the hole * filled in by another thread. Fails if interrupted before * hole filled. * * When a node/thread is about to block, it sets its waiter field * and then rechecks state at least one more time before actually * parking, thus covering race vs fulfiller noticing that waiter * is non-null so should be woken. * * Thread interruption status is checked only surrounding calls to * park. The caller is assumed to have checked interrupt status * on entry. * {@description.close} * * @param node the waiting node * @return on success, the hole; on failure, CANCEL */ private static Object await(Node node, Slot slot) { Thread w = Thread.currentThread(); int spins = SPINS; for (;;) { Object v = node.get(); if (v != null) return v; else if (spins > 0) // Spin-wait phase --spins; else if (node.waiter == null) // Set up to block next node.waiter = w; else if (w.isInterrupted()) // Abort on interrupt tryCancel(node, slot); else // Block LockSupport.park(node); } } /** {@collect.stats} * {@description.open} * Waits for (at index 0) and gets the hole filled in by another * thread. Fails if timed out or interrupted before hole filled. * Same basic logic as untimed version, but a bit messier. * {@description.close} * * @param node the waiting node * @param nanos the wait time * @return on success, the hole; on failure, CANCEL */ private Object awaitNanos(Node node, Slot slot, long nanos) { int spins = TIMED_SPINS; long lastTime = 0; Thread w = null; for (;;) { Object v = node.get(); if (v != null) return v; long now = System.nanoTime(); if (w == null) w = Thread.currentThread(); else nanos -= now - lastTime; lastTime = now; if (nanos > 0) { if (spins > 0) --spins; else if (node.waiter == null) node.waiter = w; else if (w.isInterrupted()) tryCancel(node, slot); else LockSupport.parkNanos(node, nanos); } else if (tryCancel(node, slot) && !w.isInterrupted()) return scanOnTimeout(node); } } /** {@collect.stats} * {@description.open} * Sweeps through arena checking for any waiting threads. Called * only upon return from timeout while waiting in slot 0. When a * thread gives up on a timed wait, it is possible that a * previously-entered thread is still waiting in some other * slot. So we scan to check for any. This is almost always * overkill, but decreases the likelihood of timeouts when there * are other threads present to far less than that in lock-based * exchangers in which earlier-arriving threads may still be * waiting on entry locks. * {@description.close} * * @param node the waiting node * @return another thread's item, or CANCEL */ private Object scanOnTimeout(Node node) { Object y; for (int j = arena.length - 1; j >= 0; --j) { Slot slot = arena[j]; if (slot != null) { while ((y = slot.get()) != null) { if (slot.compareAndSet(y, null)) { Node you = (Node)y; if (you.compareAndSet(null, node.item)) { LockSupport.unpark(you.waiter); return you.item; } } } } } return CANCEL; } /** {@collect.stats} * {@description.open} * Creates a new Exchanger. * {@description.close} */ public Exchanger() { } /** {@collect.stats} * {@description.open} * Waits for another thread to arrive at this exchange point (unless * the current thread is {@linkplain Thread#interrupt interrupted}), * and then transfers the given object to it, receiving its object * in return. * * <p>If another thread is already waiting at the exchange point then * it is resumed for thread scheduling purposes and receives the object * passed in by the current thread. The current thread returns immediately, * receiving the object passed to the exchange by that other thread. * * <p>If no other thread is already waiting at the exchange then the * current thread is disabled for thread scheduling purposes and lies * dormant until one of two things happens: * <ul> * <li>Some other thread enters the exchange; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} the current * thread. * </ul> * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * for the exchange, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * {@description.close} * * @param x the object to exchange * @return the object provided by the other thread * @throws InterruptedException if the current thread was * interrupted while waiting */ public V exchange(V x) throws InterruptedException { if (!Thread.interrupted()) { Object v = doExchange(x == null? NULL_ITEM : x, false, 0); if (v == NULL_ITEM) return null; if (v != CANCEL) return (V)v; Thread.interrupted(); // Clear interrupt status on IE throw } throw new InterruptedException(); } /** {@collect.stats} * {@description.open} * Waits for another thread to arrive at this exchange point (unless * the current thread is {@linkplain Thread#interrupt interrupted} or * the specified waiting time elapses), and then transfers the given * object to it, receiving its object in return. * * <p>If another thread is already waiting at the exchange point then * it is resumed for thread scheduling purposes and receives the object * passed in by the current thread. The current thread returns immediately, * receiving the object passed to the exchange by that other thread. * * <p>If no other thread is already waiting at the exchange then the * current thread is disabled for thread scheduling purposes and lies * dormant until one of three things happens: * <ul> * <li>Some other thread enters the exchange; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * </ul> * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * for the exchange, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then {@link * TimeoutException} is thrown. If the time is less than or equal * to zero, the method will not wait at all. * {@description.close} * * @param x the object to exchange * @param timeout the maximum time to wait * @param unit the time unit of the <tt>timeout</tt> argument * @return the object provided by the other thread * @throws InterruptedException if the current thread was * interrupted while waiting * @throws TimeoutException if the specified waiting time elapses * before another thread enters the exchange */ public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!Thread.interrupted()) { Object v = doExchange(x == null? NULL_ITEM : x, true, unit.toNanos(timeout)); if (v == NULL_ITEM) return null; if (v != CANCEL) return (V)v; if (!Thread.interrupted()) throw new TimeoutException(); } throw new InterruptedException(); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A {@link ScheduledFuture} that is {@link Runnable}. Successful * execution of the <tt>run</tt> method causes completion of the * <tt>Future</tt> and allows access to its results. * {@description.close} * @see FutureTask * @see Executor * @since 1.6 * @author Doug Lea * @param <V> The result type returned by this Future's <tt>get</tt> method */ public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> { /** {@collect.stats} * {@description.open} * Returns true if this is a periodic task. A periodic task may * re-run according to some schedule. A non-periodic task can be * run only once. * {@description.close} * * @return true if this task is periodic */ boolean isPeriodic(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.Map; /** {@collect.stats} * {@description.open} * A {@link java.util.Map} providing additional atomic * <tt>putIfAbsent</tt>, <tt>remove</tt>, and <tt>replace</tt> methods. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code ConcurrentMap} as a key or value * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that object from * the {@code ConcurrentMap} in another thread. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values */ public interface ConcurrentMap<K, V> extends Map<K, V> { /** {@collect.stats} * {@description.open} * If the specified key is not already associated * with a value, associate it with the given value. * This is equivalent to * <pre> * if (!map.containsKey(key)) * return map.put(key, value); * else * return map.get(key);</pre> * except that the action is performed atomically. * {@description.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * <tt>null</tt> if there was no mapping for the key. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with the key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map * */ V putIfAbsent(K key, V value); /** {@collect.stats} * {@description.open} * Removes the entry for a key only if currently mapped to a given value. * This is equivalent to * <pre> * if (map.containsKey(key) &amp;&amp; map.get(key).equals(value)) { * map.remove(key); * return true; * } else return false;</pre> * except that the action is performed atomically. * {@description.close} * * @param key key with which the specified value is associated * @param value value expected to be associated with the specified key * @return <tt>true</tt> if the value was removed * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this map * @throws ClassCastException if the key or value is of an inappropriate * type for this map (optional) * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values (optional) */ boolean remove(Object key, Object value); /** {@collect.stats} * {@description.open} * Replaces the entry for a key only if currently mapped to a given value. * This is equivalent to * <pre> * if (map.containsKey(key) &amp;&amp; map.get(key).equals(oldValue)) { * map.put(key, newValue); * return true; * } else return false;</pre> * except that the action is performed atomically. * {@description.close} * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return <tt>true</tt> if the value was replaced * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by this map * @throws ClassCastException if the class of a specified key or value * prevents it from being stored in this map * @throws NullPointerException if a specified key or value is null, * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of a specified key * or value prevents it from being stored in this map */ boolean replace(K key, V oldValue, V newValue); /** {@collect.stats} * {@description.open} * Replaces the entry for a key only if currently mapped to some value. * This is equivalent to * <pre> * if (map.containsKey(key)) { * return map.put(key, value); * } else return null;</pre> * except that the action is performed atomically. * {@description.close} * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * <tt>null</tt> if there was no mapping for the key. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with the key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map */ V replace(K key, V value); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.lang.reflect.*; /** {@collect.stats} * {@description.open} * A reflection-based utility that enables atomic updates to * designated {@code volatile int} fields of designated classes. * This class is designed for use in atomic data structures in which * several fields of the same node are independently subject to atomic * updates. * * <p>Note that the guarantees of the {@code compareAndSet} * method in this class are weaker than in other atomic classes. * Because this class cannot ensure that all uses of the field * are appropriate for purposes of atomic access, it can * guarantee atomicity only with respect to other invocations of * {@code compareAndSet} and {@code set} on the same updater. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <T> The type of the object holding the updatable field */ public abstract class AtomicIntegerFieldUpdater<T> { /** {@collect.stats} * {@description.open} * Creates and returns an updater for objects with the given field. * The Class argument is needed to check that reflective types and * generic types match. * {@description.close} * * @param tclass the class of the objects holding the field * @param fieldName the name of the field to be updated * @return the updater * @throws IllegalArgumentException if the field is not a * volatile integer type * @throws RuntimeException with a nested reflection-based * exception if the class does not hold field or is the wrong type */ public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName) { return new AtomicIntegerFieldUpdaterImpl<U>(tclass, fieldName); } /** {@collect.stats} * {@description.open} * Protected do-nothing constructor for use by subclasses. * {@description.close} */ protected AtomicIntegerFieldUpdater() { } /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor */ public abstract boolean compareAndSet(T obj, int expect, int update); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor */ public abstract boolean weakCompareAndSet(T obj, int expect, int update); /** {@collect.stats} * {@description.open} * Sets the field of the given object managed by this updater to the * given updated value. This operation is guaranteed to act as a volatile * store with respect to subsequent invocations of {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value */ public abstract void set(T obj, int newValue); /** {@collect.stats} * {@description.open} * Eventually sets the field of the given object managed by this * updater to the given updated value. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value * @since 1.6 */ public abstract void lazySet(T obj, int newValue); /** {@collect.stats} * {@description.open} * Gets the current value held in the field of the given object managed * by this updater. * {@description.close} * * @param obj An object whose field to get * @return the current value */ public abstract int get(T obj); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given value and returns the old value. * {@description.close} * * @param obj An object whose field to get and set * @param newValue the new value * @return the previous value */ public int getAndSet(T obj, int newValue) { for (;;) { int current = get(obj); if (compareAndSet(obj, current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the previous value */ public int getAndIncrement(T obj) { for (;;) { int current = get(obj); int next = current + 1; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the previous value */ public int getAndDecrement(T obj) { for (;;) { int current = get(obj); int next = current - 1; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value of the field of * the given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @param delta the value to add * @return the previous value */ public int getAndAdd(T obj, int delta) { for (;;) { int current = get(obj); int next = current + delta; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the updated value */ public int incrementAndGet(T obj) { for (;;) { int current = get(obj); int next = current + 1; if (compareAndSet(obj, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the updated value */ public int decrementAndGet(T obj) { for (;;) { int current = get(obj); int next = current - 1; if (compareAndSet(obj, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value of the field of * the given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @param delta the value to add * @return the updated value */ public int addAndGet(T obj, int delta) { for (;;) { int current = get(obj); int next = current + delta; if (compareAndSet(obj, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Standard hotspot implementation using intrinsics * {@description.close} */ private static class AtomicIntegerFieldUpdaterImpl<T> extends AtomicIntegerFieldUpdater<T> { private static final Unsafe unsafe = Unsafe.getUnsafe(); private final long offset; private final Class<T> tclass; private final Class cclass; AtomicIntegerFieldUpdaterImpl(Class<T> tclass, String fieldName) { Field field = null; Class caller = null; int modifiers = 0; try { field = tclass.getDeclaredField(fieldName); caller = sun.reflect.Reflection.getCallerClass(3); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); } catch(Exception ex) { throw new RuntimeException(ex); } Class fieldt = field.getType(); if (fieldt != int.class) throw new IllegalArgumentException("Must be integer type"); if (!Modifier.isVolatile(modifiers)) throw new IllegalArgumentException("Must be volatile type"); this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null; this.tclass = tclass; offset = unsafe.objectFieldOffset(field); } private void fullCheck(T obj) { if (!tclass.isInstance(obj)) throw new ClassCastException(); if (cclass != null) ensureProtectedAccess(obj); } public boolean compareAndSet(T obj, int expect, int update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.compareAndSwapInt(obj, offset, expect, update); } public boolean weakCompareAndSet(T obj, int expect, int update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.compareAndSwapInt(obj, offset, expect, update); } public void set(T obj, int newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); unsafe.putIntVolatile(obj, offset, newValue); } public void lazySet(T obj, int newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); unsafe.putOrderedInt(obj, offset, newValue); } public final int get(T obj) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.getIntVolatile(obj, offset); } private void ensureProtectedAccess(T obj) { if (cclass.isInstance(obj)) { return; } throw new RuntimeException( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + tclass.getName() + " using an instance of " + obj.getClass().getName() ) ); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ /** {@collect.stats} * {@description.open} * A small toolkit of classes that support lock-free thread-safe * programming on single variables. In essence, the classes in this * package extend the notion of {@code volatile} values, fields, and * array elements to those that also provide an atomic conditional update * operation of the form: * * <pre> * boolean compareAndSet(expectedValue, updateValue); * </pre> * * <p>This method (which varies in argument types across different * classes) atomically sets a variable to the {@code updateValue} if it * currently holds the {@code expectedValue}, reporting {@code true} on * success. The classes in this package also contain methods to get and * unconditionally set values, as well as a weaker conditional atomic * update operation {@code weakCompareAndSet} described below. * * <p>The specifications of these methods enable implementations to * employ efficient machine-level atomic instructions that are available * on contemporary processors. However on some platforms, support may * entail some form of internal locking. Thus the methods are not * strictly guaranteed to be non-blocking -- * a thread may block transiently before performing the operation. * * <p>Instances of classes * {@link java.util.concurrent.atomic.AtomicBoolean}, * {@link java.util.concurrent.atomic.AtomicInteger}, * {@link java.util.concurrent.atomic.AtomicLong}, and * {@link java.util.concurrent.atomic.AtomicReference} * each provide access and updates to a single variable of the * corresponding type. Each class also provides appropriate utility * methods for that type. For example, classes {@code AtomicLong} and * {@code AtomicInteger} provide atomic increment methods. One * application is to generate sequence numbers, as in: * * <pre> * class Sequencer { * private final AtomicLong sequenceNumber * = new AtomicLong(0); * public long next() { * return sequenceNumber.getAndIncrement(); * } * } * </pre> * * <p>The memory effects for accesses and updates of atomics generally * follow the rules for volatiles, as stated in * <a href="http://java.sun.com/docs/books/jls/"> The Java Language * Specification, Third Edition (17.4 Memory Model)</a>: * * <ul> * * <li> {@code get} has the memory effects of reading a * {@code volatile} variable. * * <li> {@code set} has the memory effects of writing (assigning) a * {@code volatile} variable. * * <li> {@code lazySet} has the memory effects of writing (assigning) * a {@code volatile} variable except that it permits reorderings with * subsequent (but not previous) memory actions that do not themselves * impose reordering constraints with ordinary non-{@code volatile} * writes. Among other usage contexts, {@code lazySet} may apply when * nulling out, for the sake of garbage collection, a reference that is * never accessed again. * * <li>{@code weakCompareAndSet} atomically reads and conditionally * writes a variable but does <em>not</em> * create any happens-before orderings, so provides no guarantees * with respect to previous or subsequent reads and writes of any * variables other than the target of the {@code weakCompareAndSet}. * * <li> {@code compareAndSet} * and all other read-and-update operations such as {@code getAndIncrement} * have the memory effects of both reading and * writing {@code volatile} variables. * </ul> * * <p>In addition to classes representing single values, this package * contains <em>Updater</em> classes that can be used to obtain * {@code compareAndSet} operations on any selected {@code volatile} * field of any selected class. * * {@link java.util.concurrent.atomic.AtomicReferenceFieldUpdater}, * {@link java.util.concurrent.atomic.AtomicIntegerFieldUpdater}, and * {@link java.util.concurrent.atomic.AtomicLongFieldUpdater} are * reflection-based utilities that provide access to the associated * field types. These are mainly of use in atomic data structures in * which several {@code volatile} fields of the same node (for * example, the links of a tree node) are independently subject to * atomic updates. These classes enable greater flexibility in how * and when to use atomic updates, at the expense of more awkward * reflection-based setup, less convenient usage, and weaker * guarantees. * * <p>The * {@link java.util.concurrent.atomic.AtomicIntegerArray}, * {@link java.util.concurrent.atomic.AtomicLongArray}, and * {@link java.util.concurrent.atomic.AtomicReferenceArray} classes * further extend atomic operation support to arrays of these types. * These classes are also notable in providing {@code volatile} access * semantics for their array elements, which is not supported for * ordinary arrays. * * <a name="Spurious"> * <p>The atomic classes also support method {@code weakCompareAndSet}, * which has limited applicability. On some platforms, the weak version * may be more efficient than {@code compareAndSet} in the normal case, * but differs in that any given invocation of the * {@code weakCompareAndSet} method may return {@code false} * <em>spuriously</em> (that is, for no apparent reason)</a>. A * {@code false} return means only that the operation may be retried if * desired, relying on the guarantee that repeated invocation when the * variable holds {@code expectedValue} and no other thread is also * attempting to set the variable will eventually succeed. (Such * spurious failures may for example be due to memory contention effects * that are unrelated to whether the expected and current values are * equal.) Additionally {@code weakCompareAndSet} does not provide * ordering guarantees that are usually needed for synchronization * control. However, the method may be useful for updating counters and * statistics when such updates are unrelated to the other * happens-before orderings of a program. When a thread sees an update * to an atomic variable caused by a {@code weakCompareAndSet}, it does * not necessarily see updates to any <em>other</em> variables that * occurred before the {@code weakCompareAndSet}. This may be * acceptable when, for example, updating performance statistics, but * rarely otherwise. * * <p>The {@link java.util.concurrent.atomic.AtomicMarkableReference} * class associates a single boolean with a reference. For example, this * bit might be used inside a data structure to mean that the object * being referenced has logically been deleted. * * The {@link java.util.concurrent.atomic.AtomicStampedReference} * class associates an integer value with a reference. This may be * used for example, to represent version numbers corresponding to * series of updates. * * <p>Atomic classes are designed primarily as building blocks for * implementing non-blocking data structures and related infrastructure * classes. The {@code compareAndSet} method is not a general * replacement for locking. It applies only when critical updates for an * object are confined to a <em>single</em> variable. * * <p>Atomic classes are not general purpose replacements for * {@code java.lang.Integer} and related classes. They do <em>not</em> * define methods such as {@code hashCode} and * {@code compareTo}. (Because atomic variables are expected to be * mutated, they are poor choices for hash table keys.) Additionally, * classes are provided only for those types that are commonly useful in * intended applications. For example, there is no atomic class for * representing {@code byte}. In those infrequent cases where you would * like to do so, you can use an {@code AtomicInteger} to hold * {@code byte} values, and cast appropriately. * * You can also hold floats using * {@link java.lang.Float#floatToIntBits} and * {@link java.lang.Float#intBitsToFloat} conversions, and doubles using * {@link java.lang.Double#doubleToLongBits} and * {@link java.lang.Double#longBitsToDouble} conversions. * {@description.close} * * @since 1.5 */ package java.util.concurrent.atomic;
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.lang.reflect.*; /** {@collect.stats} * {@description.open} * A reflection-based utility that enables atomic updates to * designated {@code volatile} reference fields of designated * classes. This class is designed for use in atomic data structures * in which several reference fields of the same node are * independently subject to atomic updates. For example, a tree node * might be declared as * * <pre> * class Node { * private volatile Node left, right; * * private static final AtomicReferenceFieldUpdater&lt;Node, Node&gt; leftUpdater = * AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "left"); * private static AtomicReferenceFieldUpdater&lt;Node, Node&gt; rightUpdater = * AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "right"); * * Node getLeft() { return left; } * boolean compareAndSetLeft(Node expect, Node update) { * return leftUpdater.compareAndSet(this, expect, update); * } * // ... and so on * } * </pre> * * <p>Note that the guarantees of the {@code compareAndSet} * method in this class are weaker than in other atomic classes. * Because this class cannot ensure that all uses of the field * are appropriate for purposes of atomic access, it can * guarantee atomicity only with respect to other invocations of * {@code compareAndSet} and {@code set} on the same updater. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <T> The type of the object holding the updatable field * @param <V> The type of the field */ public abstract class AtomicReferenceFieldUpdater<T, V> { /** {@collect.stats} * {@description.open} * Creates and returns an updater for objects with the given field. * The Class arguments are needed to check that reflective types and * generic types match. * {@description.close} * * @param tclass the class of the objects holding the field. * @param vclass the class of the field * @param fieldName the name of the field to be updated. * @return the updater * @throws IllegalArgumentException if the field is not a volatile reference type. * @throws RuntimeException with a nested reflection-based * exception if the class does not hold field or is the wrong type. */ public static <U, W> AtomicReferenceFieldUpdater<U,W> newUpdater(Class<U> tclass, Class<W> vclass, String fieldName) { return new AtomicReferenceFieldUpdaterImpl<U,W>(tclass, vclass, fieldName); } /** {@collect.stats} * {@description.open} * Protected do-nothing constructor for use by subclasses. * {@description.close} */ protected AtomicReferenceFieldUpdater() { } /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful. */ public abstract boolean compareAndSet(T obj, V expect, V update); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful. */ public abstract boolean weakCompareAndSet(T obj, V expect, V update); /** {@collect.stats} * {@description.open} * Sets the field of the given object managed by this updater to the * given updated value. This operation is guaranteed to act as a volatile * store with respect to subsequent invocations of {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value */ public abstract void set(T obj, V newValue); /** {@collect.stats} * {@description.open} * Eventually sets the field of the given object managed by this * updater to the given updated value. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value * @since 1.6 */ public abstract void lazySet(T obj, V newValue); /** {@collect.stats} * {@description.open} * Gets the current value held in the field of the given object managed * by this updater. * {@description.close} * * @param obj An object whose field to get * @return the current value */ public abstract V get(T obj); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given value and returns the old value. * {@description.close} * * @param obj An object whose field to get and set * @param newValue the new value * @return the previous value */ public V getAndSet(T obj, V newValue) { for (;;) { V current = get(obj); if (compareAndSet(obj, current, newValue)) return current; } } private static final class AtomicReferenceFieldUpdaterImpl<T,V> extends AtomicReferenceFieldUpdater<T,V> { private static final Unsafe unsafe = Unsafe.getUnsafe(); private final long offset; private final Class<T> tclass; private final Class<V> vclass; private final Class cclass; /* * Internal type checks within all update methods contain * internal inlined optimizations checking for the common * cases where the class is final (in which case a simple * getClass comparison suffices) or is of type Object (in * which case no check is needed because all objects are * instances of Object). The Object case is handled simply by * setting vclass to null in constructor. The targetCheck and * updateCheck methods are invoked when these faster * screenings fail. */ AtomicReferenceFieldUpdaterImpl(Class<T> tclass, Class<V> vclass, String fieldName) { Field field = null; Class fieldClass = null; Class caller = null; int modifiers = 0; try { field = tclass.getDeclaredField(fieldName); caller = sun.reflect.Reflection.getCallerClass(3); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); fieldClass = field.getType(); } catch (Exception ex) { throw new RuntimeException(ex); } if (vclass != fieldClass) throw new ClassCastException(); if (!Modifier.isVolatile(modifiers)) throw new IllegalArgumentException("Must be volatile type"); this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null; this.tclass = tclass; if (vclass == Object.class) this.vclass = null; else this.vclass = vclass; offset = unsafe.objectFieldOffset(field); } void targetCheck(T obj) { if (!tclass.isInstance(obj)) throw new ClassCastException(); if (cclass != null) ensureProtectedAccess(obj); } void updateCheck(T obj, V update) { if (!tclass.isInstance(obj) || (update != null && vclass != null && !vclass.isInstance(update))) throw new ClassCastException(); if (cclass != null) ensureProtectedAccess(obj); } public boolean compareAndSet(T obj, V expect, V update) { if (obj == null || obj.getClass() != tclass || cclass != null || (update != null && vclass != null && vclass != update.getClass())) updateCheck(obj, update); return unsafe.compareAndSwapObject(obj, offset, expect, update); } public boolean weakCompareAndSet(T obj, V expect, V update) { // same implementation as strong form for now if (obj == null || obj.getClass() != tclass || cclass != null || (update != null && vclass != null && vclass != update.getClass())) updateCheck(obj, update); return unsafe.compareAndSwapObject(obj, offset, expect, update); } public void set(T obj, V newValue) { if (obj == null || obj.getClass() != tclass || cclass != null || (newValue != null && vclass != null && vclass != newValue.getClass())) updateCheck(obj, newValue); unsafe.putObjectVolatile(obj, offset, newValue); } public void lazySet(T obj, V newValue) { if (obj == null || obj.getClass() != tclass || cclass != null || (newValue != null && vclass != null && vclass != newValue.getClass())) updateCheck(obj, newValue); unsafe.putOrderedObject(obj, offset, newValue); } public V get(T obj) { if (obj == null || obj.getClass() != tclass || cclass != null) targetCheck(obj); return (V)unsafe.getObjectVolatile(obj, offset); } private void ensureProtectedAccess(T obj) { if (cclass.isInstance(obj)) { return; } throw new RuntimeException ( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + tclass.getName() + " using an instance of " + obj.getClass().getName() ) ); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * A {@code boolean} value that may be updated atomically. See the * {@link java.util.concurrent.atomic} package specification for * description of the properties of atomic variables. An * {@code AtomicBoolean} is used in applications such as atomically * updated flags, and cannot be used as a replacement for a * {@link java.lang.Boolean}. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class AtomicBoolean implements java.io.Serializable { private static final long serialVersionUID = 4654671469794556979L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicBoolean.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value; /** {@collect.stats} * {@description.open} * Creates a new {@code AtomicBoolean} with the given initial value. * {@description.close} * * @param initialValue the initial value */ public AtomicBoolean(boolean initialValue) { value = initialValue ? 1 : 0; } /** {@collect.stats} * {@description.open} * Creates a new {@code AtomicBoolean} with initial value {@code false}. * {@description.close} */ public AtomicBoolean() { } /** {@collect.stats} * {@description.open} * Returns the current value. * {@description.close} * * @return the current value */ public final boolean get() { return value != 0; } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; int u = update ? 1 : 0; return unsafe.compareAndSwapInt(this, valueOffset, e, u); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. */ public boolean weakCompareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; int u = update ? 1 : 0; return unsafe.compareAndSwapInt(this, valueOffset, e, u); } /** {@collect.stats} * {@description.open} * Unconditionally sets to the given value. * {@description.close} * * @param newValue the new value */ public final void set(boolean newValue) { value = newValue ? 1 : 0; } /** {@collect.stats} * {@description.open} * Eventually sets to the given value. * {@description.close} * * @param newValue the new value * @since 1.6 */ public final void lazySet(boolean newValue) { int v = newValue ? 1 : 0; unsafe.putOrderedInt(this, valueOffset, v); } /** {@collect.stats} * {@description.open} * Atomically sets to the given value and returns the previous value. * {@description.close} * * @param newValue the new value * @return the previous value */ public final boolean getAndSet(boolean newValue) { for (;;) { boolean current = get(); if (compareAndSet(current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current value. * {@description.close} * @return the String representation of the current value. */ public String toString() { return Boolean.toString(get()); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; /** {@collect.stats} * {@description.open} * An {@code AtomicStampedReference} maintains an object reference * along with an integer "stamp", that can be updated atomically. * * <p> Implementation note. This implementation maintains stamped * references by creating internal objects representing "boxed" * [reference, integer] pairs. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <V> The type of object referred to by this reference */ public class AtomicStampedReference<V> { private static class ReferenceIntegerPair<T> { private final T reference; private final int integer; ReferenceIntegerPair(T r, int i) { reference = r; integer = i; } } private final AtomicReference<ReferenceIntegerPair<V>> atomicRef; /** {@collect.stats} * {@description.open} * Creates a new {@code AtomicStampedReference} with the given * initial values. * {@description.close} * * @param initialRef the initial reference * @param initialStamp the initial stamp */ public AtomicStampedReference(V initialRef, int initialStamp) { atomicRef = new AtomicReference<ReferenceIntegerPair<V>> (new ReferenceIntegerPair<V>(initialRef, initialStamp)); } /** {@collect.stats} * {@description.open} * Returns the current value of the reference. * {@description.close} * * @return the current value of the reference */ public V getReference() { return atomicRef.get().reference; } /** {@collect.stats} * {@description.open} * Returns the current value of the stamp. * {@description.close} * * @return the current value of the stamp */ public int getStamp() { return atomicRef.get().integer; } /** {@collect.stats} * {@description.open} * Returns the current values of both the reference and the stamp. * Typical usage is {@code int[1] holder; ref = v.get(holder); }. * {@description.close} * * @param stampHolder an array of size of at least one. On return, * {@code stampholder[0]} will hold the value of the stamp. * @return the current value of the reference */ public V get(int[] stampHolder) { ReferenceIntegerPair<V> p = atomicRef.get(); stampHolder[0] = p.integer; return p.reference; } /** {@collect.stats} * {@description.open} * Atomically sets the value of both the reference and stamp * to the given update values if the * current reference is {@code ==} to the expected reference * and the current stamp is equal to the expected stamp. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedStamp the expected value of the stamp * @param newStamp the new value for the stamp * @return true if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp) { ReferenceIntegerPair<V> current = atomicRef.get(); return expectedReference == current.reference && expectedStamp == current.integer && ((newReference == current.reference && newStamp == current.integer) || atomicRef.weakCompareAndSet(current, new ReferenceIntegerPair<V>(newReference, newStamp))); } /** {@collect.stats} * {@description.open} * Atomically sets the value of both the reference and stamp * to the given update values if the * current reference is {@code ==} to the expected reference * and the current stamp is equal to the expected stamp. * {@description.close} * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedStamp the expected value of the stamp * @param newStamp the new value for the stamp * @return true if successful */ public boolean compareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp) { ReferenceIntegerPair<V> current = atomicRef.get(); return expectedReference == current.reference && expectedStamp == current.integer && ((newReference == current.reference && newStamp == current.integer) || atomicRef.compareAndSet(current, new ReferenceIntegerPair<V>(newReference, newStamp))); } /** {@collect.stats} * {@description.open} * Unconditionally sets the value of both the reference and stamp. * {@description.close} * * @param newReference the new value for the reference * @param newStamp the new value for the stamp */ public void set(V newReference, int newStamp) { ReferenceIntegerPair<V> current = atomicRef.get(); if (newReference != current.reference || newStamp != current.integer) atomicRef.set(new ReferenceIntegerPair<V>(newReference, newStamp)); } /** {@collect.stats} * {@description.open} * Atomically sets the value of the stamp to the given update value * if the current reference is {@code ==} to the expected * reference. Any given invocation of this operation may fail * (return {@code false}) spuriously, but repeated invocation * when the current value holds the expected value and no other * thread is also attempting to set the value will eventually * succeed. * {@description.close} * * @param expectedReference the expected value of the reference * @param newStamp the new value for the stamp * @return true if successful */ public boolean attemptStamp(V expectedReference, int newStamp) { ReferenceIntegerPair<V> current = atomicRef.get(); return expectedReference == current.reference && (newStamp == current.integer || atomicRef.compareAndSet(current, new ReferenceIntegerPair<V>(expectedReference, newStamp))); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.util.*; /** {@collect.stats} * {@description.open} * A {@code long} array in which elements may be updated atomically. * See the {@link java.util.concurrent.atomic} package specification * for description of the properties of atomic variables. * {@description.close} * @since 1.5 * @author Doug Lea */ public class AtomicLongArray implements java.io.Serializable { private static final long serialVersionUID = -2308431214976778248L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final int base = unsafe.arrayBaseOffset(long[].class); private static final int scale = unsafe.arrayIndexScale(long[].class); private final long[] array; private long rawIndex(int i) { if (i < 0 || i >= array.length) throw new IndexOutOfBoundsException("index " + i); return base + (long) i * scale; } /** {@collect.stats} * {@description.open} * Creates a new AtomicLongArray of given length. * {@description.close} * * @param length the length of the array */ public AtomicLongArray(int length) { array = new long[length]; // must perform at least one volatile write to conform to JMM if (length > 0) unsafe.putLongVolatile(array, rawIndex(0), 0); } /** {@collect.stats} * {@description.open} * Creates a new AtomicLongArray with the same length as, and * all elements copied from, the given array. * {@description.close} * * @param array the array to copy elements from * @throws NullPointerException if array is null */ public AtomicLongArray(long[] array) { if (array == null) throw new NullPointerException(); int length = array.length; this.array = new long[length]; if (length > 0) { int last = length-1; for (int i = 0; i < last; ++i) this.array[i] = array[i]; // Do the last write as volatile unsafe.putLongVolatile(this.array, rawIndex(last), array[last]); } } /** {@collect.stats} * {@description.open} * Returns the length of the array. * {@description.close} * * @return the length of the array */ public final int length() { return array.length; } /** {@collect.stats} * {@description.open} * Gets the current value at position {@code i}. * {@description.close} * * @param i the index * @return the current value */ public final long get(int i) { return unsafe.getLongVolatile(array, rawIndex(i)); } /** {@collect.stats} * {@description.open} * Sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value */ public final void set(int i, long newValue) { unsafe.putLongVolatile(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Eventually sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value * @since 1.6 */ public final void lazySet(int i, long newValue) { unsafe.putOrderedLong(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given value * and returns the old value. * {@description.close} * * @param i the index * @param newValue the new value * @return the previous value */ public final long getAndSet(int i, long newValue) { while (true) { long current = get(i); if (compareAndSet(i, current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * {@description.close} * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, long expect, long update) { return unsafe.compareAndSwapLong(array, rawIndex(i), expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(int i, long expect, long update) { return compareAndSet(i, expect, update); } /** {@collect.stats} * {@description.open} * Atomically increments by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the previous value */ public final long getAndIncrement(int i) { while (true) { long current = get(i); long next = current + 1; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the previous value */ public final long getAndDecrement(int i) { while (true) { long current = get(i); long next = current - 1; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the element at index {@code i}. * {@description.close} * * @param i the index * @param delta the value to add * @return the previous value */ public final long getAndAdd(int i, long delta) { while (true) { long current = get(i); long next = current + delta; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the updated value */ public final long incrementAndGet(int i) { while (true) { long current = get(i); long next = current + 1; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the updated value */ public final long decrementAndGet(int i) { while (true) { long current = get(i); long next = current - 1; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the element at index {@code i}. * {@description.close} * * @param i the index * @param delta the value to add * @return the updated value */ public long addAndGet(int i, long delta) { while (true) { long current = get(i); long next = current + delta; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current values of array. * {@description.close} * @return the String representation of the current values of array. */ public String toString() { if (array.length > 0) // force volatile read get(0); return Arrays.toString(array); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.util.*; /** {@collect.stats} * {@description.open} * An array of object references in which elements may be updated * atomically. See the {@link java.util.concurrent.atomic} package * specification for description of the properties of atomic * variables. * {@description.close} * @since 1.5 * @author Doug Lea * @param <E> The base class of elements held in this array */ public class AtomicReferenceArray<E> implements java.io.Serializable { private static final long serialVersionUID = -6209656149925076980L; private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final int base = unsafe.arrayBaseOffset(Object[].class); private static final int scale = unsafe.arrayIndexScale(Object[].class); private final Object[] array; private long rawIndex(int i) { if (i < 0 || i >= array.length) throw new IndexOutOfBoundsException("index " + i); return base + (long) i * scale; } /** {@collect.stats} * {@description.open} * Creates a new AtomicReferenceArray of given length. * {@description.close} * @param length the length of the array */ public AtomicReferenceArray(int length) { array = new Object[length]; // must perform at least one volatile write to conform to JMM if (length > 0) unsafe.putObjectVolatile(array, rawIndex(0), null); } /** {@collect.stats} * {@description.open} * Creates a new AtomicReferenceArray with the same length as, and * all elements copied from, the given array. * {@description.close} * * @param array the array to copy elements from * @throws NullPointerException if array is null */ public AtomicReferenceArray(E[] array) { if (array == null) throw new NullPointerException(); int length = array.length; this.array = new Object[length]; if (length > 0) { int last = length-1; for (int i = 0; i < last; ++i) this.array[i] = array[i]; // Do the last write as volatile E e = array[last]; unsafe.putObjectVolatile(this.array, rawIndex(last), e); } } /** {@collect.stats} * {@description.open} * Returns the length of the array. * {@description.close} * * @return the length of the array */ public final int length() { return array.length; } /** {@collect.stats} * {@description.open} * Gets the current value at position {@code i}. * {@description.close} * * @param i the index * @return the current value */ public final E get(int i) { return (E) unsafe.getObjectVolatile(array, rawIndex(i)); } /** {@collect.stats} * {@description.open} * Sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value */ public final void set(int i, E newValue) { unsafe.putObjectVolatile(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Eventually sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value * @since 1.6 */ public final void lazySet(int i, E newValue) { unsafe.putOrderedObject(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * value and returns the old value. * {@description.close} * * @param i the index * @param newValue the new value * @return the previous value */ public final E getAndSet(int i, E newValue) { while (true) { E current = get(i); if (compareAndSet(i, current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * {@description.close} * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, E expect, E update) { return unsafe.compareAndSwapObject(array, rawIndex(i), expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(int i, E expect, E update) { return compareAndSet(i, expect, update); } /** {@collect.stats} * {@description.open} * Returns the String representation of the current values of array. * {@description.close} * @return the String representation of the current values of array. */ public String toString() { if (array.length > 0) // force volatile read get(0); return Arrays.toString(array); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; /** {@collect.stats} * {@description.open} * An {@code AtomicMarkableReference} maintains an object reference * along with a mark bit, that can be updated atomically. * <p> * <p> Implementation note. This implementation maintains markable * references by creating internal objects representing "boxed" * [reference, boolean] pairs. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <V> The type of object referred to by this reference */ public class AtomicMarkableReference<V> { private static class ReferenceBooleanPair<T> { private final T reference; private final boolean bit; ReferenceBooleanPair(T r, boolean i) { reference = r; bit = i; } } private final AtomicReference<ReferenceBooleanPair<V>> atomicRef; /** {@collect.stats} * {@description.open} * Creates a new {@code AtomicMarkableReference} with the given * initial values. * {@description.close} * * @param initialRef the initial reference * @param initialMark the initial mark */ public AtomicMarkableReference(V initialRef, boolean initialMark) { atomicRef = new AtomicReference<ReferenceBooleanPair<V>> (new ReferenceBooleanPair<V>(initialRef, initialMark)); } /** {@collect.stats} * {@description.open} * Returns the current value of the reference. * {@description.close} * * @return the current value of the reference */ public V getReference() { return atomicRef.get().reference; } /** {@collect.stats} * {@description.open} * Returns the current value of the mark. * {@description.close} * * @return the current value of the mark */ public boolean isMarked() { return atomicRef.get().bit; } /** {@collect.stats} * {@description.open} * Returns the current values of both the reference and the mark. * Typical usage is {@code boolean[1] holder; ref = v.get(holder); }. * {@description.close} * * @param markHolder an array of size of at least one. On return, * {@code markholder[0]} will hold the value of the mark. * @return the current value of the reference */ public V get(boolean[] markHolder) { ReferenceBooleanPair<V> p = atomicRef.get(); markHolder[0] = p.bit; return p.reference; } /** {@collect.stats} * {@description.open} * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return true if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { ReferenceBooleanPair<V> current = atomicRef.get(); return expectedReference == current.reference && expectedMark == current.bit && ((newReference == current.reference && newMark == current.bit) || atomicRef.weakCompareAndSet(current, new ReferenceBooleanPair<V>(newReference, newMark))); } /** {@collect.stats} * {@description.open} * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * {@description.close} * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return true if successful */ public boolean compareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { ReferenceBooleanPair<V> current = atomicRef.get(); return expectedReference == current.reference && expectedMark == current.bit && ((newReference == current.reference && newMark == current.bit) || atomicRef.compareAndSet(current, new ReferenceBooleanPair<V>(newReference, newMark))); } /** {@collect.stats} * {@description.open} * Unconditionally sets the value of both the reference and mark. * {@description.close} * * @param newReference the new value for the reference * @param newMark the new value for the mark */ public void set(V newReference, boolean newMark) { ReferenceBooleanPair<V> current = atomicRef.get(); if (newReference != current.reference || newMark != current.bit) atomicRef.set(new ReferenceBooleanPair<V>(newReference, newMark)); } /** {@collect.stats} * {@description.open} * Atomically sets the value of the mark to the given update value * if the current reference is {@code ==} to the expected * reference. Any given invocation of this operation may fail * (return {@code false}) spuriously, but repeated invocation * when the current value holds the expected value and no other * thread is also attempting to set the value will eventually * succeed. * {@description.close} * * @param expectedReference the expected value of the reference * @param newMark the new value for the mark * @return true if successful */ public boolean attemptMark(V expectedReference, boolean newMark) { ReferenceBooleanPair<V> current = atomicRef.get(); return expectedReference == current.reference && (newMark == current.bit || atomicRef.compareAndSet (current, new ReferenceBooleanPair<V>(expectedReference, newMark))); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * An {@code int} value that may be updated atomically. See the * {@link java.util.concurrent.atomic} package specification for * description of the properties of atomic variables. An * {@code AtomicInteger} is used in applications such as atomically * incremented counters, and cannot be used as a replacement for an * {@link java.lang.Integer}. However, this class does extend * {@code Number} to allow uniform access by tools and utilities that * deal with numerically-based classes. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class AtomicInteger extends Number implements java.io.Serializable { private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value; /** {@collect.stats} * {@description.open} * Creates a new AtomicInteger with the given initial value. * {@description.close} * * @param initialValue the initial value */ public AtomicInteger(int initialValue) { value = initialValue; } /** {@collect.stats} * {@description.open} * Creates a new AtomicInteger with initial value {@code 0}. * {@description.close} */ public AtomicInteger() { } /** {@collect.stats} * {@description.open} * Gets the current value. * {@description.close} * * @return the current value */ public final int get() { return value; } /** {@collect.stats} * {@description.open} * Sets to the given value. * {@description.close} * * @param newValue the new value */ public final void set(int newValue) { value = newValue; } /** {@collect.stats} * {@description.open} * Eventually sets to the given value. * {@description.close} * * @param newValue the new value * @since 1.6 */ public final void lazySet(int newValue) { unsafe.putOrderedInt(this, valueOffset, newValue); } /** {@collect.stats} * {@description.open} * Atomically sets to the given value and returns the old value. * {@description.close} * * @param newValue the new value * @return the previous value */ public final int getAndSet(int newValue) { for (;;) { int current = get(); if (compareAndSet(current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value. * {@description.close} * * @return the previous value */ public final int getAndIncrement() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value. * {@description.close} * * @return the previous value */ public final int getAndDecrement() { for (;;) { int current = get(); int next = current - 1; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value. * {@description.close} * * @param delta the value to add * @return the previous value */ public final int getAndAdd(int delta) { for (;;) { int current = get(); int next = current + delta; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value. * {@description.close} * * @return the updated value */ public final int incrementAndGet() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value. * {@description.close} * * @return the updated value */ public final int decrementAndGet() { for (;;) { int current = get(); int next = current - 1; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value. * {@description.close} * * @param delta the value to add * @return the updated value */ public final int addAndGet(int delta) { for (;;) { int current = get(); int next = current + delta; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current value. * {@description.close} * @return the String representation of the current value. */ public String toString() { return Integer.toString(get()); } public int intValue() { return get(); } public long longValue() { return (long)get(); } public float floatValue() { return (float)get(); } public double doubleValue() { return (double)get(); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.lang.reflect.*; /** {@collect.stats} * {@description.open} * A reflection-based utility that enables atomic updates to * designated {@code volatile long} fields of designated classes. * This class is designed for use in atomic data structures in which * several fields of the same node are independently subject to atomic * updates. * * <p>Note that the guarantees of the {@code compareAndSet} * method in this class are weaker than in other atomic classes. * Because this class cannot ensure that all uses of the field * are appropriate for purposes of atomic access, it can * guarantee atomicity only with respect to other invocations of * {@code compareAndSet} and {@code set} on the same updater. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <T> The type of the object holding the updatable field */ public abstract class AtomicLongFieldUpdater<T> { /** {@collect.stats} * {@description.open} * Creates and returns an updater for objects with the given field. * The Class argument is needed to check that reflective types and * generic types match. * {@description.close} * * @param tclass the class of the objects holding the field * @param fieldName the name of the field to be updated. * @return the updater * @throws IllegalArgumentException if the field is not a * volatile long type. * @throws RuntimeException with a nested reflection-based * exception if the class does not hold field or is the wrong type. */ public static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName) { if (AtomicLong.VM_SUPPORTS_LONG_CAS) return new CASUpdater<U>(tclass, fieldName); else return new LockedUpdater<U>(tclass, fieldName); } /** {@collect.stats} * {@description.open} * Protected do-nothing constructor for use by subclasses. * {@description.close} */ protected AtomicLongFieldUpdater() { } /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful. * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor. */ public abstract boolean compareAndSet(T obj, long expect, long update); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given updated value if the current value {@code ==} the * expected value. This method is guaranteed to be atomic with respect to * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value * @return true if successful. * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor. */ public abstract boolean weakCompareAndSet(T obj, long expect, long update); /** {@collect.stats} * {@description.open} * Sets the field of the given object managed by this updater to the * given updated value. This operation is guaranteed to act as a volatile * store with respect to subsequent invocations of {@code compareAndSet}. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value */ public abstract void set(T obj, long newValue); /** {@collect.stats} * {@description.open} * Eventually sets the field of the given object managed by this * updater to the given updated value. * {@description.close} * * @param obj An object whose field to set * @param newValue the new value * @since 1.6 */ public abstract void lazySet(T obj, long newValue); /** {@collect.stats} * {@description.open} * Gets the current value held in the field of the given object managed * by this updater. * {@description.close} * * @param obj An object whose field to get * @return the current value */ public abstract long get(T obj); /** {@collect.stats} * {@description.open} * Atomically sets the field of the given object managed by this updater * to the given value and returns the old value. * {@description.close} * * @param obj An object whose field to get and set * @param newValue the new value * @return the previous value */ public long getAndSet(T obj, long newValue) { for (;;) { long current = get(obj); if (compareAndSet(obj, current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the previous value */ public long getAndIncrement(T obj) { for (;;) { long current = get(obj); long next = current + 1; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the previous value */ public long getAndDecrement(T obj) { for (;;) { long current = get(obj); long next = current - 1; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value of the field of * the given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @param delta the value to add * @return the previous value */ public long getAndAdd(T obj, long delta) { for (;;) { long current = get(obj); long next = current + delta; if (compareAndSet(obj, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the updated value */ public long incrementAndGet(T obj) { for (;;) { long current = get(obj); long next = current + 1; if (compareAndSet(obj, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value of the field of the * given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @return the updated value */ public long decrementAndGet(T obj) { for (;;) { long current = get(obj); long next = current - 1; if (compareAndSet(obj, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value of the field of * the given object managed by this updater. * {@description.close} * * @param obj An object whose field to get and set * @param delta the value to add * @return the updated value */ public long addAndGet(T obj, long delta) { for (;;) { long current = get(obj); long next = current + delta; if (compareAndSet(obj, current, next)) return next; } } private static class CASUpdater<T> extends AtomicLongFieldUpdater<T> { private static final Unsafe unsafe = Unsafe.getUnsafe(); private final long offset; private final Class<T> tclass; private final Class cclass; CASUpdater(Class<T> tclass, String fieldName) { Field field = null; Class caller = null; int modifiers = 0; try { field = tclass.getDeclaredField(fieldName); caller = sun.reflect.Reflection.getCallerClass(3); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); } catch(Exception ex) { throw new RuntimeException(ex); } Class fieldt = field.getType(); if (fieldt != long.class) throw new IllegalArgumentException("Must be long type"); if (!Modifier.isVolatile(modifiers)) throw new IllegalArgumentException("Must be volatile type"); this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null; this.tclass = tclass; offset = unsafe.objectFieldOffset(field); } private void fullCheck(T obj) { if (!tclass.isInstance(obj)) throw new ClassCastException(); if (cclass != null) ensureProtectedAccess(obj); } public boolean compareAndSet(T obj, long expect, long update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.compareAndSwapLong(obj, offset, expect, update); } public boolean weakCompareAndSet(T obj, long expect, long update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.compareAndSwapLong(obj, offset, expect, update); } public void set(T obj, long newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); unsafe.putLongVolatile(obj, offset, newValue); } public void lazySet(T obj, long newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); unsafe.putOrderedLong(obj, offset, newValue); } public long get(T obj) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); return unsafe.getLongVolatile(obj, offset); } private void ensureProtectedAccess(T obj) { if (cclass.isInstance(obj)) { return; } throw new RuntimeException ( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + tclass.getName() + " using an instance of " + obj.getClass().getName() ) ); } } private static class LockedUpdater<T> extends AtomicLongFieldUpdater<T> { private static final Unsafe unsafe = Unsafe.getUnsafe(); private final long offset; private final Class<T> tclass; private final Class cclass; LockedUpdater(Class<T> tclass, String fieldName) { Field field = null; Class caller = null; int modifiers = 0; try { field = tclass.getDeclaredField(fieldName); caller = sun.reflect.Reflection.getCallerClass(3); modifiers = field.getModifiers(); sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); } catch(Exception ex) { throw new RuntimeException(ex); } Class fieldt = field.getType(); if (fieldt != long.class) throw new IllegalArgumentException("Must be long type"); if (!Modifier.isVolatile(modifiers)) throw new IllegalArgumentException("Must be volatile type"); this.cclass = (Modifier.isProtected(modifiers) && caller != tclass) ? caller : null; this.tclass = tclass; offset = unsafe.objectFieldOffset(field); } private void fullCheck(T obj) { if (!tclass.isInstance(obj)) throw new ClassCastException(); if (cclass != null) ensureProtectedAccess(obj); } public boolean compareAndSet(T obj, long expect, long update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); synchronized(this) { long v = unsafe.getLong(obj, offset); if (v != expect) return false; unsafe.putLong(obj, offset, update); return true; } } public boolean weakCompareAndSet(T obj, long expect, long update) { return compareAndSet(obj, expect, update); } public void set(T obj, long newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); synchronized(this) { unsafe.putLong(obj, offset, newValue); } } public void lazySet(T obj, long newValue) { set(obj, newValue); } public long get(T obj) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); synchronized(this) { return unsafe.getLong(obj, offset); } } private void ensureProtectedAccess(T obj) { if (cclass.isInstance(obj)) { return; } throw new RuntimeException ( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + tclass.getName() + " using an instance of " + obj.getClass().getName() ) ); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * An object reference that may be updated atomically. See the {@link * java.util.concurrent.atomic} package specification for description * of the properties of atomic variables. * {@description.close} * @since 1.5 * @author Doug Lea * @param <V> The type of object referred to by this reference */ public class AtomicReference<V> implements java.io.Serializable { private static final long serialVersionUID = -1848883965231344442L; private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicReference.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile V value; /** {@collect.stats} * {@description.open} * Creates a new AtomicReference with the given initial value. * {@description.close} * * @param initialValue the initial value */ public AtomicReference(V initialValue) { value = initialValue; } /** {@collect.stats} * {@description.open} * Creates a new AtomicReference with null initial value. * {@description.close} */ public AtomicReference() { } /** {@collect.stats} * {@description.open} * Gets the current value. * {@description.close} * * @return the current value */ public final V get() { return value; } /** {@collect.stats} * {@description.open} * Sets to the given value. * {@description.close} * * @param newValue the new value */ public final void set(V newValue) { value = newValue; } /** {@collect.stats} * {@description.open} * Eventually sets to the given value. * {@description.close} * * @param newValue the new value * @since 1.6 */ public final void lazySet(V newValue) { unsafe.putOrderedObject(this, valueOffset, newValue); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * {@description.close} * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(V expect, V update) { return unsafe.compareAndSwapObject(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(V expect, V update) { return unsafe.compareAndSwapObject(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets to the given value and returns the old value. * {@description.close} * * @param newValue the new value * @return the previous value */ public final V getAndSet(V newValue) { while (true) { V x = get(); if (compareAndSet(x, newValue)) return x; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current value. * {@description.close} * @return the String representation of the current value. */ public String toString() { return String.valueOf(get()); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; import java.util.*; /** {@collect.stats} * {@description.open} * An {@code int} array in which elements may be updated atomically. * See the {@link java.util.concurrent.atomic} package * specification for description of the properties of atomic * variables. * {@description.close} * @since 1.5 * @author Doug Lea */ public class AtomicIntegerArray implements java.io.Serializable { private static final long serialVersionUID = 2862133569453604235L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final int base = unsafe.arrayBaseOffset(int[].class); private static final int scale = unsafe.arrayIndexScale(int[].class); private final int[] array; private long rawIndex(int i) { if (i < 0 || i >= array.length) throw new IndexOutOfBoundsException("index " + i); return base + (long) i * scale; } /** {@collect.stats} * {@description.open} * Creates a new AtomicIntegerArray of given length. * {@description.close} * * @param length the length of the array */ public AtomicIntegerArray(int length) { array = new int[length]; // must perform at least one volatile write to conform to JMM if (length > 0) unsafe.putIntVolatile(array, rawIndex(0), 0); } /** {@collect.stats} * {@description.open} * Creates a new AtomicIntegerArray with the same length as, and * all elements copied from, the given array. * {@description.close} * * @param array the array to copy elements from * @throws NullPointerException if array is null */ public AtomicIntegerArray(int[] array) { if (array == null) throw new NullPointerException(); int length = array.length; this.array = new int[length]; if (length > 0) { int last = length-1; for (int i = 0; i < last; ++i) this.array[i] = array[i]; // Do the last write as volatile unsafe.putIntVolatile(this.array, rawIndex(last), array[last]); } } /** {@collect.stats} * {@description.open} * Returns the length of the array. * {@description.close} * * @return the length of the array */ public final int length() { return array.length; } /** {@collect.stats} * {@description.open} * Gets the current value at position {@code i}. * {@description.close} * * @param i the index * @return the current value */ public final int get(int i) { return unsafe.getIntVolatile(array, rawIndex(i)); } /** {@collect.stats} * {@description.open} * Sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value */ public final void set(int i, int newValue) { unsafe.putIntVolatile(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Eventually sets the element at position {@code i} to the given value. * {@description.close} * * @param i the index * @param newValue the new value * @since 1.6 */ public final void lazySet(int i, int newValue) { unsafe.putOrderedInt(array, rawIndex(i), newValue); } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * value and returns the old value. * {@description.close} * * @param i the index * @param newValue the new value * @return the previous value */ public final int getAndSet(int i, int newValue) { while (true) { int current = get(i); if (compareAndSet(i, current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * {@description.close} * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, int expect, int update) { return unsafe.compareAndSwapInt(array, rawIndex(i), expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(int i, int expect, int update) { return compareAndSet(i, expect, update); } /** {@collect.stats} * {@description.open} * Atomically increments by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the previous value */ public final int getAndIncrement(int i) { while (true) { int current = get(i); int next = current + 1; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the previous value */ public final int getAndDecrement(int i) { while (true) { int current = get(i); int next = current - 1; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the element at index {@code i}. * {@description.close} * * @param i the index * @param delta the value to add * @return the previous value */ public final int getAndAdd(int i, int delta) { while (true) { int current = get(i); int next = current + delta; if (compareAndSet(i, current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the updated value */ public final int incrementAndGet(int i) { while (true) { int current = get(i); int next = current + 1; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the element at index {@code i}. * {@description.close} * * @param i the index * @return the updated value */ public final int decrementAndGet(int i) { while (true) { int current = get(i); int next = current - 1; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the element at index {@code i}. * {@description.close} * * @param i the index * @param delta the value to add * @return the updated value */ public final int addAndGet(int i, int delta) { while (true) { int current = get(i); int next = current + delta; if (compareAndSet(i, current, next)) return next; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current values of array. * {@description.close} * @return the String representation of the current values of array. */ public String toString() { if (array.length > 0) // force volatile read get(0); return Arrays.toString(array); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent.atomic; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * A {@code long} value that may be updated atomically. See the * {@link java.util.concurrent.atomic} package specification for * description of the properties of atomic variables. An * {@code AtomicLong} is used in applications such as atomically * incremented sequence numbers, and cannot be used as a replacement * for a {@link java.lang.Long}. However, this class does extend * {@code Number} to allow uniform access by tools and utilities that * deal with numerically-based classes. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class AtomicLong extends Number implements java.io.Serializable { private static final long serialVersionUID = 1927816293512124184L; // setup to use Unsafe.compareAndSwapLong for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; /** {@collect.stats} * {@description.open} * Records whether the underlying JVM supports lockless * compareAndSwap for longs. While the Unsafe.compareAndSwapLong * method works in either case, some constructions should be * handled at Java level to avoid locking user-visible locks. * {@description.close} */ static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8(); /** {@collect.stats} * {@description.open} * Returns whether underlying JVM supports lockless CompareAndSet * for longs. Called only once and cached in VM_SUPPORTS_LONG_CAS. * {@description.close} */ private static native boolean VMSupportsCS8(); static { try { valueOffset = unsafe.objectFieldOffset (AtomicLong.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile long value; /** {@collect.stats} * {@description.open} * Creates a new AtomicLong with the given initial value. * {@description.close} * * @param initialValue the initial value */ public AtomicLong(long initialValue) { value = initialValue; } /** {@collect.stats} * {@description.open} * Creates a new AtomicLong with initial value {@code 0}. * {@description.close} */ public AtomicLong() { } /** {@collect.stats} * {@description.open} * Gets the current value. * {@description.close} * * @return the current value */ public final long get() { return value; } /** {@collect.stats} * {@description.open} * Sets to the given value. * {@description.close} * * @param newValue the new value */ public final void set(long newValue) { value = newValue; } /** {@collect.stats} * {@description.open} * Eventually sets to the given value. * {@description.close} * * @param newValue the new value * @since 1.6 */ public final void lazySet(long newValue) { unsafe.putOrderedLong(this, valueOffset, newValue); } /** {@collect.stats} * {@description.open} * Atomically sets to the given value and returns the old value. * {@description.close} * * @param newValue the new value * @return the previous value */ public final long getAndSet(long newValue) { while (true) { long current = get(); if (compareAndSet(current, newValue)) return current; } } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(long expect, long update) { return unsafe.compareAndSwapLong(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * {@description.close} * * @param expect the expected value * @param update the new value * @return true if successful. */ public final boolean weakCompareAndSet(long expect, long update) { return unsafe.compareAndSwapLong(this, valueOffset, expect, update); } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value. * {@description.close} * * @return the previous value */ public final long getAndIncrement() { while (true) { long current = get(); long next = current + 1; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value. * {@description.close} * * @return the previous value */ public final long getAndDecrement() { while (true) { long current = get(); long next = current - 1; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value. * {@description.close} * * @param delta the value to add * @return the previous value */ public final long getAndAdd(long delta) { while (true) { long current = get(); long next = current + delta; if (compareAndSet(current, next)) return current; } } /** {@collect.stats} * {@description.open} * Atomically increments by one the current value. * {@description.close} * * @return the updated value */ public final long incrementAndGet() { for (;;) { long current = get(); long next = current + 1; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically decrements by one the current value. * {@description.close} * * @return the updated value */ public final long decrementAndGet() { for (;;) { long current = get(); long next = current - 1; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Atomically adds the given value to the current value. * {@description.close} * * @param delta the value to add * @return the updated value */ public final long addAndGet(long delta) { for (;;) { long current = get(); long next = current + delta; if (compareAndSet(current, next)) return next; } } /** {@collect.stats} * {@description.open} * Returns the String representation of the current value. * {@description.close} * @return the String representation of the current value. */ public String toString() { return Long.toString(get()); } public int intValue() { return (int)get(); } public long longValue() { return get(); } public float floatValue() { return (float)get(); } public double doubleValue() { return (double)get(); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea, Bill Scherer, and Michael Scott with * assistance from members of JCP JSR-166 Expert Group and released to * the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; import java.util.*; /** {@collect.stats} * {@description.open} * A {@linkplain BlockingQueue blocking queue} in which each insert * operation must wait for a corresponding remove operation by another * thread, and vice versa. A synchronous queue does not have any * internal capacity, not even a capacity of one. You cannot * <tt>peek</tt> at a synchronous queue because an element is only * present when you try to remove it; you cannot insert an element * (using any method) unless another thread is trying to remove it; * you cannot iterate as there is nothing to iterate. The * <em>head</em> of the queue is the element that the first queued * inserting thread is trying to add to the queue; if there is no such * queued thread then no element is available for removal and * <tt>poll()</tt> will return <tt>null</tt>. For purposes of other * <tt>Collection</tt> methods (for example <tt>contains</tt>), a * <tt>SynchronousQueue</tt> acts as an empty collection. This queue * does not permit <tt>null</tt> elements. * * <p>Synchronous queues are similar to rendezvous channels used in * CSP and Ada. They are well suited for handoff designs, in which an * object running in one thread must sync up with an object running * in another thread in order to hand it some information, event, or * task. * * <p> This class supports an optional fairness policy for ordering * waiting producer and consumer threads. By default, this ordering * is not guaranteed. However, a queue constructed with fairness set * to <tt>true</tt> grants threads access in FIFO order. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea and Bill Scherer and Michael Scott * @param <E> the type of elements held in this collection */ public class SynchronousQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable { private static final long serialVersionUID = -3223113410248163686L; /* * This class implements extensions of the dual stack and dual * queue algorithms described in "Nonblocking Concurrent Objects * with Condition Synchronization", by W. N. Scherer III and * M. L. Scott. 18th Annual Conf. on Distributed Computing, * Oct. 2004 (see also * http://www.cs.rochester.edu/u/scott/synchronization/pseudocode/duals.html). * The (Lifo) stack is used for non-fair mode, and the (Fifo) * queue for fair mode. The performance of the two is generally * similar. Fifo usually supports higher throughput under * contention but Lifo maintains higher thread locality in common * applications. * * A dual queue (and similarly stack) is one that at any given * time either holds "data" -- items provided by put operations, * or "requests" -- slots representing take operations, or is * empty. A call to "fulfill" (i.e., a call requesting an item * from a queue holding data or vice versa) dequeues a * complementary node. The most interesting feature of these * queues is that any operation can figure out which mode the * queue is in, and act accordingly without needing locks. * * Both the queue and stack extend abstract class Transferer * defining the single method transfer that does a put or a * take. These are unified into a single method because in dual * data structures, the put and take operations are symmetrical, * so nearly all code can be combined. The resulting transfer * methods are on the long side, but are easier to follow than * they would be if broken up into nearly-duplicated parts. * * The queue and stack data structures share many conceptual * similarities but very few concrete details. For simplicity, * they are kept distinct so that they can later evolve * separately. * * The algorithms here differ from the versions in the above paper * in extending them for use in synchronous queues, as well as * dealing with cancellation. The main differences include: * * 1. The original algorithms used bit-marked pointers, but * the ones here use mode bits in nodes, leading to a number * of further adaptations. * 2. SynchronousQueues must block threads waiting to become * fulfilled. * 3. Support for cancellation via timeout and interrupts, * including cleaning out cancelled nodes/threads * from lists to avoid garbage retention and memory depletion. * * Blocking is mainly accomplished using LockSupport park/unpark, * except that nodes that appear to be the next ones to become * fulfilled first spin a bit (on multiprocessors only). On very * busy synchronous queues, spinning can dramatically improve * throughput. And on less busy ones, the amount of spinning is * small enough not to be noticeable. * * Cleaning is done in different ways in queues vs stacks. For * queues, we can almost always remove a node immediately in O(1) * time (modulo retries for consistency checks) when it is * cancelled. But if it may be pinned as the current tail, it must * wait until some subsequent cancellation. For stacks, we need a * potentially O(n) traversal to be sure that we can remove the * node, but this can run concurrently with other threads * accessing the stack. * * While garbage collection takes care of most node reclamation * issues that otherwise complicate nonblocking algorithms, care * is taken to "forget" references to data, other nodes, and * threads that might be held on to long-term by blocked * threads. In cases where setting to null would otherwise * conflict with main algorithms, this is done by changing a * node's link to now point to the node itself. This doesn't arise * much for Stack nodes (because blocked threads do not hang on to * old head pointers), but references in Queue nodes must be * aggressively forgotten to avoid reachability of everything any * node has ever referred to since arrival. */ /** {@collect.stats} * {@description.open} * Shared internal API for dual stacks and queues. * {@description.close} */ static abstract class Transferer { /** {@collect.stats} * {@description.open} * Performs a put or take. * {@description.close} * * @param e if non-null, the item to be handed to a consumer; * if null, requests that transfer return an item * offered by producer. * @param timed if this operation should timeout * @param nanos the timeout, in nanoseconds * @return if non-null, the item provided or received; if null, * the operation failed due to timeout or interrupt -- * the caller can distinguish which of these occurred * by checking Thread.interrupted. */ abstract Object transfer(Object e, boolean timed, long nanos); } /** {@collect.stats} * {@description.open} * The number of CPUs, for spin control * {@description.close} */ static final int NCPUS = Runtime.getRuntime().availableProcessors(); /** {@collect.stats} * {@description.open} * The number of times to spin before blocking in timed waits. * The value is empirically derived -- it works well across a * variety of processors and OSes. Empirically, the best value * seems not to vary with number of CPUs (beyond 2) so is just * a constant. * {@description.close} */ static final int maxTimedSpins = (NCPUS < 2)? 0 : 32; /** {@collect.stats} * {@description.open} * The number of times to spin before blocking in untimed waits. * This is greater than timed value because untimed waits spin * faster since they don't need to check times on each spin. * {@description.close} */ static final int maxUntimedSpins = maxTimedSpins * 16; /** {@collect.stats} * {@description.open} * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices. * {@description.close} */ static final long spinForTimeoutThreshold = 1000L; /** {@collect.stats} * {@description.open} * Dual stack * {@description.close} */ static final class TransferStack extends Transferer { /* * This extends Scherer-Scott dual stack algorithm, differing, * among other ways, by using "covering" nodes rather than * bit-marked pointers: Fulfilling operations push on marker * nodes (with FULFILLING bit set in mode) to reserve a spot * to match a waiting node. */ /* Modes for SNodes, ORed together in node fields */ /** {@collect.stats} * {@description.open} * Node represents an unfulfilled consumer * {@description.close} */ static final int REQUEST = 0; /** {@collect.stats} * {@description.open} * Node represents an unfulfilled producer * {@description.close} */ static final int DATA = 1; /** {@collect.stats} * {@description.open} * Node is fulfilling another unfulfilled DATA or REQUEST * {@description.close} */ static final int FULFILLING = 2; /** {@collect.stats} * {@description.open} * Return true if m has fulfilling bit set * {@description.close} */ static boolean isFulfilling(int m) { return (m & FULFILLING) != 0; } /** {@collect.stats} * {@description.open} * Node class for TransferStacks. * {@description.close} */ static final class SNode { volatile SNode next; // next node in stack volatile SNode match; // the node matched to this volatile Thread waiter; // to control park/unpark Object item; // data; or null for REQUESTs int mode; // Note: item and mode fields don't need to be volatile // since they are always written before, and read after, // other volatile/atomic operations. SNode(Object item) { this.item = item; } static final AtomicReferenceFieldUpdater<SNode, SNode> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (SNode.class, SNode.class, "next"); boolean casNext(SNode cmp, SNode val) { return (cmp == next && nextUpdater.compareAndSet(this, cmp, val)); } static final AtomicReferenceFieldUpdater<SNode, SNode> matchUpdater = AtomicReferenceFieldUpdater.newUpdater (SNode.class, SNode.class, "match"); /** {@collect.stats} * {@description.open} * Tries to match node s to this node, if so, waking up thread. * Fulfillers call tryMatch to identify their waiters. * Waiters block until they have been matched. * {@description.close} * * @param s the node to match * @return true if successfully matched to s */ boolean tryMatch(SNode s) { if (match == null && matchUpdater.compareAndSet(this, null, s)) { Thread w = waiter; if (w != null) { // waiters need at most one unpark waiter = null; LockSupport.unpark(w); } return true; } return match == s; } /** {@collect.stats} * {@description.open} * Tries to cancel a wait by matching node to itself. * {@description.close} */ void tryCancel() { matchUpdater.compareAndSet(this, null, this); } boolean isCancelled() { return match == this; } } /** {@collect.stats} * {@description.open} * The head (top) of the stack * {@description.close} */ volatile SNode head; static final AtomicReferenceFieldUpdater<TransferStack, SNode> headUpdater = AtomicReferenceFieldUpdater.newUpdater (TransferStack.class, SNode.class, "head"); boolean casHead(SNode h, SNode nh) { return h == head && headUpdater.compareAndSet(this, h, nh); } /** {@collect.stats} * {@description.open} * Creates or resets fields of a node. Called only from transfer * where the node to push on stack is lazily created and * reused when possible to help reduce intervals between reads * and CASes of head and to avoid surges of garbage when CASes * to push nodes fail due to contention. * {@description.close} */ static SNode snode(SNode s, Object e, SNode next, int mode) { if (s == null) s = new SNode(e); s.mode = mode; s.next = next; return s; } /** {@collect.stats} * {@description.open} * Puts or takes an item. * {@description.close} */ Object transfer(Object e, boolean timed, long nanos) { /* * Basic algorithm is to loop trying one of three actions: * * 1. If apparently empty or already containing nodes of same * mode, try to push node on stack and wait for a match, * returning it, or null if cancelled. * * 2. If apparently containing node of complementary mode, * try to push a fulfilling node on to stack, match * with corresponding waiting node, pop both from * stack, and return matched item. The matching or * unlinking might not actually be necessary because of * other threads performing action 3: * * 3. If top of stack already holds another fulfilling node, * help it out by doing its match and/or pop * operations, and then continue. The code for helping * is essentially the same as for fulfilling, except * that it doesn't return the item. */ SNode s = null; // constructed/reused as needed int mode = (e == null)? REQUEST : DATA; for (;;) { SNode h = head; if (h == null || h.mode == mode) { // empty or same-mode if (timed && nanos <= 0) { // can't wait if (h != null && h.isCancelled()) casHead(h, h.next); // pop cancelled node else return null; } else if (casHead(h, s = snode(s, e, h, mode))) { SNode m = awaitFulfill(s, timed, nanos); if (m == s) { // wait was cancelled clean(s); return null; } if ((h = head) != null && h.next == s) casHead(h, s.next); // help s's fulfiller return mode == REQUEST? m.item : s.item; } } else if (!isFulfilling(h.mode)) { // try to fulfill if (h.isCancelled()) // already cancelled casHead(h, h.next); // pop and retry else if (casHead(h, s=snode(s, e, h, FULFILLING|mode))) { for (;;) { // loop until matched or waiters disappear SNode m = s.next; // m is s's match if (m == null) { // all waiters are gone casHead(s, null); // pop fulfill node s = null; // use new node next time break; // restart main loop } SNode mn = m.next; if (m.tryMatch(s)) { casHead(s, mn); // pop both s and m return (mode == REQUEST)? m.item : s.item; } else // lost match s.casNext(m, mn); // help unlink } } } else { // help a fulfiller SNode m = h.next; // m is h's match if (m == null) // waiter is gone casHead(h, null); // pop fulfilling node else { SNode mn = m.next; if (m.tryMatch(h)) // help match casHead(h, mn); // pop both h and m else // lost match h.casNext(m, mn); // help unlink } } } } /** {@collect.stats} * {@description.open} * Spins/blocks until node s is matched by a fulfill operation. * {@description.close} * * @param s the waiting node * @param timed true if timed wait * @param nanos timeout value * @return matched node, or s if cancelled */ SNode awaitFulfill(SNode s, boolean timed, long nanos) { /* * When a node/thread is about to block, it sets its waiter * field and then rechecks state at least one more time * before actually parking, thus covering race vs * fulfiller noticing that waiter is non-null so should be * woken. * * When invoked by nodes that appear at the point of call * to be at the head of the stack, calls to park are * preceded by spins to avoid blocking when producers and * consumers are arriving very close in time. This can * happen enough to bother only on multiprocessors. * * The order of checks for returning out of main loop * reflects fact that interrupts have precedence over * normal returns, which have precedence over * timeouts. (So, on timeout, one last check for match is * done before giving up.) Except that calls from untimed * SynchronousQueue.{poll/offer} don't check interrupts * and don't wait at all, so are trapped in transfer * method rather than calling awaitFulfill. */ long lastTime = (timed)? System.nanoTime() : 0; Thread w = Thread.currentThread(); SNode h = head; int spins = (shouldSpin(s)? (timed? maxTimedSpins : maxUntimedSpins) : 0); for (;;) { if (w.isInterrupted()) s.tryCancel(); SNode m = s.match; if (m != null) return m; if (timed) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.tryCancel(); continue; } } if (spins > 0) spins = shouldSpin(s)? (spins-1) : 0; else if (s.waiter == null) s.waiter = w; // establish waiter so can park next iter else if (!timed) LockSupport.park(this); else if (nanos > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanos); } } /** {@collect.stats} * {@description.open} * Returns true if node s is at head or there is an active * fulfiller. * {@description.close} */ boolean shouldSpin(SNode s) { SNode h = head; return (h == s || h == null || isFulfilling(h.mode)); } /** {@collect.stats} * {@description.open} * Unlinks s from the stack. * {@description.close} */ void clean(SNode s) { s.item = null; // forget item s.waiter = null; // forget thread /* * At worst we may need to traverse entire stack to unlink * s. If there are multiple concurrent calls to clean, we * might not see s if another thread has already removed * it. But we can stop when we see any node known to * follow s. We use s.next unless it too is cancelled, in * which case we try the node one past. We don't check any * further because we don't want to doubly traverse just to * find sentinel. */ SNode past = s.next; if (past != null && past.isCancelled()) past = past.next; // Absorb cancelled nodes at head SNode p; while ((p = head) != null && p != past && p.isCancelled()) casHead(p, p.next); // Unsplice embedded nodes while (p != null && p != past) { SNode n = p.next; if (n != null && n.isCancelled()) p.casNext(n, n.next); else p = n; } } } /** {@collect.stats} * {@description.open} * Dual Queue * {@description.close} */ static final class TransferQueue extends Transferer { /* * This extends Scherer-Scott dual queue algorithm, differing, * among other ways, by using modes within nodes rather than * marked pointers. The algorithm is a little simpler than * that for stacks because fulfillers do not need explicit * nodes, and matching is done by CAS'ing QNode.item field * from non-null to null (for put) or vice versa (for take). */ /** {@collect.stats} * {@description.open} * Node class for TransferQueue. * {@description.close} */ static final class QNode { volatile QNode next; // next node in queue volatile Object item; // CAS'ed to or from null volatile Thread waiter; // to control park/unpark final boolean isData; QNode(Object item, boolean isData) { this.item = item; this.isData = isData; } static final AtomicReferenceFieldUpdater<QNode, QNode> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (QNode.class, QNode.class, "next"); boolean casNext(QNode cmp, QNode val) { return (next == cmp && nextUpdater.compareAndSet(this, cmp, val)); } static final AtomicReferenceFieldUpdater<QNode, Object> itemUpdater = AtomicReferenceFieldUpdater.newUpdater (QNode.class, Object.class, "item"); boolean casItem(Object cmp, Object val) { return (item == cmp && itemUpdater.compareAndSet(this, cmp, val)); } /** {@collect.stats} * {@description.open} * Tries to cancel by CAS'ing ref to this as item. * {@description.close} */ void tryCancel(Object cmp) { itemUpdater.compareAndSet(this, cmp, this); } boolean isCancelled() { return item == this; } /** {@collect.stats} * {@description.open} * Returns true if this node is known to be off the queue * because its next pointer has been forgotten due to * an advanceHead operation. * {@description.close} */ boolean isOffList() { return next == this; } } /** {@collect.stats} * {@description.open} * Head of queue * {@description.close} */ transient volatile QNode head; /** {@collect.stats} * {@description.open} * Tail of queue * {@description.close} */ transient volatile QNode tail; /** {@collect.stats} * {@description.open} * Reference to a cancelled node that might not yet have been * unlinked from queue because it was the last inserted node * when it cancelled. * {@description.close} */ transient volatile QNode cleanMe; TransferQueue() { QNode h = new QNode(null, false); // initialize to dummy node. head = h; tail = h; } static final AtomicReferenceFieldUpdater<TransferQueue, QNode> headUpdater = AtomicReferenceFieldUpdater.newUpdater (TransferQueue.class, QNode.class, "head"); /** {@collect.stats} * {@description.open} * Tries to cas nh as new head; if successful, unlink * old head's next node to avoid garbage retention. * {@description.close} */ void advanceHead(QNode h, QNode nh) { if (h == head && headUpdater.compareAndSet(this, h, nh)) h.next = h; // forget old next } static final AtomicReferenceFieldUpdater<TransferQueue, QNode> tailUpdater = AtomicReferenceFieldUpdater.newUpdater (TransferQueue.class, QNode.class, "tail"); /** {@collect.stats} * {@description.open} * Tries to cas nt as new tail. * {@description.close} */ void advanceTail(QNode t, QNode nt) { if (tail == t) tailUpdater.compareAndSet(this, t, nt); } static final AtomicReferenceFieldUpdater<TransferQueue, QNode> cleanMeUpdater = AtomicReferenceFieldUpdater.newUpdater (TransferQueue.class, QNode.class, "cleanMe"); /** {@collect.stats} * {@description.open} * Tries to CAS cleanMe slot. * {@description.close} */ boolean casCleanMe(QNode cmp, QNode val) { return (cleanMe == cmp && cleanMeUpdater.compareAndSet(this, cmp, val)); } /** {@collect.stats} * {@description.open} * Puts or takes an item. * {@description.close} */ Object transfer(Object e, boolean timed, long nanos) { /* Basic algorithm is to loop trying to take either of * two actions: * * 1. If queue apparently empty or holding same-mode nodes, * try to add node to queue of waiters, wait to be * fulfilled (or cancelled) and return matching item. * * 2. If queue apparently contains waiting items, and this * call is of complementary mode, try to fulfill by CAS'ing * item field of waiting node and dequeuing it, and then * returning matching item. * * In each case, along the way, check for and try to help * advance head and tail on behalf of other stalled/slow * threads. * * The loop starts off with a null check guarding against * seeing uninitialized head or tail values. This never * happens in current SynchronousQueue, but could if * callers held non-volatile/final ref to the * transferer. The check is here anyway because it places * null checks at top of loop, which is usually faster * than having them implicitly interspersed. */ QNode s = null; // constructed/reused as needed boolean isData = (e != null); for (;;) { QNode t = tail; QNode h = head; if (t == null || h == null) // saw uninitialized value continue; // spin if (h == t || t.isData == isData) { // empty or same-mode QNode tn = t.next; if (t != tail) // inconsistent read continue; if (tn != null) { // lagging tail advanceTail(t, tn); continue; } if (timed && nanos <= 0) // can't wait return null; if (s == null) s = new QNode(e, isData); if (!t.casNext(null, s)) // failed to link in continue; advanceTail(t, s); // swing tail and wait Object x = awaitFulfill(s, e, timed, nanos); if (x == s) { // wait was cancelled clean(t, s); return null; } if (!s.isOffList()) { // not already unlinked advanceHead(t, s); // unlink if head if (x != null) // and forget fields s.item = s; s.waiter = null; } return (x != null)? x : e; } else { // complementary-mode QNode m = h.next; // node to fulfill if (t != tail || m == null || h != head) continue; // inconsistent read Object x = m.item; if (isData == (x != null) || // m already fulfilled x == m || // m cancelled !m.casItem(x, e)) { // lost CAS advanceHead(h, m); // dequeue and retry continue; } advanceHead(h, m); // successfully fulfilled LockSupport.unpark(m.waiter); return (x != null)? x : e; } } } /** {@collect.stats} * {@description.open} * Spins/blocks until node s is fulfilled. * {@description.close} * * @param s the waiting node * @param e the comparison value for checking match * @param timed true if timed wait * @param nanos timeout value * @return matched item, or s if cancelled */ Object awaitFulfill(QNode s, Object e, boolean timed, long nanos) { /* Same idea as TransferStack.awaitFulfill */ long lastTime = (timed)? System.nanoTime() : 0; Thread w = Thread.currentThread(); int spins = ((head.next == s) ? (timed? maxTimedSpins : maxUntimedSpins) : 0); for (;;) { if (w.isInterrupted()) s.tryCancel(e); Object x = s.item; if (x != e) return x; if (timed) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.tryCancel(e); continue; } } if (spins > 0) --spins; else if (s.waiter == null) s.waiter = w; else if (!timed) LockSupport.park(this); else if (nanos > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanos); } } /** {@collect.stats} * {@description.open} * Gets rid of cancelled node s with original predecessor pred. * {@description.close} */ void clean(QNode pred, QNode s) { s.waiter = null; // forget thread /* * At any given time, exactly one node on list cannot be * deleted -- the last inserted node. To accommodate this, * if we cannot delete s, we save its predecessor as * "cleanMe", deleting the previously saved version * first. At least one of node s or the node previously * saved can always be deleted, so this always terminates. */ while (pred.next == s) { // Return early if already unlinked QNode h = head; QNode hn = h.next; // Absorb cancelled first node as head if (hn != null && hn.isCancelled()) { advanceHead(h, hn); continue; } QNode t = tail; // Ensure consistent read for tail if (t == h) return; QNode tn = t.next; if (t != tail) continue; if (tn != null) { advanceTail(t, tn); continue; } if (s != t) { // If not tail, try to unsplice QNode sn = s.next; if (sn == s || pred.casNext(s, sn)) return; } QNode dp = cleanMe; if (dp != null) { // Try unlinking previous cancelled node QNode d = dp.next; QNode dn; if (d == null || // d is gone or d == dp || // d is off list or !d.isCancelled() || // d not cancelled or (d != t && // d not tail and (dn = d.next) != null && // has successor dn != d && // that is on list dp.casNext(d, dn))) // d unspliced casCleanMe(dp, null); if (dp == pred) return; // s is already saved node } else if (casCleanMe(null, pred)) return; // Postpone cleaning s } } } /** {@collect.stats} * {@description.open} * The transferer. Set only in constructor, but cannot be declared * as final without further complicating serialization. Since * this is accessed only at most once per public method, there * isn't a noticeable performance penalty for using volatile * instead of final here. * {@description.close} */ private transient volatile Transferer transferer; /** {@collect.stats} * {@description.open} * Creates a <tt>SynchronousQueue</tt> with nonfair access policy. * {@description.close} */ public SynchronousQueue() { this(false); } /** {@collect.stats} * {@description.open} * Creates a <tt>SynchronousQueue</tt> with the specified fairness policy. * {@description.close} * * @param fair if true, waiting threads contend in FIFO order for * access; otherwise the order is unspecified. */ public SynchronousQueue(boolean fair) { transferer = (fair)? new TransferQueue() : new TransferStack(); } /** {@collect.stats} * {@description.open} * Adds the specified element to this queue, waiting if necessary for * another thread to receive it. * {@description.close} * * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public void put(E o) throws InterruptedException { if (o == null) throw new NullPointerException(); if (transferer.transfer(o, false, 0) == null) { Thread.interrupted(); throw new InterruptedException(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue, waiting if necessary * up to the specified wait time for another thread to receive it. * {@description.close} * * @return <tt>true</tt> if successful, or <tt>false</tt> if the * specified waiting time elapses before a consumer appears. * @throws InterruptedException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException { if (o == null) throw new NullPointerException(); if (transferer.transfer(o, true, unit.toNanos(timeout)) != null) return true; if (!Thread.interrupted()) return false; throw new InterruptedException(); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue, if another thread is * waiting to receive it. * {@description.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this queue, else * <tt>false</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { if (e == null) throw new NullPointerException(); return transferer.transfer(e, true, 0) != null; } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, waiting if necessary * for another thread to insert it. * {@description.close} * * @return the head of this queue * @throws InterruptedException {@inheritDoc} */ public E take() throws InterruptedException { Object e = transferer.transfer(null, false, 0); if (e != null) return (E)e; Thread.interrupted(); throw new InterruptedException(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, waiting * if necessary up to the specified wait time, for another thread * to insert it. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if the * specified waiting time elapses before an element is present. * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { Object e = transferer.transfer(null, true, unit.toNanos(timeout)); if (e != null || !Thread.interrupted()) return (E)e; throw new InterruptedException(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, if another thread * is currently making an element available. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if no * element is available. */ public E poll() { return (E)transferer.transfer(null, true, 0); } /** {@collect.stats} * {@description.open} * Always returns <tt>true</tt>. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @return <tt>true</tt> */ public boolean isEmpty() { return true; } /** {@collect.stats} * {@description.open} * Always returns zero. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @return zero. */ public int size() { return 0; } /** {@collect.stats} * {@description.open} * Always returns zero. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @return zero. */ public int remainingCapacity() { return 0; } /** {@collect.stats} * {@description.open} * Does nothing. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} */ public void clear() { } /** {@collect.stats} * {@description.open} * Always returns <tt>false</tt>. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @param o the element * @return <tt>false</tt> */ public boolean contains(Object o) { return false; } /** {@collect.stats} * {@description.open} * Always returns <tt>false</tt>. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @param o the element to remove * @return <tt>false</tt> */ public boolean remove(Object o) { return false; } /** {@collect.stats} * {@description.open} * Returns <tt>false</tt> unless the given collection is empty. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @param c the collection * @return <tt>false</tt> unless given collection is empty */ public boolean containsAll(Collection<?> c) { return c.isEmpty(); } /** {@collect.stats} * {@description.open} * Always returns <tt>false</tt>. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @param c the collection * @return <tt>false</tt> */ public boolean removeAll(Collection<?> c) { return false; } /** {@collect.stats} * {@description.open} * Always returns <tt>false</tt>. * A <tt>SynchronousQueue</tt> has no internal capacity. * {@description.close} * * @param c the collection * @return <tt>false</tt> */ public boolean retainAll(Collection<?> c) { return false; } /** {@collect.stats} * {@description.open} * Always returns <tt>null</tt>. * A <tt>SynchronousQueue</tt> does not return elements * unless actively waited on. * {@description.close} * * @return <tt>null</tt> */ public E peek() { return null; } /** {@collect.stats} * {@description.open} * Returns an empty iterator in which <tt>hasNext</tt> always returns * <tt>false</tt>. * {@description.close} * * @return an empty iterator */ public Iterator<E> iterator() { return Collections.<E>emptyList().iterator(); } /** {@collect.stats} * {@description.open} * Returns a zero-length array. * {@description.close} * @return a zero-length array */ public Object[] toArray() { return new Object[0]; } /** {@collect.stats} * {@description.open} * Sets the zeroeth element of the specified array to <tt>null</tt> * (if the array has non-zero length) and returns it. * {@description.close} * * @param a the array * @return the specified array * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); int n = 0; E e; while ( (e = poll()) != null) { c.add(e); ++n; } return n; } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); int n = 0; E e; while (n < maxElements && (e = poll()) != null) { c.add(e); ++n; } return n; } /* * To cope with serialization strategy in the 1.5 version of * SynchronousQueue, we declare some unused classes and fields * that exist solely to enable serializability across versions. * These fields are never used, so are initialized only if this * object is ever serialized or deserialized. */ static class WaitQueue implements java.io.Serializable { } static class LifoWaitQueue extends WaitQueue { private static final long serialVersionUID = -3633113410248163686L; } static class FifoWaitQueue extends WaitQueue { private static final long serialVersionUID = -3623113410248163686L; } private ReentrantLock qlock; private WaitQueue waitingProducers; private WaitQueue waitingConsumers; /** {@collect.stats} * {@description.open} * Save the state to a stream (that is, serialize it). * {@description.close} * * @param s the stream */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { boolean fair = transferer instanceof TransferQueue; if (fair) { qlock = new ReentrantLock(true); waitingProducers = new FifoWaitQueue(); waitingConsumers = new FifoWaitQueue(); } else { qlock = new ReentrantLock(); waitingProducers = new LifoWaitQueue(); waitingConsumers = new LifoWaitQueue(); } s.defaultWriteObject(); } private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); if (waitingProducers instanceof FifoWaitQueue) transferer = new TransferQueue(); else transferer = new TransferStack(); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.List; import java.util.Collection; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; /** {@collect.stats} * {@description.open} * An {@link Executor} that provides methods to manage termination and * methods that can produce a {@link Future} for tracking progress of * one or more asynchronous tasks. * * <p> An <tt>ExecutorService</tt> can be shut down, which will cause * it to reject new tasks. Two different methods are provided for * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown} * method will allow previously submitted tasks to execute before * terminating, while the {@link #shutdownNow} method prevents waiting * tasks from starting and attempts to stop currently executing tasks. * Upon termination, an executor has no tasks actively executing, no * tasks awaiting execution, and no new tasks can be submitted. An * unused <tt>ExecutorService</tt> should be shut down to allow * reclamation of its resources. * * <p> Method <tt>submit</tt> extends base method {@link * Executor#execute} by creating and returning a {@link Future} that * can be used to cancel execution and/or wait for completion. * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most * commonly useful forms of bulk execution, executing a collection of * tasks and then waiting for at least one, or all, to * complete. (Class {@link ExecutorCompletionService} can be used to * write customized variants of these methods.) * * <p>The {@link Executors} class provides factory methods for the * executor services provided in this package. * * <h3>Usage Examples</h3> * * Here is a sketch of a network service in which threads in a thread * pool service incoming requests. It uses the preconfigured {@link * Executors#newFixedThreadPool} factory method: * * <pre> * class NetworkService implements Runnable { * private final ServerSocket serverSocket; * private final ExecutorService pool; * * public NetworkService(int port, int poolSize) * throws IOException { * serverSocket = new ServerSocket(port); * pool = Executors.newFixedThreadPool(poolSize); * } * * public void run() { // run the service * try { * for (;;) { * pool.execute(new Handler(serverSocket.accept())); * } * } catch (IOException ex) { * pool.shutdown(); * } * } * } * * class Handler implements Runnable { * private final Socket socket; * Handler(Socket socket) { this.socket = socket; } * public void run() { * // read and service request on socket * } * } * </pre> * * The following method shuts down an <tt>ExecutorService</tt> in two phases, * first by calling <tt>shutdown</tt> to reject incoming tasks, and then * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks: * * <pre> * void shutdownAndAwaitTermination(ExecutorService pool) { * pool.shutdown(); // Disable new tasks from being submitted * try { * // Wait a while for existing tasks to terminate * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { * pool.shutdownNow(); // Cancel currently executing tasks * // Wait a while for tasks to respond to being cancelled * if (!pool.awaitTermination(60, TimeUnit.SECONDS)) * System.err.println("Pool did not terminate"); * } * } catch (InterruptedException ie) { * // (Re-)Cancel if current thread also interrupted * pool.shutdownNow(); * // Preserve interrupt status * Thread.currentThread().interrupt(); * } * } * </pre> * * <p>Memory consistency effects: Actions in a thread prior to the * submission of a {@code Runnable} or {@code Callable} task to an * {@code ExecutorService} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * any actions taken by that task, which in turn <i>happen-before</i> the * result is retrieved via {@code Future.get()}. * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface ExecutorService extends Executor { /** {@collect.stats} * {@description.open} * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. * Invocation has no additional effect if already shut down. * {@description.close} * * @throws SecurityException if a security manager exists and * shutting down this ExecutorService may manipulate * threads that the caller is not permitted to modify * because it does not hold {@link * java.lang.RuntimePermission}<tt>("modifyThread")</tt>, * or the security manager's <tt>checkAccess</tt> method * denies access. */ void shutdown(); /** {@collect.stats} * {@description.open} * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks that were * awaiting execution. * * <p>There are no guarantees beyond best-effort attempts to stop * processing actively executing tasks. For example, typical * implementations will cancel via {@link Thread#interrupt}, so any * task that fails to respond to interrupts may never terminate. * {@description.close} * * @return list of tasks that never commenced execution * @throws SecurityException if a security manager exists and * shutting down this ExecutorService may manipulate * threads that the caller is not permitted to modify * because it does not hold {@link * java.lang.RuntimePermission}<tt>("modifyThread")</tt>, * or the security manager's <tt>checkAccess</tt> method * denies access. */ List<Runnable> shutdownNow(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this executor has been shut down. * {@description.close} * * @return <tt>true</tt> if this executor has been shut down */ boolean isShutdown(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if all tasks have completed following shut down. * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first. * {@description.close} * * @return <tt>true</tt> if all tasks have completed following shut down */ boolean isTerminated(); /** {@collect.stats} * {@description.open} * Blocks until all tasks have completed execution after a shutdown * request, or the timeout occurs, or the current thread is * interrupted, whichever happens first. * {@description.close} * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return <tt>true</tt> if this executor terminated and * <tt>false</tt> if the timeout elapsed before termination * @throws InterruptedException if interrupted while waiting */ boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Submits a value-returning task for execution and returns a * Future representing the pending results of the task. The * Future's <tt>get</tt> method will return the task's result upon * successful completion. * * <p> * If you would like to immediately block waiting * for a task, you can use constructions of the form * <tt>result = exec.submit(aCallable).get();</tt> * * <p> Note: The {@link Executors} class includes a set of methods * that can convert some other common closure-like objects, * for example, {@link java.security.PrivilegedAction} to * {@link Callable} form so they can be submitted. * {@description.close} * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ <T> Future<T> submit(Callable<T> task); /** {@collect.stats} * {@description.open} * Submits a Runnable task for execution and returns a Future * representing that task. The Future's <tt>get</tt> method will * return the given result upon successful completion. * {@description.close} * * @param task the task to submit * @param result the result to return * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ <T> Future<T> submit(Runnable task, T result); /** {@collect.stats} * {@description.open} * Submits a Runnable task for execution and returns a Future * representing that task. The Future's <tt>get</tt> method will * return <tt>null</tt> upon <em>successful</em> completion. * {@description.close} * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ Future<?> submit(Runnable task); /** {@collect.stats} * {@description.open} * Executes the given tasks, returning a list of Futures holding * their status and results when all complete. * {@link Future#isDone} is <tt>true</tt> for each * element of the returned list. * Note that a <em>completed</em> task could have * terminated either normally or by throwing an exception. * The results of this method are undefined if the given * collection is modified while this operation is in progress. * {@description.close} * * @param tasks the collection of tasks * @return A list of Futures representing the tasks, in the same * sequential order as produced by the iterator for the * given task list, each of which has completed. * @throws InterruptedException if interrupted while waiting, in * which case unfinished tasks are cancelled. * @throws NullPointerException if tasks or any of its elements are <tt>null</tt> * @throws RejectedExecutionException if any task cannot be * scheduled for execution */ <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException; /** {@collect.stats} * {@description.open} * Executes the given tasks, returning a list of Futures holding * their status and results * when all complete or the timeout expires, whichever happens first. * {@link Future#isDone} is <tt>true</tt> for each * element of the returned list. * Upon return, tasks that have not completed are cancelled. * Note that a <em>completed</em> task could have * terminated either normally or by throwing an exception. * The results of this method are undefined if the given * collection is modified while this operation is in progress. * {@description.close} * * @param tasks the collection of tasks * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return a list of Futures representing the tasks, in the same * sequential order as produced by the iterator for the * given task list. If the operation did not time out, * each task will have completed. If it did time out, some * of these tasks will not have completed. * @throws InterruptedException if interrupted while waiting, in * which case unfinished tasks are cancelled * @throws NullPointerException if tasks, any of its elements, or * unit are <tt>null</tt> * @throws RejectedExecutionException if any task cannot be scheduled * for execution */ <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * 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. * {@description.close} * * @param tasks the collection of tasks * @return the result returned by one of the tasks * @throws InterruptedException if interrupted while waiting * @throws NullPointerException if tasks or any of its elements * are <tt>null</tt> * @throws IllegalArgumentException if tasks is empty * @throws ExecutionException if no task successfully completes * @throws RejectedExecutionException if tasks cannot be scheduled * for execution */ <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; /** {@collect.stats} * {@description.open} * Executes the given tasks, returning the result * of one that has completed successfully (i.e., without throwing * an exception), if any do before the given timeout elapses. * 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. * {@description.close} * * @param tasks the collection of tasks * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return the result returned by one of the tasks. * @throws InterruptedException if interrupted while waiting * @throws NullPointerException if tasks, any of its elements, or * unit are <tt>null</tt> * @throws TimeoutException if the given timeout elapses before * any task successfully completes * @throws ExecutionException if no task successfully completes * @throws RejectedExecutionException if tasks cannot be scheduled * for execution */ <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; /** {@collect.stats} * {@description.open} * A synchronization aid that allows one or more threads to wait until * a set of operations being performed in other threads completes. * * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>. * The {@link #await await} methods block until the current count reaches * zero due to invocations of the {@link #countDown} method, after which * all waiting threads are released and any subsequent invocations of * {@link #await await} return immediately. This is a one-shot phenomenon * -- the count cannot be reset. If you need a version that resets the * count, consider using a {@link CyclicBarrier}. * * <p>A {@code CountDownLatch} is a versatile synchronization tool * and can be used for a number of purposes. A * {@code CountDownLatch} initialized with a count of one serves as a * simple on/off latch, or gate: all threads invoking {@link #await await} * wait at the gate until it is opened by a thread invoking {@link * #countDown}. A {@code CountDownLatch} initialized to <em>N</em> * can be used to make one thread wait until <em>N</em> threads have * completed some action, or some action has been completed N times. * * <p>A useful property of a {@code CountDownLatch} is that it * doesn't require that threads calling {@code countDown} wait for * the count to reach zero before proceeding, it simply prevents any * thread from proceeding past an {@link #await await} until all * threads could pass. * * <p><b>Sample usage:</b> Here is a pair of classes in which a group * of worker threads use two countdown latches: * <ul> * <li>The first is a start signal that prevents any worker from proceeding * until the driver is ready for them to proceed; * <li>The second is a completion signal that allows the driver to wait * until all workers have completed. * </ul> * * <pre> * class Driver { // ... * void main() throws InterruptedException { * CountDownLatch startSignal = new CountDownLatch(1); * CountDownLatch doneSignal = new CountDownLatch(N); * * for (int i = 0; i < N; ++i) // create and start threads * new Thread(new Worker(startSignal, doneSignal)).start(); * * doSomethingElse(); // don't let run yet * startSignal.countDown(); // let all threads proceed * doSomethingElse(); * doneSignal.await(); // wait for all to finish * } * } * * class Worker implements Runnable { * private final CountDownLatch startSignal; * private final CountDownLatch doneSignal; * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) { * this.startSignal = startSignal; * this.doneSignal = doneSignal; * } * public void run() { * try { * startSignal.await(); * doWork(); * doneSignal.countDown(); * } catch (InterruptedException ex) {} // return; * } * * void doWork() { ... } * } * * </pre> * * <p>Another typical usage would be to divide a problem into N parts, * describe each part with a Runnable that executes that portion and * counts down on the latch, and queue all the Runnables to an * Executor. When all sub-parts are complete, the coordinating thread * will be able to pass through await. (When threads must repeatedly * count down in this way, instead use a {@link CyclicBarrier}.) * * <pre> * class Driver2 { // ... * void main() throws InterruptedException { * CountDownLatch doneSignal = new CountDownLatch(N); * Executor e = ... * * for (int i = 0; i < N; ++i) // create and start threads * e.execute(new WorkerRunnable(doneSignal, i)); * * doneSignal.await(); // wait for all to finish * } * } * * class WorkerRunnable implements Runnable { * private final CountDownLatch doneSignal; * private final int i; * WorkerRunnable(CountDownLatch doneSignal, int i) { * this.doneSignal = doneSignal; * this.i = i; * } * public void run() { * try { * doWork(i); * doneSignal.countDown(); * } catch (InterruptedException ex) {} // return; * } * * void doWork() { ... } * } * * </pre> * * <p>Memory consistency effects: Actions in a thread prior to calling * {@code countDown()} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions following a successful return from a corresponding * {@code await()} in another thread. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class CountDownLatch { /** {@collect.stats} * {@description.open} * Synchronization control For CountDownLatch. * Uses AQS state to represent count. * {@description.close} */ private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; Sync(int count) { setState(count); } int getCount() { return getState(); } protected int tryAcquireShared(int acquires) { return getState() == 0? 1 : -1; } protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } } } private final Sync sync; /** {@collect.stats} * {@description.open} * Constructs a {@code CountDownLatch} initialized with the given count. * {@description.close} * * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * @throws IllegalArgumentException if {@code count} is negative */ public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); } /** {@collect.stats} * {@description.open} * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. * * <p>If the current count is zero then this method returns immediately. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of two things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * {@description.close} * * @throws InterruptedException if the current thread is interrupted * while waiting */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** {@collect.stats} * {@description.open} * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}, * or the specified waiting time elapses. * * <p>If the current count is zero then this method returns immediately * with the value {@code true}. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of three things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * </ul> * * <p>If the count reaches zero then the method returns with the * value {@code true}. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * {@description.close} * * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return {@code true} if the count reached zero and {@code false} * if the waiting time elapsed before the count reached zero * @throws InterruptedException if the current thread is interrupted * while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Decrements the count of the latch, releasing all waiting threads if * the count reaches zero. * * <p>If the current count is greater than zero then it is decremented. * If the new count is zero then all waiting threads are re-enabled for * thread scheduling purposes. * * <p>If the current count equals zero then nothing happens. * {@description.close} */ public void countDown() { sync.releaseShared(1); } /** {@collect.stats} * {@description.open} * Returns the current count. * * <p>This method is typically used for debugging and testing purposes. * {@description.close} * * @return the current count */ public long getCount() { return sync.getCount(); } /** {@collect.stats} * {@description.open} * Returns a string identifying this latch, as well as its state. * The state, in brackets, includes the String {@code "Count ="} * followed by the current count. * {@description.close} * * @return a string identifying this latch, as well as its state */ public String toString() { return super.toString() + "[Count = " + sync.getCount() + "]"; } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.*; /** {@collect.stats} * {@description.open} * An unbounded {@linkplain BlockingQueue blocking queue} that uses * the same ordering rules as class {@link PriorityQueue} and supplies * blocking retrieval operations. While this queue is logically * unbounded, attempted additions may fail due to resource exhaustion * (causing <tt>OutOfMemoryError</tt>). This class does not permit * <tt>null</tt> elements. A priority queue relying on {@linkplain * Comparable natural ordering} also does not permit insertion of * non-comparable objects (doing so results in * <tt>ClassCastException</tt>). * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link * #iterator()} is <em>not</em> guaranteed to traverse the elements of * the PriorityBlockingQueue in any particular order. If you need * ordered traversal, consider using * <tt>Arrays.sort(pq.toArray())</tt>. Also, method <tt>drainTo</tt> * can be used to <em>remove</em> some or all elements in priority * order and place them in another collection. * * <p>Operations on this class make no guarantees about the ordering * of elements with equal priority. If you need to enforce an * ordering, you can define custom classes or comparators that use a * secondary key to break ties in primary priority values. For * example, here is a class that applies first-in-first-out * tie-breaking to comparable elements. To use it, you would insert a * <tt>new FIFOEntry(anEntry)</tt> instead of a plain entry object. * * <pre> * class FIFOEntry&lt;E extends Comparable&lt;? super E&gt;&gt; * implements Comparable&lt;FIFOEntry&lt;E&gt;&gt; { * final static AtomicLong seq = new AtomicLong(); * final long seqNum; * final E entry; * public FIFOEntry(E entry) { * seqNum = seq.getAndIncrement(); * this.entry = entry; * } * public E getEntry() { return entry; } * public int compareTo(FIFOEntry&lt;E&gt; other) { * int res = entry.compareTo(other.entry); * if (res == 0 &amp;&amp; other.entry != this.entry) * res = (seqNum &lt; other.seqNum ? -1 : 1); * return res; * } * }</pre> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class PriorityBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, java.io.Serializable { private static final long serialVersionUID = 5595510919245408276L; private final PriorityQueue<E> q; private final ReentrantLock lock = new ReentrantLock(true); private final Condition notEmpty = lock.newCondition(); /** {@collect.stats} * {@description.open} * Creates a <tt>PriorityBlockingQueue</tt> with the default * initial capacity (11) that orders its elements according to * their {@linkplain Comparable natural ordering}. * {@description.close} */ public PriorityBlockingQueue() { q = new PriorityQueue<E>(); } /** {@collect.stats} * {@description.open} * Creates a <tt>PriorityBlockingQueue</tt> with the specified * initial capacity that orders its elements according to their * {@linkplain Comparable natural ordering}. * {@description.close} * * @param initialCapacity the initial capacity for this priority queue * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less * than 1 */ public PriorityBlockingQueue(int initialCapacity) { q = new PriorityQueue<E>(initialCapacity, null); } /** {@collect.stats} * {@description.open} * Creates a <tt>PriorityBlockingQueue</tt> with the specified initial * capacity that orders its elements according to the specified * comparator. * {@description.close} * * @param initialCapacity the initial capacity for this priority queue * @param comparator the comparator that will be used to order this * priority queue. If {@code null}, the {@linkplain Comparable * natural ordering} of the elements will be used. * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less * than 1 */ public PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) { q = new PriorityQueue<E>(initialCapacity, comparator); } /** {@collect.stats} * {@description.open} * Creates a <tt>PriorityBlockingQueue</tt> containing the elements * in the specified collection. If the specified collection is a * {@link SortedSet} or a {@link PriorityQueue}, this * priority queue will be ordered according to the same ordering. * Otherwise, this priority queue will be ordered according to the * {@linkplain Comparable natural ordering} of its elements. * {@description.close} * * @param c the collection whose elements are to be placed * into this priority queue * @throws ClassCastException if elements of the specified collection * cannot be compared to one another according to the priority * queue's ordering * @throws NullPointerException if the specified collection or any * of its elements are null */ public PriorityBlockingQueue(Collection<? extends E> c) { q = new PriorityQueue<E>(c); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws ClassCastException if the specified element cannot be compared * with elements currently in the priority queue according to the * priority queue's ordering * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return offer(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @throws ClassCastException if the specified element cannot be compared * with elements currently in the priority queue according to the * priority queue's ordering * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { boolean ok = q.offer(e); assert ok; notEmpty.signal(); return true; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. As the queue is * unbounded this method will never block. * {@description.close} * * @param e the element to add * @throws ClassCastException if the specified element cannot be compared * with elements currently in the priority queue according to the * priority queue's ordering * @throws NullPointerException if the specified element is null */ public void put(E e) { offer(e); // never need to block } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. As the queue is * unbounded this method will never block. * {@description.close} * * @param e the element to add * @param timeout This parameter is ignored as the method never blocks * @param unit This parameter is ignored as the method never blocks * @return <tt>true</tt> * @throws ClassCastException if the specified element cannot be compared * with elements currently in the priority queue according to the * priority queue's ordering * @throws NullPointerException if the specified element is null */ public boolean offer(E e, long timeout, TimeUnit unit) { return offer(e); // never need to block } public E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.poll(); } finally { lock.unlock(); } } public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { try { while (q.size() == 0) notEmpty.await(); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread throw ie; } E x = q.poll(); assert x != null; 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 (;;) { E x = q.poll(); if (x != null) 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 E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.peek(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the comparator used to order the elements in this queue, * or <tt>null</tt> if this queue uses the {@linkplain Comparable * natural ordering} of its elements. * {@description.close} * * @return the comparator used to order the elements in this queue, * or <tt>null</tt> if this queue uses the natural * ordering of its elements */ public Comparator<? super E> comparator() { return q.comparator(); } public int size() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.size(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Always returns <tt>Integer.MAX_VALUE</tt> because * a <tt>PriorityBlockingQueue</tt> is not capacity constrained. * {@description.close} * @return <tt>Integer.MAX_VALUE</tt> */ public int remainingCapacity() { return Integer.MAX_VALUE; } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element {@code e} such * that {@code o.equals(e)}, if this queue contains one or more such * elements. Returns {@code true} if and only if this queue contained * the specified element (or equivalently, if this queue changed as a * result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return <tt>true</tt> if this queue changed as a result of the call */ public boolean remove(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.remove(o); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns {@code true} if this queue contains the specified element. * More formally, returns {@code true} if and only if this queue contains * at least one element {@code e} such that {@code o.equals(e)}. * {@description.close} * * @param o object to be checked for containment in this queue * @return <tt>true</tt> if this queue contains the specified element */ public boolean contains(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.contains(o); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue. * The returned array elements are in no particular order. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toArray(); } finally { lock.unlock(); } } public String toString() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toString(); } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; E e; while ( (e = q.poll()) != null) { c.add(e); ++n; } return n; } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; E e; while (n < maxElements && (e = q.poll()) != null) { c.add(e); ++n; } return n; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Atomically removes all of the elements from this queue. * The queue will be empty after this call returns. * {@description.close} */ public void clear() { final ReentrantLock lock = this.lock; lock.lock(); try { q.clear(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue; the * runtime type of the returned array is that of the specified array. * The returned array elements are in no particular order. * If the queue fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toArray(a); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this queue. The * iterator does not return the elements in any particular order. * {@description.close} * {@property.open weak-consistent} * 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. * {@property.close} * * @return an iterator over the elements in this queue */ public Iterator<E> iterator() { return new Itr(toArray()); } /** {@collect.stats} * {@description.open} * Snapshot iterator that works off copy of underlying q array. * {@description.close} */ 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(); } } } /** {@collect.stats} * {@description.open} * Saves the state to a stream (that is, serializes it). This * merely wraps default serialization within lock. The * serialization strategy for items is left to underlying * Queue. Note that locking is not needed on deserialization, so * readObject is not defined, just relying on default. * {@description.close} */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { lock.lock(); try { s.defaultWriteObject(); } finally { lock.unlock(); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A task that returns a result and may throw an exception. * Implementors define a single method with no arguments called * <tt>call</tt>. * * <p>The <tt>Callable</tt> interface is similar to {@link * java.lang.Runnable}, in that both are designed for classes whose * instances are potentially executed by another thread. A * <tt>Runnable</tt>, however, does not return a result and cannot * throw a checked exception. * * <p> The {@link Executors} class contains utility methods to * convert from other common forms to <tt>Callable</tt> classes. * {@description.close} * * @see Executor * @since 1.5 * @author Doug Lea * @param <V> the result type of method <tt>call</tt> */ public interface Callable<V> { /** {@collect.stats} * {@description.open} * Computes a result, or throws an exception if unable to do so. * {@description.close} * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; /** {@collect.stats} * {@description.open} * 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. * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface Delayed extends Comparable<Delayed> { /** {@collect.stats} * {@description.open} * Returns the remaining delay associated with this object, in the * given time unit. * {@description.close} * * @param unit the time unit * @return the remaining delay; zero or negative values indicate * that the delay has already elapsed */ long getDelay(TimeUnit unit); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.*; /** {@collect.stats} * {@description.open} * 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. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ 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>(); /** {@collect.stats} * {@description.open} * Creates a new <tt>DelayQueue</tt> that is initially empty. * {@description.close} */ public DelayQueue() {} /** {@collect.stats} * {@description.open} * Creates a <tt>DelayQueue</tt> initially containing the elements of the * given collection of {@link Delayed} instances. * {@description.close} * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public DelayQueue(Collection<? extends E> c) { this.addAll(c); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this delay queue. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return offer(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this delay queue. * {@description.close} * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ 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(); } } /** {@collect.stats} * {@description.open} * Inserts the specified element into this delay queue. As the queue is * unbounded this method will never block. * {@description.close} * * @param e the element to add * @throws NullPointerException {@inheritDoc} */ public void put(E e) { offer(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this delay queue. As the queue is * unbounded this method will never block. * {@description.close} * * @param e the element to add * @param timeout This parameter is ignored as the method never blocks * @param unit This parameter is ignored as the method never blocks * @return <tt>true</tt> * @throws NullPointerException {@inheritDoc} */ public boolean offer(E e, long timeout, TimeUnit unit) { return offer(e); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, or returns <tt>null</tt> * if this queue has no elements with an expired delay. * {@description.close} * * @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(); } } /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, waiting if necessary * until an element with an expired delay is available on this queue. * {@description.close} * * @return the head of this queue * @throws InterruptedException {@inheritDoc} */ 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(); } } /** {@collect.stats} * {@description.open} * 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. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if the * specified waiting time elapses before an element with * an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ 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(); } } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of this queue, or * returns <tt>null</tt> if this queue is empty. Unlike * <tt>poll</tt>, if no expired elements are available in the queue, * this method returns the element that will expire next, * if one exists. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if this * queue is empty. */ public E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.peek(); } finally { lock.unlock(); } } public int size() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.size(); } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; for (;;) { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) break; c.add(q.poll()); ++n; } if (n > 0) available.signalAll(); return n; } finally { lock.unlock(); } } /** {@collect.stats} * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; while (n < maxElements) { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) break; c.add(q.poll()); ++n; } if (n > 0) available.signalAll(); return n; } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Atomically removes all of the elements from this delay queue. * The queue will be empty after this call returns. * Elements with an unexpired delay are not waited for; they are * simply discarded from the queue. * {@description.close} */ public void clear() { final ReentrantLock lock = this.lock; lock.lock(); try { q.clear(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Always returns <tt>Integer.MAX_VALUE</tt> because * a <tt>DelayQueue</tt> is not capacity constrained. * {@description.close} * * @return <tt>Integer.MAX_VALUE</tt> */ public int remainingCapacity() { return Integer.MAX_VALUE; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue. * The returned array elements are in no particular order. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toArray(); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue; the * runtime type of the returned array is that of the specified array. * The returned array elements are in no particular order. * If the queue fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * <tt>null</tt>. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>The following code can be used to dump a delay queue into a newly * allocated array of <tt>Delayed</tt>: * * <pre> * Delayed[] a = q.toArray(new Delayed[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toArray(a); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this * queue, if it is present, whether or not it has expired. * {@description.close} */ public boolean remove(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.remove(o); } finally { lock.unlock(); } } /** {@collect.stats} * {@description.open} * 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. * {@description.close} * {@property.open synchronized} * 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. * {@property.close} * * @return an iterator over the elements in this queue */ public Iterator<E> iterator() { return new Itr(toArray()); } /** {@collect.stats} * {@description.open} * Snapshot iterator that works off copy of underlying q array. * {@description.close} */ 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(); } } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A <tt>Future</tt> represents the result of an asynchronous * computation. Methods are provided to check if the computation is * complete, to wait for its completion, and to retrieve the result of * the computation. The result can only be retrieved using method * <tt>get</tt> when the computation has completed, blocking if * necessary until it is ready. Cancellation is performed by the * <tt>cancel</tt> method. Additional methods are provided to * determine if the task completed normally or was cancelled. Once a * computation has completed, the computation cannot be cancelled. * If you would like to use a <tt>Future</tt> for the sake * of cancellability but not provide a usable result, you can * declare types of the form <tt>Future&lt;?&gt;</tt> and * return <tt>null</tt> as a result of the underlying task. * * <p> * <b>Sample Usage</b> (Note that the following classes are all * made-up.) <p> * <pre> * interface ArchiveSearcher { String search(String target); } * class App { * ExecutorService executor = ... * ArchiveSearcher searcher = ... * void showSearch(final String target) * throws InterruptedException { * Future&lt;String&gt; future * = executor.submit(new Callable&lt;String&gt;() { * public String call() { * return searcher.search(target); * }}); * displayOtherThings(); // do other things while searching * try { * displayText(future.get()); // use future * } catch (ExecutionException ex) { cleanup(); return; } * } * } * </pre> * * The {@link FutureTask} class is an implementation of <tt>Future</tt> that * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>. * For example, the above construction with <tt>submit</tt> could be replaced by: * <pre> * FutureTask&lt;String&gt; future = * new FutureTask&lt;String&gt;(new Callable&lt;String&gt;() { * public String call() { * return searcher.search(target); * }}); * executor.execute(future); * </pre> * * <p>Memory consistency effects: Actions taken by the asynchronous computation * <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a> * actions following the corresponding {@code Future.get()} in another thread. * {@description.close} * * @see FutureTask * @see Executor * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this Future's <tt>get</tt> method */ public interface Future<V> { /** {@collect.stats} * {@description.open} * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, has already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * <p>After this method returns, subsequent calls to {@link #isDone} will * always return <tt>true</tt>. Subsequent calls to {@link #isCancelled} * will always return <tt>true</tt> if this method returned <tt>true</tt>. * {@description.close} * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise */ boolean cancel(boolean mayInterruptIfRunning); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this task was cancelled before it completed * normally. * {@description.close} * * @return <tt>true</tt> if this task was cancelled before it completed */ boolean isCancelled(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this task completed. * * Completion may be due to normal termination, an exception, or * cancellation -- in all of these cases, this method will return * <tt>true</tt>. * {@description.close} * * @return <tt>true</tt> if this task completed */ boolean isDone(); /** {@collect.stats} * {@description.open} * Waits if necessary for the computation to complete, and then * retrieves its result. * {@description.close} * * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting */ V get() throws InterruptedException, ExecutionException; /** {@collect.stats} * {@description.open} * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. * {@description.close} * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the wait timed out */ V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; /** {@collect.stats} * {@description.open} * A counting semaphore. Conceptually, a semaphore maintains a set of * permits. Each {@link #acquire} blocks if necessary until a permit is * available, and then takes it. Each {@link #release} adds a permit, * potentially releasing a blocking acquirer. * However, no actual permit objects are used; the {@code Semaphore} just * keeps a count of the number available and acts accordingly. * * <p>Semaphores are often used to restrict the number of threads than can * access some (physical or logical) resource. For example, here is * a class that uses a semaphore to control access to a pool of items: * <pre> * class Pool { * private static final int MAX_AVAILABLE = 100; * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true); * * public Object getItem() throws InterruptedException { * available.acquire(); * return getNextAvailableItem(); * } * * public void putItem(Object x) { * if (markAsUnused(x)) * available.release(); * } * * // Not a particularly efficient data structure; just for demo * * protected Object[] items = ... whatever kinds of items being managed * protected boolean[] used = new boolean[MAX_AVAILABLE]; * * protected synchronized Object getNextAvailableItem() { * for (int i = 0; i < MAX_AVAILABLE; ++i) { * if (!used[i]) { * used[i] = true; * return items[i]; * } * } * return null; // not reached * } * * protected synchronized boolean markAsUnused(Object item) { * for (int i = 0; i < MAX_AVAILABLE; ++i) { * if (item == items[i]) { * if (used[i]) { * used[i] = false; * return true; * } else * return false; * } * } * return false; * } * * } * </pre> * * <p>Before obtaining an item each thread must acquire a permit from * the semaphore, guaranteeing that an item is available for use. When * the thread has finished with the item it is returned back to the * pool and a permit is returned to the semaphore, allowing another * thread to acquire that item. * {@description.close} * {@property.open} * Note that no synchronization lock is * held when {@link #acquire} is called as that would prevent an item * from being returned to the pool. * {@property.close} * {@description.open} * The semaphore encapsulates the * synchronization needed to restrict access to the pool, separately * from any synchronization needed to maintain the consistency of the * pool itself. * * <p>A semaphore initialized to one, and which is used such that it * only has at most one permit available, can serve as a mutual * exclusion lock. This is more commonly known as a <em>binary * semaphore</em>, because it only has two states: one permit * available, or zero permits available. When used in this way, the * binary semaphore has the property (unlike many {@link Lock} * implementations), that the &quot;lock&quot; can be released by a * thread other than the owner (as semaphores have no notion of * ownership). This can be useful in some specialized contexts, such * as deadlock recovery. * * <p> The constructor for this class optionally accepts a * <em>fairness</em> parameter. When set false, this class makes no * guarantees about the order in which threads acquire permits. In * particular, <em>barging</em> is permitted, that is, a thread * invoking {@link #acquire} can be allocated a permit ahead of a * thread that has been waiting - logically the new thread places itself at * the head of the queue of waiting threads. When fairness is set true, the * semaphore guarantees that threads invoking any of the {@link * #acquire() acquire} methods are selected to obtain permits in the order in * which their invocation of those methods was processed * (first-in-first-out; FIFO). Note that FIFO ordering necessarily * applies to specific internal points of execution within these * methods. So, it is possible for one thread to invoke * {@code acquire} before another, but reach the ordering point after * the other, and similarly upon return from the method. * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not * honor the fairness setting, but will take any permits that are * available. * * <p>Generally, semaphores used to control resource access should be * initialized as fair, to ensure that no thread is starved out from * accessing a resource. When using semaphores for other kinds of * synchronization control, the throughput advantages of non-fair * ordering often outweigh fairness considerations. * * <p>This class also provides convenience methods to {@link * #acquire(int) acquire} and {@link #release(int) release} multiple * permits at a time. Beware of the increased risk of indefinite * postponement when these methods are used without fairness set true. * * <p>Memory consistency effects: Actions in a thread prior to calling * a "release" method such as {@code release()} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions following a successful "acquire" method such as {@code acquire()} * in another thread. * {@description.close} * * @since 1.5 * @author Doug Lea * */ public class Semaphore implements java.io.Serializable { private static final long serialVersionUID = -3222578661600680210L; /** {@collect.stats} * {@description.open} * All mechanics via AbstractQueuedSynchronizer subclass * {@description.close} */ private final Sync sync; /** {@collect.stats} * {@description.open} * Synchronization implementation for semaphore. Uses AQS state * to represent permits. Subclassed into fair and nonfair * versions. * {@description.close} */ abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1192457210091910933L; Sync(int permits) { setState(permits); } final int getPermits() { return getState(); } final int nonfairTryAcquireShared(int acquires) { for (;;) { int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } protected final boolean tryReleaseShared(int releases) { for (;;) { int p = getState(); if (compareAndSetState(p, p + releases)) return true; } } final void reducePermits(int reductions) { for (;;) { int current = getState(); int next = current - reductions; if (compareAndSetState(current, next)) return; } } final int drainPermits() { for (;;) { int current = getState(); if (current == 0 || compareAndSetState(current, 0)) return current; } } } /** {@collect.stats} * {@description.open} * NonFair version * {@description.close} */ final static class NonfairSync extends Sync { private static final long serialVersionUID = -2694183684443567898L; NonfairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { return nonfairTryAcquireShared(acquires); } } /** {@collect.stats} * {@description.open} * Fair version * {@description.close} */ final static class FairSync extends Sync { private static final long serialVersionUID = 2014338818796000944L; FairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { for (;;) { if (getFirstQueuedThread() != Thread.currentThread() && hasQueuedThreads()) return -1; int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } } /** {@collect.stats} * {@description.open} * Creates a {@code Semaphore} with the given number of * permits and nonfair fairness setting. * {@description.close} * * @param permits the initial number of permits available. * This value may be negative, in which case releases * must occur before any acquires will be granted. */ public Semaphore(int permits) { sync = new NonfairSync(permits); } /** {@collect.stats} * {@description.open} * Creates a {@code Semaphore} with the given number of * permits and the given fairness setting. * {@description.close} * * @param permits the initial number of permits available. * This value may be negative, in which case releases * must occur before any acquires will be granted. * @param fair {@code true} if this semaphore will guarantee * first-in first-out granting of permits under contention, * else {@code false} */ public Semaphore(int permits, boolean fair) { sync = (fair)? new FairSync(permits) : new NonfairSync(permits); } /** {@collect.stats} * {@description.open} * Acquires a permit from this semaphore, blocking until one is * available, or the thread is {@linkplain Thread#interrupt interrupted}. * * <p>Acquires a permit, if one is available and returns immediately, * reducing the number of available permits by one. * * <p>If no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * one of two things happens: * <ul> * <li>Some other thread invokes the {@link #release} method for this * semaphore and the current thread is next to be assigned a permit; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * for a permit, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * {@description.close} * * @throws InterruptedException if the current thread is interrupted */ public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** {@collect.stats} * {@description.open} * Acquires a permit from this semaphore, blocking until one is * available. * * <p>Acquires a permit, if one is available and returns immediately, * reducing the number of available permits by one. * * <p>If no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * some other thread invokes the {@link #release} method for this * semaphore and the current thread is next to be assigned a permit. * * <p>If the current thread is {@linkplain Thread#interrupt interrupted} * while waiting for a permit then it will continue to wait, but the * time at which the thread is assigned a permit may change compared to * the time it would have received the permit had no interruption * occurred. When the thread does return from this method its interrupt * status will be set. * {@description.close} */ public void acquireUninterruptibly() { sync.acquireShared(1); } /** {@collect.stats} * {@description.open} * Acquires a permit from this semaphore, only if one is available at the * time of invocation. * * <p>Acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>If no permit is available then this method will return * immediately with the value {@code false}. * * <p>Even when this semaphore has been set to use a * fair ordering policy, a call to {@code tryAcquire()} <em>will</em> * immediately acquire a permit if one is available, whether or not * other threads are currently waiting. * This &quot;barging&quot; behavior can be useful in certain * circumstances, even though it breaks fairness. If you want to honor * the fairness setting, then use * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * {@description.close} * * @return {@code true} if a permit was acquired and {@code false} * otherwise */ public boolean tryAcquire() { return sync.nonfairTryAcquireShared(1) >= 0; } /** {@collect.stats} * {@description.open} * Acquires a permit from this semaphore, if one becomes available * within the given waiting time and the current thread has not * been {@linkplain Thread#interrupt interrupted}. * * <p>Acquires a permit, if one is available and returns immediately, * with the value {@code true}, * reducing the number of available permits by one. * * <p>If no permit is available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * one of three things happens: * <ul> * <li>Some other thread invokes the {@link #release} method for this * semaphore and the current thread is next to be assigned a permit; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * </ul> * * <p>If a permit is acquired then the value {@code true} is returned. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * to acquire a permit, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. * {@description.close} * * @param timeout the maximum time to wait for a permit * @param unit the time unit of the {@code timeout} argument * @return {@code true} if a permit was acquired and {@code false} * if the waiting time elapsed before a permit was acquired * @throws InterruptedException if the current thread is interrupted */ public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Releases a permit, returning it to the semaphore. * * <p>Releases a permit, increasing the number of available permits by * one. If any threads are trying to acquire a permit, then one is * selected and given the permit that was just released. That thread * is (re)enabled for thread scheduling purposes. * {@description.close} * * {@property.open} * <p>There is no requirement that a thread that releases a permit must * have acquired that permit by calling {@link #acquire}. * Correct usage of a semaphore is established by programming convention * in the application. * {@property.close} */ public void release() { sync.releaseShared(1); } /** {@collect.stats} * {@description.open} * Acquires the given number of permits from this semaphore, * blocking until all are available, * or the thread is {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the given number of permits, if they are available, * and returns immediately, reducing the number of available permits * by the given amount. * * <p>If insufficient permits are available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * one of two things happens: * <ul> * <li>Some other thread invokes one of the {@link #release() release} * methods for this semaphore, the current thread is next to be assigned * permits and the number of available permits satisfies this request; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * for a permit, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * Any permits that were to be assigned to this thread are instead * assigned to other threads trying to acquire permits, as if * permits had been made available by a call to {@link #release()}. * {@description.close} * * @param permits the number of permits to acquire * @throws InterruptedException if the current thread is interrupted * @throws IllegalArgumentException if {@code permits} is negative */ public void acquire(int permits) throws InterruptedException { if (permits < 0) throw new IllegalArgumentException(); sync.acquireSharedInterruptibly(permits); } /** {@collect.stats} * {@description.open} * Acquires the given number of permits from this semaphore, * blocking until all are available. * * <p>Acquires the given number of permits, if they are available, * and returns immediately, reducing the number of available permits * by the given amount. * * <p>If insufficient permits are available then the current thread becomes * disabled for thread scheduling purposes and lies dormant until * some other thread invokes one of the {@link #release() release} * methods for this semaphore, the current thread is next to be assigned * permits and the number of available permits satisfies this request. * * <p>If the current thread is {@linkplain Thread#interrupt interrupted} * while waiting for permits then it will continue to wait and its * position in the queue is not affected. When the thread does return * from this method its interrupt status will be set. * {@description.close} * * @param permits the number of permits to acquire * @throws IllegalArgumentException if {@code permits} is negative * */ public void acquireUninterruptibly(int permits) { if (permits < 0) throw new IllegalArgumentException(); sync.acquireShared(permits); } /** {@collect.stats} * {@description.open} * Acquires the given number of permits from this semaphore, only * if all are available at the time of invocation. * * <p>Acquires the given number of permits, if they are available, and * returns immediately, with the value {@code true}, * reducing the number of available permits by the given amount. * * <p>If insufficient permits are available then this method will return * immediately with the value {@code false} and the number of available * permits is unchanged. * * <p>Even when this semaphore has been set to use a fair ordering * policy, a call to {@code tryAcquire} <em>will</em> * immediately acquire a permit if one is available, whether or * not other threads are currently waiting. This * &quot;barging&quot; behavior can be useful in certain * circumstances, even though it breaks fairness. If you want to * honor the fairness setting, then use {@link #tryAcquire(int, * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * {@description.close} * * @param permits the number of permits to acquire * @return {@code true} if the permits were acquired and * {@code false} otherwise * @throws IllegalArgumentException if {@code permits} is negative */ public boolean tryAcquire(int permits) { if (permits < 0) throw new IllegalArgumentException(); return sync.nonfairTryAcquireShared(permits) >= 0; } /** {@collect.stats} * {@description.open} * Acquires the given number of permits from this semaphore, if all * become available within the given waiting time and the current * thread has not been {@linkplain Thread#interrupt interrupted}. * * <p>Acquires the given number of permits, if they are available and * returns immediately, with the value {@code true}, * reducing the number of available permits by the given amount. * * <p>If insufficient permits are available then * the current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * <ul> * <li>Some other thread invokes one of the {@link #release() release} * methods for this semaphore, the current thread is next to be assigned * permits and the number of available permits satisfies this request; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * <li>The specified waiting time elapses. * </ul> * * <p>If the permits are acquired then the value {@code true} is returned. * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting * to acquire the permits, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * Any permits that were to be assigned to this thread, are instead * assigned to other threads trying to acquire permits, as if * the permits had been made available by a call to {@link #release()}. * * <p>If the specified waiting time elapses then the value {@code false} * is returned. If the time is less than or equal to zero, the method * will not wait at all. Any permits that were to be assigned to this * thread, are instead assigned to other threads trying to acquire * permits, as if the permits had been made available by a call to * {@link #release()}. * {@description.close} * * @param permits the number of permits to acquire * @param timeout the maximum time to wait for the permits * @param unit the time unit of the {@code timeout} argument * @return {@code true} if all permits were acquired and {@code false} * if the waiting time elapsed before all permits were acquired * @throws InterruptedException if the current thread is interrupted * @throws IllegalArgumentException if {@code permits} is negative */ public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { if (permits < 0) throw new IllegalArgumentException(); return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout)); } /** {@collect.stats} * {@description.open} * Releases the given number of permits, returning them to the semaphore. * * <p>Releases the given number of permits, increasing the number of * available permits by that amount. * If any threads are trying to acquire permits, then one * is selected and given the permits that were just released. * If the number of available permits satisfies that thread's request * then that thread is (re)enabled for thread scheduling purposes; * otherwise the thread will wait until sufficient permits are available. * If there are still permits available * after this thread's request has been satisfied, then those permits * are assigned in turn to other threads trying to acquire permits. * {@description.close} * * {@property.open} * <p>There is no requirement that a thread that releases a permit must * have acquired that permit by calling {@link Semaphore#acquire acquire}. * Correct usage of a semaphore is established by programming convention * in the application. * {@property.close} * * @param permits the number of permits to release * @throws IllegalArgumentException if {@code permits} is negative */ public void release(int permits) { if (permits < 0) throw new IllegalArgumentException(); sync.releaseShared(permits); } /** {@collect.stats} * {@description.open} * Returns the current number of permits available in this semaphore. * * <p>This method is typically used for debugging and testing purposes. * {@description.close} * * @return the number of permits available in this semaphore */ public int availablePermits() { return sync.getPermits(); } /** {@collect.stats} * {@description.open} * Acquires and returns all permits that are immediately available. * {@description.close} * * @return the number of permits acquired */ public int drainPermits() { return sync.drainPermits(); } /** {@collect.stats} * {@description.open} * Shrinks the number of available permits by the indicated * reduction. This method can be useful in subclasses that use * semaphores to track resources that become unavailable. This * method differs from {@code acquire} in that it does not block * waiting for permits to become available. * {@description.close} * * @param reduction the number of permits to remove * @throws IllegalArgumentException if {@code reduction} is negative */ protected void reducePermits(int reduction) { if (reduction < 0) throw new IllegalArgumentException(); sync.reducePermits(reduction); } /** {@collect.stats} * {@description.open} * Returns {@code true} if this semaphore has fairness set true. * {@description.close} * * @return {@code true} if this semaphore has fairness set true */ public boolean isFair() { return sync instanceof FairSync; } /** {@collect.stats} * {@description.open} * Queries whether any threads are waiting to acquire. Note that * because cancellations may occur at any time, a {@code true} * return does not guarantee that any other thread will ever * acquire. This method is designed primarily for use in * monitoring of the system state. * {@description.close} * * @return {@code true} if there may be other threads waiting to * acquire the lock */ public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** {@collect.stats} * {@description.open} * Returns an estimate of the number of threads waiting to acquire. * The value is only an estimate because the number of threads may * change dynamically while this method traverses internal data * structures. This method is designed for use in monitoring of the * system state, not for synchronization control. * {@description.close} * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** {@collect.stats} * {@description.open} * Returns a collection containing threads that may be waiting to acquire. * Because the actual set of threads may change dynamically while * constructing this result, the returned collection is only a best-effort * estimate. The elements of the returned collection are in no particular * order. This method is designed to facilitate construction of * subclasses that provide more extensive monitoring facilities. * {@description.close} * * @return the collection of threads */ protected Collection<Thread> getQueuedThreads() { return sync.getQueuedThreads(); } /** {@collect.stats} * {@description.open} * Returns a string identifying this semaphore, as well as its state. * The state, in brackets, includes the String {@code "Permits ="} * followed by the number of permits. * {@description.close} * * @return a string identifying this semaphore, as well as its state */ public String toString() { return super.toString() + "[Permits = " + sync.getPermits() + "]"; } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; /** {@collect.stats} * {@description.open} * A {@link Deque} that additionally supports blocking operations that wait * for the deque to become non-empty when retrieving an element, and wait for * space to become available in the deque when storing an element. * * <p><tt>BlockingDeque</tt> methods come in four forms, with different ways * of handling operations that cannot be satisfied immediately, but may be * satisfied at some point in the future: * one throws an exception, the second returns a special value (either * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third * blocks the current thread indefinitely until the operation can succeed, * and the fourth blocks for only a given maximum time limit before giving * up. These methods are summarized in the following table: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td ALIGN=CENTER COLSPAN = 5> <b>First Element (Head)</b></td> * </tr> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * <td ALIGN=CENTER><em>Blocks</em></td> * <td ALIGN=CENTER><em>Times out</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link #addFirst addFirst(e)}</td> * <td>{@link #offerFirst(Object) offerFirst(e)}</td> * <td>{@link #putFirst putFirst(e)}</td> * <td>{@link #offerFirst(Object, long, TimeUnit) offerFirst(e, time, unit)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link #removeFirst removeFirst()}</td> * <td>{@link #pollFirst pollFirst()}</td> * <td>{@link #takeFirst takeFirst()}</td> * <td>{@link #pollFirst(long, TimeUnit) pollFirst(time, unit)}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link #getFirst getFirst()}</td> * <td>{@link #peekFirst peekFirst()}</td> * <td><em>not applicable</em></td> * <td><em>not applicable</em></td> * </tr> * <tr> * <td ALIGN=CENTER COLSPAN = 5> <b>Last Element (Tail)</b></td> * </tr> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * <td ALIGN=CENTER><em>Blocks</em></td> * <td ALIGN=CENTER><em>Times out</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link #addLast addLast(e)}</td> * <td>{@link #offerLast(Object) offerLast(e)}</td> * <td>{@link #putLast putLast(e)}</td> * <td>{@link #offerLast(Object, long, TimeUnit) offerLast(e, time, unit)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link #removeLast() removeLast()}</td> * <td>{@link #pollLast() pollLast()}</td> * <td>{@link #takeLast takeLast()}</td> * <td>{@link #pollLast(long, TimeUnit) pollLast(time, unit)}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link #getLast getLast()}</td> * <td>{@link #peekLast peekLast()}</td> * <td><em>not applicable</em></td> * <td><em>not applicable</em></td> * </tr> * </table> * * <p>Like any {@link BlockingQueue}, a <tt>BlockingDeque</tt> is thread safe, * does not permit null elements, and may (or may not) be * capacity-constrained. * * <p>A <tt>BlockingDeque</tt> implementation may be used directly as a FIFO * <tt>BlockingQueue</tt>. The methods inherited from the * <tt>BlockingQueue</tt> interface are precisely equivalent to * <tt>BlockingDeque</tt> methods as indicated in the following table: * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td ALIGN=CENTER> <b><tt>BlockingQueue</tt> Method</b></td> * <td ALIGN=CENTER> <b>Equivalent <tt>BlockingDeque</tt> Method</b></td> * </tr> * <tr> * <td ALIGN=CENTER COLSPAN = 2> <b>Insert</b></td> * </tr> * <tr> * <td>{@link #add(Object) add(e)}</td> * <td>{@link #addLast(Object) addLast(e)}</td> * </tr> * <tr> * <td>{@link #offer(Object) offer(e)}</td> * <td>{@link #offerLast(Object) offerLast(e)}</td> * </tr> * <tr> * <td>{@link #put(Object) put(e)}</td> * <td>{@link #putLast(Object) putLast(e)}</td> * </tr> * <tr> * <td>{@link #offer(Object, long, TimeUnit) offer(e, time, unit)}</td> * <td>{@link #offerLast(Object, long, TimeUnit) offerLast(e, time, unit)}</td> * </tr> * <tr> * <td ALIGN=CENTER COLSPAN = 2> <b>Remove</b></td> * </tr> * <tr> * <td>{@link #remove() remove()}</td> * <td>{@link #removeFirst() removeFirst()}</td> * </tr> * <tr> * <td>{@link #poll() poll()}</td> * <td>{@link #pollFirst() pollFirst()}</td> * </tr> * <tr> * <td>{@link #take() take()}</td> * <td>{@link #takeFirst() takeFirst()}</td> * </tr> * <tr> * <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td> * <td>{@link #pollFirst(long, TimeUnit) pollFirst(time, unit)}</td> * </tr> * <tr> * <td ALIGN=CENTER COLSPAN = 2> <b>Examine</b></td> * </tr> * <tr> * <td>{@link #element() element()}</td> * <td>{@link #getFirst() getFirst()}</td> * </tr> * <tr> * <td>{@link #peek() peek()}</td> * <td>{@link #peekFirst() peekFirst()}</td> * </tr> * </table> * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code BlockingDeque} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code BlockingDeque} in another thread. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.6 * @author Doug Lea * @param <E> the type of elements held in this collection */ public interface BlockingDeque<E> extends BlockingQueue<E>, Deque<E> { /* * We have "diamond" multiple interface inheritance here, and that * introduces ambiguities. Methods might end up with different * specs depending on the branch chosen by javadoc. Thus a lot of * methods specs here are copied from superinterfaces. */ /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions, * throwing an <tt>IllegalStateException</tt> if no space is currently * available. When using a capacity-restricted deque, it is generally * preferable to use {@link #offerFirst(Object) offerFirst}. * {@description.close} * * @param e the element to add * @throws IllegalStateException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException {@inheritDoc} */ void addFirst(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions, * throwing an <tt>IllegalStateException</tt> if no space is currently * available. When using a capacity-restricted deque, it is generally * preferable to use {@link #offerLast(Object) offerLast}. * {@description.close} * * @param e the element to add * @throws IllegalStateException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException {@inheritDoc} */ void addLast(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions, * returning <tt>true</tt> upon success and <tt>false</tt> if no space is * currently available. * When using a capacity-restricted deque, this method is generally * preferable to the {@link #addFirst(Object) addFirst} method, which can * fail to insert an element only by throwing an exception. * {@description.close} * * @param e the element to add * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException {@inheritDoc} */ boolean offerFirst(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions, * returning <tt>true</tt> upon success and <tt>false</tt> if no space is * currently available. * When using a capacity-restricted deque, this method is generally * preferable to the {@link #addLast(Object) addLast} method, which can * fail to insert an element only by throwing an exception. * {@description.close} * * @param e the element to add * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException {@inheritDoc} */ boolean offerLast(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque, * waiting if necessary for space to become available. * {@description.close} * * @param e the element to add * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void putFirst(E e) throws InterruptedException; /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque, * waiting if necessary for space to become available. * {@description.close} * * @param e the element to add * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void putLast(E e) throws InterruptedException; /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this deque, * waiting up to the specified wait time if necessary for space to * become available. * {@description.close} * * @param e the element to add * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return <tt>true</tt> if successful, or <tt>false</tt> if * the specified waiting time elapses before space is available * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this deque, * waiting up to the specified wait time if necessary for space to * become available. * {@description.close} * * @param e the element to add * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return <tt>true</tt> if successful, or <tt>false</tt> if * the specified waiting time elapses before space is available * @throws InterruptedException if interrupted while waiting * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the first element of this deque, waiting * if necessary until an element becomes available. * {@description.close} * * @return the head of this deque * @throws InterruptedException if interrupted while waiting */ E takeFirst() throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the last element of this deque, waiting * if necessary until an element becomes available. * {@description.close} * * @return the tail of this deque * @throws InterruptedException if interrupted while waiting */ E takeLast() throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the first element of this deque, waiting * up to the specified wait time if necessary for an element to * become available. * {@description.close} * * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return the head of this deque, or <tt>null</tt> if the specified * waiting time elapses before an element is available * @throws InterruptedException if interrupted while waiting */ E pollFirst(long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the last element of this deque, waiting * up to the specified wait time if necessary for an element to * become available. * {@description.close} * * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return the tail of this deque, or <tt>null</tt> if the specified * waiting time elapses before an element is available * @throws InterruptedException if interrupted while waiting */ E pollLast(long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null (optional) */ boolean removeFirstOccurrence(Object o); /** {@collect.stats} * {@description.open} * Removes the last occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the last element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null (optional) */ boolean removeLastOccurrence(Object o); // *** BlockingQueue methods *** /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an * <tt>IllegalStateException</tt> if no space is currently available. * When using a capacity-restricted deque, it is generally preferable to * use {@link #offer(Object) offer}. * * <p>This method is equivalent to {@link #addLast(Object) addLast}. * {@description.close} * * @param e the element to add * @throws IllegalStateException {@inheritDoc} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean add(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and <tt>false</tt> if no space is currently * available. When using a capacity-restricted deque, this method is * generally preferable to the {@link #add} method, which can fail to * insert an element only by throwing an exception. * * <p>This method is equivalent to {@link #offerLast(Object) offerLast}. * {@description.close} * * @param e the element to add * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offer(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque), waiting if necessary for * space to become available. * * <p>This method is equivalent to {@link #putLast(Object) putLast}. * {@description.close} * * @param e the element to add * @throws InterruptedException {@inheritDoc} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ void put(E e) throws InterruptedException; /** {@collect.stats} * {@description.open} * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque), waiting up to the * specified wait time if necessary for space to become available. * * <p>This method is equivalent to * {@link #offerLast(Object,long,TimeUnit) offerLast}. * {@description.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this deque, else * <tt>false</tt> * @throws InterruptedException {@inheritDoc} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */ boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque). * This method differs from {@link #poll poll} only in that it * throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst() removeFirst}. * {@description.close} * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ E remove(); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst()}. * {@description.close} * * @return the head of this deque, or <tt>null</tt> if this deque is empty */ E poll(); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), waiting if * necessary until an element becomes available. * * <p>This method is equivalent to {@link #takeFirst() takeFirst}. * {@description.close} * * @return the head of this deque * @throws InterruptedException if interrupted while waiting */ E take() throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), waiting up to the * specified wait time if necessary for an element to become available. * * <p>This method is equivalent to * {@link #pollFirst(long,TimeUnit) pollFirst}. * {@description.close} * * @return the head of this deque, or <tt>null</tt> if the * specified waiting time elapses before an element is available * @throws InterruptedException if interrupted while waiting */ E poll(long timeout, TimeUnit unit) throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque). * This method differs from {@link #peek peek} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst() getFirst}. * {@description.close} * * @return the head of this deque * @throws NoSuchElementException if this deque is empty */ E element(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque), or * returns <tt>null</tt> if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst() peekFirst}. * {@description.close} * * @return the head of this deque, or <tt>null</tt> if this deque is empty */ E peek(); /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element <tt>e</tt> such that * <tt>o.equals(e)</tt> (if such an element exists). * Returns <tt>true</tt> if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}. * {@description.close} * * @param o element to be removed from this deque, if present * @return <tt>true</tt> if this deque changed as a result of the call * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null (optional) */ boolean remove(Object o); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this deque contains the specified element. * More formally, returns <tt>true</tt> if and only if this deque contains * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>. * {@description.close} * * @param o object to be checked for containment in this deque * @return <tt>true</tt> if this deque contains the specified element * @throws ClassCastException if the class of the specified element * is incompatible with this deque (optional) * @throws NullPointerException if the specified element is null (optional) */ public boolean contains(Object o); /** {@collect.stats} * {@description.open} * Returns the number of elements in this deque. * {@description.close} * * @return the number of elements in this deque */ public int size(); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * {@description.close} * * @return an iterator over the elements in this deque in proper sequence */ Iterator<E> iterator(); // *** Stack methods *** /** {@collect.stats} * {@description.open} * Pushes an element onto the stack represented by this deque. In other * words, inserts the element at the front of this deque unless it would * violate capacity restrictions. * * <p>This method is equivalent to {@link #addFirst(Object) addFirst}. * {@description.close} * * @throws IllegalStateException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * @throws IllegalArgumentException {@inheritDoc} */ void push(E e); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.atomic.*; import java.util.*; /** {@collect.stats} * {@description.open} * A {@link ThreadPoolExecutor} that can additionally schedule * commands to run after a given delay, or to execute * periodically. This class is preferable to {@link java.util.Timer} * when multiple worker threads are needed, or when the additional * flexibility or capabilities of {@link ThreadPoolExecutor} (which * this class extends) are required. * * <p> Delayed tasks execute no sooner than they are enabled, but * without any real-time guarantees about when, after they are * enabled, they will commence. Tasks scheduled for exactly the same * execution time are enabled in first-in-first-out (FIFO) order of * submission. * * <p>While this class inherits from {@link ThreadPoolExecutor}, a few * of the inherited tuning methods are not useful for it. In * particular, because it acts as a fixed-sized pool using * {@code corePoolSize} threads and an unbounded queue, adjustments * to {@code maximumPoolSize} have no useful effect. Additionally, it * is almost never a good idea to set {@code corePoolSize} to zero or * use {@code allowCoreThreadTimeOut} because this may leave the pool * without threads to handle tasks once they become eligible to run. * * <p><b>Extension notes:</b> This class overrides the * {@link ThreadPoolExecutor#execute execute} and * {@link AbstractExecutorService#submit(Runnable) submit} * methods to generate internal {@link ScheduledFuture} objects to * control per-task delays and scheduling. To preserve * functionality, any further overrides of these methods in * subclasses must invoke superclass versions, which effectively * disables additional task customization. However, this class * provides alternative protected extension method * {@code decorateTask} (one version each for {@code Runnable} and * {@code Callable}) that can be used to customize the concrete task * types used to execute commands entered via {@code execute}, * {@code submit}, {@code schedule}, {@code scheduleAtFixedRate}, * and {@code scheduleWithFixedDelay}. By default, a * {@code ScheduledThreadPoolExecutor} uses a task type extending * {@link FutureTask}. However, this may be modified or replaced using * subclasses of the form: * * <pre> {@code * public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor { * * static class CustomTask<V> implements RunnableScheduledFuture<V> { ... } * * protected <V> RunnableScheduledFuture<V> decorateTask( * Runnable r, RunnableScheduledFuture<V> task) { * return new CustomTask<V>(r, task); * } * * protected <V> RunnableScheduledFuture<V> decorateTask( * Callable<V> c, RunnableScheduledFuture<V> task) { * return new CustomTask<V>(c, task); * } * // ... add constructors, etc. * }}</pre> * {@description.close} * * @since 1.5 * @author Doug Lea */ public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService { /* * This class specializes ThreadPoolExecutor implementation by * * 1. Using a custom task type, ScheduledFutureTask for * tasks, even those that don't require scheduling (i.e., * those submitted using ExecutorService execute, not * ScheduledExecutorService methods) which are treated as * delayed tasks with a delay of zero. * * 2. Using a custom queue (DelayedWorkQueue) based on an * unbounded DelayQueue. The lack of capacity constraint and * the fact that corePoolSize and maximumPoolSize are * effectively identical simplifies some execution mechanics * (see delayedExecute) compared to ThreadPoolExecutor * version. * * The DelayedWorkQueue class is defined below for the sake of * ensuring that all elements are instances of * RunnableScheduledFuture. Since DelayQueue otherwise * requires type be Delayed, but not necessarily Runnable, and * the workQueue requires the opposite, we need to explicitly * define a class that requires both to ensure that users don't * add objects that aren't RunnableScheduledFutures via * getQueue().add() etc. * * 3. Supporting optional run-after-shutdown parameters, which * leads to overrides of shutdown methods to remove and cancel * tasks that should NOT be run after shutdown, as well as * different recheck logic when task (re)submission overlaps * with a shutdown. * * 4. Task decoration methods to allow interception and * instrumentation, which are needed because subclasses cannot * otherwise override submit methods to get this effect. These * don't have any impact on pool control logic though. */ /** {@collect.stats} * {@description.open} * False if should cancel/suppress periodic tasks on shutdown. * {@description.close} */ private volatile boolean continueExistingPeriodicTasksAfterShutdown; /** {@collect.stats} * {@description.open} * False if should cancel non-periodic tasks on shutdown. * {@description.close} */ private volatile boolean executeExistingDelayedTasksAfterShutdown = true; /** {@collect.stats} * {@description.open} * Sequence number to break scheduling ties, and in turn to * guarantee FIFO order among tied entries. * {@description.close} */ private static final AtomicLong sequencer = new AtomicLong(0); /** {@collect.stats} * {@description.open} * Returns current nanosecond time. * {@description.close} */ final long now() { return System.nanoTime(); } private class ScheduledFutureTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V> { /** {@collect.stats} * {@description.open} * Sequence number to break ties FIFO * {@description.close} */ private final long sequenceNumber; /** {@collect.stats} * {@description.open} * The time the task is enabled to execute in nanoTime units * {@description.close} */ private long time; /** {@collect.stats} * {@description.open} * Period in nanoseconds for repeating tasks. A positive * value indicates fixed-rate execution. A negative value * indicates fixed-delay execution. A value of 0 indicates a * non-repeating task. * {@description.close} */ private final long period; /** {@collect.stats} * {@description.open} * The actual task to be re-enqueued by reExecutePeriodic * {@description.close} */ RunnableScheduledFuture<V> outerTask = this; /** {@collect.stats} * {@description.open} * Creates a one-shot action with given nanoTime-based trigger time. * {@description.close} */ ScheduledFutureTask(Runnable r, V result, long ns) { super(r, result); this.time = ns; this.period = 0; this.sequenceNumber = sequencer.getAndIncrement(); } /** {@collect.stats} * {@description.open} * Creates a periodic action with given nano time and period. * {@description.close} */ ScheduledFutureTask(Runnable r, V result, long ns, long period) { super(r, result); this.time = ns; this.period = period; this.sequenceNumber = sequencer.getAndIncrement(); } /** {@collect.stats} * {@description.open} * Creates a one-shot action with given nanoTime-based trigger. * {@description.close} */ ScheduledFutureTask(Callable<V> callable, long ns) { super(callable); this.time = ns; this.period = 0; this.sequenceNumber = sequencer.getAndIncrement(); } public long getDelay(TimeUnit unit) { long d = unit.convert(time - now(), TimeUnit.NANOSECONDS); return d; } public int compareTo(Delayed other) { if (other == this) // compare zero ONLY if same object return 0; if (other instanceof ScheduledFutureTask) { ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other; long diff = time - x.time; if (diff < 0) return -1; else if (diff > 0) return 1; else if (sequenceNumber < x.sequenceNumber) return -1; else return 1; } long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS)); return (d == 0) ? 0 : ((d < 0) ? -1 : 1); } /** {@collect.stats} * {@description.open} * Returns true if this is a periodic (not a one-shot) action. * {@description.close} * * @return true if periodic */ public boolean isPeriodic() { return period != 0; } /** {@collect.stats} * {@description.open} * Sets the next time to run for a periodic task. * {@description.close} */ private void setNextRunTime() { long p = period; if (p > 0) time += p; else time = now() - p; } /** {@collect.stats} * {@description.open} * Overrides FutureTask version so as to reset/requeue if periodic. * {@description.close} */ public void run() { boolean periodic = isPeriodic(); if (!canRunInCurrentRunState(periodic)) cancel(false); else if (!periodic) ScheduledFutureTask.super.run(); else if (ScheduledFutureTask.super.runAndReset()) { setNextRunTime(); reExecutePeriodic(outerTask); } } } /** {@collect.stats} * {@description.open} * Returns true if can run a task given current run state * and run-after-shutdown parameters. * {@description.close} * * @param periodic true if this task periodic, false if delayed */ boolean canRunInCurrentRunState(boolean periodic) { return isRunningOrShutdown(periodic ? continueExistingPeriodicTasksAfterShutdown : executeExistingDelayedTasksAfterShutdown); } /** {@collect.stats} * {@description.open} * Main execution method for delayed or periodic tasks. If pool * is shut down, rejects the task. Otherwise adds task to queue * and starts a thread, if necessary, to run it. (We cannot * prestart the thread to run the task because the task (probably) * shouldn't be run yet,) If the pool is shut down while the task * is being added, cancel and remove it if required by state and * run-after-shutdown parameters. * {@description.close} * * @param task the task */ private void delayedExecute(RunnableScheduledFuture<?> task) { if (isShutdown()) reject(task); else { super.getQueue().add(task); if (isShutdown() && !canRunInCurrentRunState(task.isPeriodic()) && remove(task)) task.cancel(false); else prestartCoreThread(); } } /** {@collect.stats} * {@description.open} * Requeues a periodic task unless current run state precludes it. * Same idea as delayedExecute except drops task rather than rejecting. * {@description.close} * * @param task the task */ void reExecutePeriodic(RunnableScheduledFuture<?> task) { if (canRunInCurrentRunState(true)) { super.getQueue().add(task); if (!canRunInCurrentRunState(true) && remove(task)) task.cancel(false); else prestartCoreThread(); } } /** {@collect.stats} * {@description.open} * Cancels and clears the queue of all tasks that should not be run * due to shutdown policy. Invoked within super.shutdown. * {@description.close} */ @Override void onShutdown() { BlockingQueue<Runnable> q = super.getQueue(); boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy(); boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy(); if (!keepDelayed && !keepPeriodic) q.clear(); else { // Traverse snapshot to avoid iterator exceptions for (Object e : q.toArray()) { if (e instanceof RunnableScheduledFuture) { RunnableScheduledFuture<?> t = (RunnableScheduledFuture<?>)e; if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) || t.isCancelled()) { // also remove if already cancelled if (q.remove(t)) t.cancel(false); } } } } tryTerminate(); } /** {@collect.stats} * {@description.open} * Modifies or replaces the task used to execute a runnable. * This method can be used to override the concrete * class used for managing internal tasks. * The default implementation simply returns the given task. * {@description.close} * * @param runnable the submitted Runnable * @param task the task created to execute the runnable * @return a task that can execute the runnable * @since 1.6 */ protected <V> RunnableScheduledFuture<V> decorateTask( Runnable runnable, RunnableScheduledFuture<V> task) { return task; } /** {@collect.stats} * {@description.open} * Modifies or replaces the task used to execute a callable. * This method can be used to override the concrete * class used for managing internal tasks. * The default implementation simply returns the given task. * {@description.close} * * @param callable the submitted Callable * @param task the task created to execute the callable * @return a task that can execute the callable * @since 1.6 */ protected <V> RunnableScheduledFuture<V> decorateTask( Callable<V> callable, RunnableScheduledFuture<V> task) { return task; } /** {@collect.stats} * {@description.open} * Creates a new {@code ScheduledThreadPoolExecutor} with the * given core pool size. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @throws IllegalArgumentException if {@code corePoolSize < 0} */ public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue()); } /** {@collect.stats} * {@description.open} * Creates a new {@code ScheduledThreadPoolExecutor} with the * given initial parameters. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param threadFactory the factory to use when the executor * creates a new thread * @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws NullPointerException if {@code threadFactory} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), threadFactory); } /** {@collect.stats} * {@description.open} * Creates a new ScheduledThreadPoolExecutor with the given * initial parameters. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws NullPointerException if {@code handler} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), handler); } /** {@collect.stats} * {@description.open} * Creates a new ScheduledThreadPoolExecutor with the given * initial parameters. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param threadFactory the factory to use when the executor * creates a new thread * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws NullPointerException if {@code threadFactory} or * {@code handler} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), threadFactory, handler); } public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (delay < 0) delay = 0; long triggerTime = now() + unit.toNanos(delay); RunnableScheduledFuture<?> t = decorateTask(command, new ScheduledFutureTask<Void>(command, null, triggerTime)); delayedExecute(t); return t; } public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { if (callable == null || unit == null) throw new NullPointerException(); if (delay < 0) delay = 0; long triggerTime = now() + unit.toNanos(delay); RunnableScheduledFuture<V> t = decorateTask(callable, new ScheduledFutureTask<V>(callable, triggerTime)); delayedExecute(t); return t; } public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (period <= 0) throw new IllegalArgumentException(); if (initialDelay < 0) initialDelay = 0; long triggerTime = now() + unit.toNanos(initialDelay); ScheduledFutureTask<Void> sft = new ScheduledFutureTask<Void>(command, null, triggerTime, unit.toNanos(period)); RunnableScheduledFuture<Void> t = decorateTask(command, sft); sft.outerTask = t; delayedExecute(t); return t; } public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (delay <= 0) throw new IllegalArgumentException(); if (initialDelay < 0) initialDelay = 0; long triggerTime = now() + unit.toNanos(initialDelay); ScheduledFutureTask<Void> sft = new ScheduledFutureTask<Void>(command, null, triggerTime, unit.toNanos(-delay)); RunnableScheduledFuture<Void> t = decorateTask(command, sft); sft.outerTask = t; delayedExecute(t); return t; } /** {@collect.stats} * {@description.open} * Executes {@code command} with zero required delay. * This has effect equivalent to * {@link #schedule(Runnable,long,TimeUnit) schedule(command, 0, anyUnit)}. * Note that inspections of the queue and of the list returned by * {@code shutdownNow} will access the zero-delayed * {@link ScheduledFuture}, not the {@code command} itself. * * <p>A consequence of the use of {@code ScheduledFuture} objects is * that {@link ThreadPoolExecutor#afterExecute afterExecute} is always * called with a null second {@code Throwable} argument, even if the * {@code command} terminated abruptly. Instead, the {@code Throwable} * thrown by such a task can be obtained via {@link Future#get}. * {@description.close} * * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution because the * executor has been shut down * @throws NullPointerException {@inheritDoc} */ public void execute(Runnable command) { schedule(command, 0, TimeUnit.NANOSECONDS); } // Override AbstractExecutorService methods public Future<?> submit(Runnable task) { return schedule(task, 0, TimeUnit.NANOSECONDS); } public <T> Future<T> submit(Runnable task, T result) { return schedule(Executors.callable(task, result), 0, TimeUnit.NANOSECONDS); } public <T> Future<T> submit(Callable<T> task) { return schedule(task, 0, TimeUnit.NANOSECONDS); } /** {@collect.stats} * {@description.open} * Sets the policy on whether to continue executing existing * periodic tasks even when this executor has been {@code shutdown}. * In this case, these tasks will only terminate upon * {@code shutdownNow} or after setting the policy to * {@code false} when already shutdown. * This value is by default {@code false}. * {@description.close} * * @param value if {@code true}, continue after shutdown, else don't. * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy */ public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) { continueExistingPeriodicTasksAfterShutdown = value; if (!value && isShutdown()) onShutdown(); } /** {@collect.stats} * {@description.open} * Gets the policy on whether to continue executing existing * periodic tasks even when this executor has been {@code shutdown}. * In this case, these tasks will only terminate upon * {@code shutdownNow} or after setting the policy to * {@code false} when already shutdown. * This value is by default {@code false}. * {@description.close} * * @return {@code true} if will continue after shutdown * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy */ public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() { return continueExistingPeriodicTasksAfterShutdown; } /** {@collect.stats} * {@description.open} * Sets the policy on whether to execute existing delayed * tasks even when this executor has been {@code shutdown}. * In this case, these tasks will only terminate upon * {@code shutdownNow}, or after setting the policy to * {@code false} when already shutdown. * This value is by default {@code true}. * {@description.close} * * @param value if {@code true}, execute after shutdown, else don't. * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy */ public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) { executeExistingDelayedTasksAfterShutdown = value; if (!value && isShutdown()) onShutdown(); } /** {@collect.stats} * {@description.open} * Gets the policy on whether to execute existing delayed * tasks even when this executor has been {@code shutdown}. * In this case, these tasks will only terminate upon * {@code shutdownNow}, or after setting the policy to * {@code false} when already shutdown. * This value is by default {@code true}. * {@description.close} * * @return {@code true} if will execute after shutdown * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy */ public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() { return executeExistingDelayedTasksAfterShutdown; } /** {@collect.stats} * {@description.open} * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. If the * {@code ExecuteExistingDelayedTasksAfterShutdownPolicy} has * been set {@code false}, existing delayed tasks whose delays * have not yet elapsed are cancelled. And unless the * {@code ContinueExistingPeriodicTasksAfterShutdownPolicy} has * been set {@code true}, future executions of existing periodic * tasks will be cancelled. * {@description.close} */ public void shutdown() { super.shutdown(); } /** {@collect.stats} * {@description.open} * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks * that were awaiting execution. * * <p>There are no guarantees beyond best-effort attempts to stop * processing actively executing tasks. This implementation * cancels tasks via {@link Thread#interrupt}, so any task that * fails to respond to interrupts may never terminate. * {@description.close} * * @return list of tasks that never commenced execution. * Each element of this list is a {@link ScheduledFuture}, * including those tasks submitted using {@code execute}, * which are for scheduling purposes used as the basis of a * zero-delay {@code ScheduledFuture}. * @throws SecurityException {@inheritDoc} */ public List<Runnable> shutdownNow() { return super.shutdownNow(); } /** {@collect.stats} * {@description.open} * Returns the task queue used by this executor. Each element of * this queue is a {@link ScheduledFuture}, including those * tasks submitted using {@code execute} which are for scheduling * purposes used as the basis of a zero-delay * {@code ScheduledFuture}. Iteration over this queue is * <em>not</em> guaranteed to traverse tasks in the order in * which they will execute. * {@description.close} * * @return the task queue */ public BlockingQueue<Runnable> getQueue() { return super.getQueue(); } /** {@collect.stats} * {@description.open} * An annoying wrapper class to convince javac to use a * DelayQueue<RunnableScheduledFuture> as a BlockingQueue<Runnable> * {@description.close} */ private static class DelayedWorkQueue extends AbstractCollection<Runnable> implements BlockingQueue<Runnable> { private final DelayQueue<RunnableScheduledFuture> dq = new DelayQueue<RunnableScheduledFuture>(); public Runnable poll() { return dq.poll(); } public Runnable peek() { return dq.peek(); } public Runnable take() throws InterruptedException { return dq.take(); } public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException { return dq.poll(timeout, unit); } public boolean add(Runnable x) { return dq.add((RunnableScheduledFuture)x); } public boolean offer(Runnable x) { return dq.offer((RunnableScheduledFuture)x); } public void put(Runnable x) { dq.put((RunnableScheduledFuture)x); } public boolean offer(Runnable x, long timeout, TimeUnit unit) { return dq.offer((RunnableScheduledFuture)x, timeout, unit); } public Runnable remove() { return dq.remove(); } public Runnable element() { return dq.element(); } public void clear() { dq.clear(); } public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); } public int drainTo(Collection<? super Runnable> c, int maxElements) { return dq.drainTo(c, maxElements); } public int remainingCapacity() { return dq.remainingCapacity(); } public boolean remove(Object x) { return dq.remove(x); } public boolean contains(Object x) { return dq.contains(x); } public int size() { return dq.size(); } public boolean isEmpty() { return dq.isEmpty(); } public Object[] toArray() { return dq.toArray(); } public <T> T[] toArray(T[] array) { return dq.toArray(array); } public Iterator<Runnable> iterator() { return new Iterator<Runnable>() { private Iterator<RunnableScheduledFuture> it = dq.iterator(); public boolean hasNext() { return it.hasNext(); } public Runnable next() { return it.next(); } public void remove() { it.remove(); } }; } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.concurrent.atomic.*; import java.util.*; /** {@collect.stats} * {@description.open} * An {@link ExecutorService} that executes each submitted task using * one of possibly several pooled threads, normally configured * using {@link Executors} factory methods. * * <p>Thread pools address two different problems: they usually * provide improved performance when executing large numbers of * asynchronous tasks, due to reduced per-task invocation overhead, * and they provide a means of bounding and managing the resources, * including threads, consumed when executing a collection of tasks. * Each {@code ThreadPoolExecutor} also maintains some basic * statistics, such as the number of completed tasks. * * <p>To be useful across a wide range of contexts, this class * provides many adjustable parameters and extensibility * hooks. However, programmers are urged to use the more convenient * {@link Executors} factory methods {@link * Executors#newCachedThreadPool} (unbounded thread pool, with * automatic thread reclamation), {@link Executors#newFixedThreadPool} * (fixed size thread pool) and {@link * Executors#newSingleThreadExecutor} (single background thread), that * preconfigure settings for the most common usage * scenarios. Otherwise, use the following guide when manually * configuring and tuning this class: * * <dl> * * <dt>Core and maximum pool sizes</dt> * * <dd>A {@code ThreadPoolExecutor} will automatically adjust the * pool size (see {@link #getPoolSize}) * according to the bounds set by * corePoolSize (see {@link #getCorePoolSize}) and * maximumPoolSize (see {@link #getMaximumPoolSize}). * * When a new task is submitted in method {@link #execute}, and fewer * than corePoolSize threads are running, a new thread is created to * handle the request, even if other worker threads are idle. If * there are more than corePoolSize but less than maximumPoolSize * threads running, a new thread will be created only if the queue is * full. By setting corePoolSize and maximumPoolSize the same, you * create a fixed-size thread pool. By setting maximumPoolSize to an * essentially unbounded value such as {@code Integer.MAX_VALUE}, you * allow the pool to accommodate an arbitrary number of concurrent * tasks. Most typically, core and maximum pool sizes are set only * upon construction, but they may also be changed dynamically using * {@link #setCorePoolSize} and {@link #setMaximumPoolSize}. </dd> * * <dt>On-demand construction</dt> * * <dd> By default, even core threads are initially created and * started only when new tasks arrive, but this can be overridden * dynamically using method {@link #prestartCoreThread} or {@link * #prestartAllCoreThreads}. You probably want to prestart threads if * you construct the pool with a non-empty queue. </dd> * * <dt>Creating new threads</dt> * * <dd>New threads are created using a {@link ThreadFactory}. If not * otherwise specified, a {@link Executors#defaultThreadFactory} is * used, that creates threads to all be in the same {@link * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and * non-daemon status. By supplying a different ThreadFactory, you can * alter the thread's name, thread group, priority, daemon status, * etc. If a {@code ThreadFactory} fails to create a thread when asked * by returning null from {@code newThread}, the executor will * continue, but might not be able to execute any tasks. Threads * should possess the "modifyThread" {@code RuntimePermission}. If * worker threads or other threads using the pool do not possess this * permission, service may be degraded: configuration changes may not * take effect in a timely manner, and a shutdown pool may remain in a * state in which termination is possible but not completed.</dd> * * <dt>Keep-alive times</dt> * * <dd>If the pool currently has more than corePoolSize threads, * excess threads will be terminated if they have been idle for more * than the keepAliveTime (see {@link #getKeepAliveTime}). This * provides a means of reducing resource consumption when the pool is * not being actively used. If the pool becomes more active later, new * threads will be constructed. This parameter can also be changed * dynamically using method {@link #setKeepAliveTime}. Using a value * of {@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS} effectively * disables idle threads from ever terminating prior to shut down. By * default, the keep-alive policy applies only when there are more * than corePoolSizeThreads. But method {@link * #allowCoreThreadTimeOut(boolean)} can be used to apply this * time-out policy to core threads as well, so long as the * keepAliveTime value is non-zero. </dd> * * <dt>Queuing</dt> * * <dd>Any {@link BlockingQueue} may be used to transfer and hold * submitted tasks. The use of this queue interacts with pool sizing: * * <ul> * * <li> If fewer than corePoolSize threads are running, the Executor * always prefers adding a new thread * rather than queuing.</li> * * <li> If corePoolSize or more threads are running, the Executor * always prefers queuing a request rather than adding a new * thread.</li> * * <li> If a request cannot be queued, a new thread is created unless * this would exceed maximumPoolSize, in which case, the task will be * rejected.</li> * * </ul> * * There are three general strategies for queuing: * <ol> * * <li> <em> Direct handoffs.</em> A good default choice for a work * queue is a {@link SynchronousQueue} that hands off tasks to threads * without otherwise holding them. Here, an attempt to queue a task * will fail if no threads are immediately available to run it, so a * new thread will be constructed. This policy avoids lockups when * handling sets of requests that might have internal dependencies. * Direct handoffs generally require unbounded maximumPoolSizes to * avoid rejection of new submitted tasks. This in turn admits the * possibility of unbounded thread growth when commands continue to * arrive on average faster than they can be processed. </li> * * <li><em> Unbounded queues.</em> Using an unbounded queue (for * example a {@link LinkedBlockingQueue} without a predefined * capacity) will cause new tasks to wait in the queue when all * corePoolSize threads are busy. Thus, no more than corePoolSize * threads will ever be created. (And the value of the maximumPoolSize * therefore doesn't have any effect.) This may be appropriate when * each task is completely independent of others, so tasks cannot * affect each others execution; for example, in a web page server. * While this style of queuing can be useful in smoothing out * transient bursts of requests, it admits the possibility of * unbounded work queue growth when commands continue to arrive on * average faster than they can be processed. </li> * * <li><em>Bounded queues.</em> A bounded queue (for example, an * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when * used with finite maximumPoolSizes, but can be more difficult to * tune and control. Queue sizes and maximum pool sizes may be traded * off for each other: Using large queues and small pools minimizes * CPU usage, OS resources, and context-switching overhead, but can * lead to artificially low throughput. If tasks frequently block (for * example if they are I/O bound), a system may be able to schedule * time for more threads than you otherwise allow. Use of small queues * generally requires larger pool sizes, which keeps CPUs busier but * may encounter unacceptable scheduling overhead, which also * decreases throughput. </li> * * </ol> * * </dd> * * <dt>Rejected tasks</dt> * * <dd> New tasks submitted in method {@link #execute} will be * <em>rejected</em> when the Executor has been shut down, and also * when the Executor uses finite bounds for both maximum threads and * work queue capacity, and is saturated. In either case, the {@code * execute} method invokes the {@link * RejectedExecutionHandler#rejectedExecution} method of its {@link * RejectedExecutionHandler}. Four predefined handler policies are * provided: * * <ol> * * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the * handler throws a runtime {@link RejectedExecutionException} upon * rejection. </li> * * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread * that invokes {@code execute} itself runs the task. This provides a * simple feedback control mechanism that will slow down the rate that * new tasks are submitted. </li> * * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that * cannot be executed is simply dropped. </li> * * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the * executor is not shut down, the task at the head of the work queue * is dropped, and then execution is retried (which can fail again, * causing this to be repeated.) </li> * * </ol> * * It is possible to define and use other kinds of {@link * RejectedExecutionHandler} classes. Doing so requires some care * especially when policies are designed to work only under particular * capacity or queuing policies. </dd> * * <dt>Hook methods</dt> * * <dd>This class provides {@code protected} overridable {@link * #beforeExecute} and {@link #afterExecute} methods that are called * before and after execution of each task. These can be used to * manipulate the execution environment; for example, reinitializing * ThreadLocals, gathering statistics, or adding log * entries. Additionally, method {@link #terminated} can be overridden * to perform any special processing that needs to be done once the * Executor has fully terminated. * * <p>If hook or callback methods throw exceptions, internal worker * threads may in turn fail and abruptly terminate.</dd> * * <dt>Queue maintenance</dt> * * <dd> Method {@link #getQueue} allows access to the work queue for * purposes of monitoring and debugging. Use of this method for any * other purpose is strongly discouraged. Two supplied methods, * {@link #remove} and {@link #purge} are available to assist in * storage reclamation when large numbers of queued tasks become * cancelled.</dd> * * <dt>Finalization</dt> * * <dd> A pool that is no longer referenced in a program <em>AND</em> * has no remaining threads will be {@code shutdown} automatically. If * you would like to ensure that unreferenced pools are reclaimed even * if users forget to call {@link #shutdown}, then you must arrange * that unused threads eventually die, by setting appropriate * keep-alive times, using a lower bound of zero core threads and/or * setting {@link #allowCoreThreadTimeOut(boolean)}. </dd> * * </dl> * * <p> <b>Extension example</b>. Most extensions of this class * override one or more of the protected hook methods. For example, * here is a subclass that adds a simple pause/resume feature: * * <pre> {@code * class PausableThreadPoolExecutor extends ThreadPoolExecutor { * private boolean isPaused; * private ReentrantLock pauseLock = new ReentrantLock(); * private Condition unpaused = pauseLock.newCondition(); * * public PausableThreadPoolExecutor(...) { super(...); } * * protected void beforeExecute(Thread t, Runnable r) { * super.beforeExecute(t, r); * pauseLock.lock(); * try { * while (isPaused) unpaused.await(); * } catch (InterruptedException ie) { * t.interrupt(); * } finally { * pauseLock.unlock(); * } * } * * public void pause() { * pauseLock.lock(); * try { * isPaused = true; * } finally { * pauseLock.unlock(); * } * } * * public void resume() { * pauseLock.lock(); * try { * isPaused = false; * unpaused.signalAll(); * } finally { * pauseLock.unlock(); * } * } * }}</pre> * {@description.close} * * @since 1.5 * @author Doug Lea */ public class ThreadPoolExecutor extends AbstractExecutorService { /** {@collect.stats} * {@description.open} * The main pool control state, ctl, is an atomic integer packing * two conceptual fields * workerCount, indicating the effective number of threads * runState, indicating whether running, shutting down etc * * In order to pack them into one int, we limit workerCount to * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2 * billion) otherwise representable. If this is ever an issue in * the future, the variable can be changed to be an AtomicLong, * and the shift/mask constants below adjusted. But until the need * arises, this code is a bit faster and simpler using an int. * * The workerCount is the number of workers that have been * permitted to start and not permitted to stop. The value may be * transiently different from the actual number of live threads, * for example when a ThreadFactory fails to create a thread when * asked, and when exiting threads are still performing * bookkeeping before terminating. The user-visible pool size is * reported as the current size of the workers set. * * The runState provides the main lifecyle control, taking on values: * * RUNNING: Accept new tasks and process queued tasks * SHUTDOWN: Don't accept new tasks, but process queued tasks * STOP: Don't accept new tasks, don't process queued tasks, * and interrupt in-progress tasks * TIDYING: All tasks have terminated, workerCount is zero, * the thread transitioning to state TIDYING * will run the terminated() hook method * TERMINATED: terminated() has completed * * The numerical order among these values matters, to allow * ordered comparisons. The runState monotonically increases over * time, but need not hit each state. The transitions are: * * RUNNING -> SHUTDOWN * On invocation of shutdown(), perhaps implicitly in finalize() * (RUNNING or SHUTDOWN) -> STOP * On invocation of shutdownNow() * SHUTDOWN -> TIDYING * When both queue and pool are empty * STOP -> TIDYING * When pool is empty * TIDYING -> TERMINATED * When the terminated() hook method has completed * * Threads waiting in awaitTermination() will return when the * state reaches TERMINATED. * * Detecting the transition from SHUTDOWN to TIDYING is less * straightforward than you'd like because the queue may become * empty after non-empty and vice versa during SHUTDOWN state, but * we can only terminate if, after seeing that it is empty, we see * that workerCount is 0 (which sometimes entails a recheck -- see * below). * {@description.close} */ private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static final int COUNT_BITS = Integer.SIZE - 3; private static final int CAPACITY = (1 << COUNT_BITS) - 1; // runState is stored in the high-order bits private static final int RUNNING = -1 << COUNT_BITS; private static final int SHUTDOWN = 0 << COUNT_BITS; private static final int STOP = 1 << COUNT_BITS; private static final int TIDYING = 2 << COUNT_BITS; private static final int TERMINATED = 3 << COUNT_BITS; // Packing and unpacking ctl private static int runStateOf(int c) { return c & ~CAPACITY; } private static int workerCountOf(int c) { return c & CAPACITY; } private static int ctlOf(int rs, int wc) { return rs | wc; } /* * Bit field accessors that don't require unpacking ctl. * These depend on the bit layout and on workerCount being never negative. */ private static boolean runStateLessThan(int c, int s) { return c < s; } private static boolean runStateAtLeast(int c, int s) { return c >= s; } private static boolean isRunning(int c) { return c < SHUTDOWN; } /** {@collect.stats} * {@description.open} * Attempt to CAS-increment the workerCount field of ctl. * {@description.close} */ private boolean compareAndIncrementWorkerCount(int expect) { return ctl.compareAndSet(expect, expect + 1); } /** {@collect.stats} * {@description.open} * Attempt to CAS-decrement the workerCount field of ctl. * {@description.close} */ private boolean compareAndDecrementWorkerCount(int expect) { return ctl.compareAndSet(expect, expect - 1); } /** {@collect.stats} * {@description.open} * Decrements the workerCount field of ctl. This is called only on * abrupt termination of a thread (see processWorkerExit). Other * decrements are performed within getTask. * {@description.close} */ private void decrementWorkerCount() { do {} while (! compareAndDecrementWorkerCount(ctl.get())); } /** {@collect.stats} * {@description.open} * The queue used for holding tasks and handing off to worker * threads. We do not require that workQueue.poll() returning * null necessarily means that workQueue.isEmpty(), so rely * solely on isEmpty to see if the queue is empty (which we must * do for example when deciding whether to transition from * SHUTDOWN to TIDYING). This accommodates special-purpose * queues such as DelayQueues for which poll() is allowed to * return null even if it may later return non-null when delays * expire. * {@description.close} */ private final BlockingQueue<Runnable> workQueue; /** {@collect.stats} * {@description.open} * Lock held on access to workers set and related bookkeeping. * While we could use a concurrent set of some sort, it turns out * to be generally preferable to use a lock. Among the reasons is * that this serializes interruptIdleWorkers, which avoids * unnecessary interrupt storms, especially during shutdown. * Otherwise exiting threads would concurrently interrupt those * that have not yet interrupted. It also simplifies some of the * associated statistics bookkeeping of largestPoolSize etc. We * also hold mainLock on shutdown and shutdownNow, for the sake of * ensuring workers set is stable while separately checking * permission to interrupt and actually interrupting. * {@description.close} */ private final ReentrantLock mainLock = new ReentrantLock(); /** {@collect.stats} * {@description.open} * Set containing all worker threads in pool. Accessed only when * holding mainLock. * {@description.close} */ private final HashSet<Worker> workers = new HashSet<Worker>(); /** {@collect.stats} * {@description.open} * Wait condition to support awaitTermination * {@description.close} */ private final Condition termination = mainLock.newCondition(); /** {@collect.stats} * {@description.open} * Tracks largest attained pool size. * {@description.open} * {@property.open internal} * Accessed only under * mainLock. * {@property.close} */ private int largestPoolSize; /** {@collect.stats} * {@description.open} * Counter for completed tasks. Updated only on termination of * worker threads. * {@description.close} * {@property.open internal} * Accessed only under mainLock. * {@property.close} */ private long completedTaskCount; /* * All user control parameters are declared as volatiles so that * ongoing actions are based on freshest values, but without need * for locking, since no internal invariants depend on them * changing synchronously with respect to other actions. */ /** {@collect.stats} * {@description.open} * Factory for new threads. All threads are created using this * factory (via method addWorker). All callers must be prepared * for addWorker to fail, which may reflect a system or user's * policy limiting the number of threads. Even though it is not * treated as an error, failure to create threads may result in * new tasks being rejected or existing ones remaining stuck in * the queue. On the other hand, no special precautions exist to * handle OutOfMemoryErrors that might be thrown while trying to * create threads, since there is generally no recourse from * within this class. * {@description.close} */ private volatile ThreadFactory threadFactory; /** {@collect.stats} * {@description.open} * Handler called when saturated or shutdown in execute. * {@description.close} */ private volatile RejectedExecutionHandler handler; /** {@collect.stats} * {@description.open} * Timeout in nanoseconds for idle threads waiting for work. * Threads use this timeout when there are more than corePoolSize * present or if allowCoreThreadTimeOut. Otherwise they wait * forever for new work. * {@description.close} */ private volatile long keepAliveTime; /** {@collect.stats} * {@description.open} * If false (default), core threads stay alive even when idle. * If true, core threads use keepAliveTime to time out waiting * for work. * {@description.close} */ private volatile boolean allowCoreThreadTimeOut; /** {@collect.stats} * {@description.open} * Core pool size is the minimum number of workers to keep alive * (and not allow to time out etc) unless allowCoreThreadTimeOut * is set, in which case the minimum is zero. * {@description.close} */ private volatile int corePoolSize; /** {@collect.stats} * {@description.open} * Maximum pool size. Note that the actual maximum is internally * bounded by CAPACITY. * {@description.close} */ private volatile int maximumPoolSize; /** {@collect.stats} * {@description.open} * The default rejected execution handler * {@description.close} */ private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); /** {@collect.stats} * {@description.open} * Permission required for callers of shutdown and shutdownNow. * We additionally require (see checkShutdownAccess) that callers * have permission to actually interrupt threads in the worker set * (as governed by Thread.interrupt, which relies on * ThreadGroup.checkAccess, which in turn relies on * SecurityManager.checkAccess). Shutdowns are attempted only if * these checks pass. * * All actual invocations of Thread.interrupt (see * interruptIdleWorkers and interruptWorkers) ignore * SecurityExceptions, meaning that the attempted interrupts * silently fail. In the case of shutdown, they should not fail * unless the SecurityManager has inconsistent policies, sometimes * allowing access to a thread and sometimes not. In such cases, * failure to actually interrupt threads may disable or delay full * termination. Other uses of interruptIdleWorkers are advisory, * and failure to actually interrupt will merely delay response to * configuration changes so is not handled exceptionally. * {@description.close} */ private static final RuntimePermission shutdownPerm = new RuntimePermission("modifyThread"); /** {@collect.stats} * {@description.open} * Class Worker mainly maintains interrupt control state for * threads running tasks, along with other minor bookkeeping. * This class opportunistically extends AbstractQueuedSynchronizer * to simplify acquiring and releasing a lock surrounding each * task execution. This protects against interrupts that are * intended to wake up a worker thread waiting for a task from * instead interrupting a task being run. We implement a simple * non-reentrant mutual exclusion lock rather than use ReentrantLock * because we do not want worker tasks to be able to reacquire the * lock when they invoke pool control methods like setCorePoolSize. * {@description.close} */ private final class Worker extends AbstractQueuedSynchronizer implements Runnable { /** {@collect.stats} * {@description.open} * This class will never be serialized, but we provide a * serialVersionUID to suppress a javac warning. * {@description.close} */ private static final long serialVersionUID = 6138294804551838833L; /** {@collect.stats} * {@description.open} * Thread this worker is running in. Null if factory fails. * {@description.close} */ final Thread thread; /** {@collect.stats} * {@description.open} * Initial task to run. Possibly null. * {@description.close} */ Runnable firstTask; /** {@collect.stats} * {@description.open} * Per-thread task counter * {@description.close} */ volatile long completedTasks; /** {@collect.stats} * {@description.open} * Creates with given first task and thread from ThreadFactory. * {@description.close} * @param firstTask the first task (null if none) */ Worker(Runnable firstTask) { this.firstTask = firstTask; this.thread = getThreadFactory().newThread(this); } /** {@collect.stats} * {@description.open} * Delegates main run loop to outer runWorker * {@description.close} */ public void run() { runWorker(this); } // Lock methods // // The value 0 represents the unlocked state. // The value 1 represents the locked state. protected boolean isHeldExclusively() { return getState() == 1; } protected boolean tryAcquire(int unused) { if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } protected boolean tryRelease(int unused) { setExclusiveOwnerThread(null); setState(0); return true; } public void lock() { acquire(1); } public boolean tryLock() { return tryAcquire(1); } public void unlock() { release(1); } public boolean isLocked() { return isHeldExclusively(); } } /* * Methods for setting control state */ /** {@collect.stats} * {@description.open} * Transitions runState to given target, or leaves it alone if * already at least the given target. * {@description.close} * * @param targetState the desired state, either SHUTDOWN or STOP * (but not TIDYING or TERMINATED -- use tryTerminate for that) */ private void advanceRunState(int targetState) { for (;;) { int c = ctl.get(); if (runStateAtLeast(c, targetState) || ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c)))) break; } } /** {@collect.stats} * {@description.open} * Transitions to TERMINATED state if either (SHUTDOWN and pool * and queue empty) or (STOP and pool empty). If otherwise * eligible to terminate but workerCount is nonzero, interrupts an * idle worker to ensure that shutdown signals propagate. This * method must be called following any action that might make * termination possible -- reducing worker count or removing tasks * from the queue during shutdown. The method is non-private to * allow access from ScheduledThreadPoolExecutor. * {@description.close} */ final void tryTerminate() { for (;;) { int c = ctl.get(); if (isRunning(c) || runStateAtLeast(c, TIDYING) || (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty())) return; if (workerCountOf(c) != 0) { // Eligible to terminate interruptIdleWorkers(ONLY_ONE); return; } final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) { try { terminated(); } finally { ctl.set(ctlOf(TERMINATED, 0)); termination.signalAll(); } return; } } finally { mainLock.unlock(); } // else retry on failed CAS } } /* * Methods for controlling interrupts to worker threads. */ /** {@collect.stats} * {@description.open} * If there is a security manager, makes sure caller has * permission to shut down threads in general (see shutdownPerm). * If this passes, additionally makes sure the caller is allowed * to interrupt each worker thread. This might not be true even if * first check passed, if the SecurityManager treats some threads * specially. * {@description.close} */ private void checkShutdownAccess() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(shutdownPerm); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) security.checkAccess(w.thread); } finally { mainLock.unlock(); } } } /** {@collect.stats} * {@description.open} * Interrupts all threads, even if active. Ignores SecurityExceptions * (in which case some threads may remain uninterrupted). * {@description.close} */ private void interruptWorkers() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) { try { w.thread.interrupt(); } catch (SecurityException ignore) { } } } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Interrupts threads that might be waiting for tasks (as * indicated by not being locked) so they can check for * termination or configuration changes. Ignores * SecurityExceptions (in which case some threads may remain * uninterrupted). * {@description.close} * * @param onlyOne If true, interrupt at most one worker. This is * called only from tryTerminate when termination is otherwise * enabled but there are still other workers. In this case, at * most one waiting worker is interrupted to propagate shutdown * signals in case all threads are currently waiting. * Interrupting any arbitrary thread ensures that newly arriving * workers since shutdown began will also eventually exit. * To guarantee eventual termination, it suffices to always * interrupt only one idle worker, but shutdown() interrupts all * idle workers so that redundant workers exit promptly, not * waiting for a straggler task to finish. */ private void interruptIdleWorkers(boolean onlyOne) { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) { Thread t = w.thread; if (!t.isInterrupted() && w.tryLock()) { try { t.interrupt(); } catch (SecurityException ignore) { } finally { w.unlock(); } } if (onlyOne) break; } } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Common form of interruptIdleWorkers, to avoid having to * remember what the boolean argument means. * {@description.close} */ private void interruptIdleWorkers() { interruptIdleWorkers(false); } private static final boolean ONLY_ONE = true; /** {@collect.stats} * {@description.open} * Ensures that unless the pool is stopping, the current thread * does not have its interrupt set. This requires a double-check * of state in case the interrupt was cleared concurrently with a * shutdownNow -- if so, the interrupt is re-enabled. * {@description.close} */ private void clearInterruptsForTaskRun() { if (runStateLessThan(ctl.get(), STOP) && Thread.interrupted() && runStateAtLeast(ctl.get(), STOP)) Thread.currentThread().interrupt(); } /* * Misc utilities, most of which are also exported to * ScheduledThreadPoolExecutor */ /** {@collect.stats} * {@description.open} * Invokes the rejected execution handler for the given command. * Package-protected for use by ScheduledThreadPoolExecutor. * {@description.close} */ final void reject(Runnable command) { handler.rejectedExecution(command, this); } /** {@collect.stats} * {@description.open} * Performs any further cleanup following run state transition on * invocation of shutdown. A no-op here, but used by * ScheduledThreadPoolExecutor to cancel delayed tasks. * {@description.close} */ void onShutdown() { } /** {@collect.stats} * {@description.open} * State check needed by ScheduledThreadPoolExecutor to * enable running tasks during shutdown. * {@description.close} * * @param shutdownOK true if should return true if SHUTDOWN */ final boolean isRunningOrShutdown(boolean shutdownOK) { int rs = runStateOf(ctl.get()); return rs == RUNNING || (rs == SHUTDOWN && shutdownOK); } /** {@collect.stats} * {@description.open} * Drains the task queue into a new list, normally using * drainTo. But if the queue is a DelayQueue or any other kind of * queue for which poll or drainTo may fail to remove some * elements, it deletes them one by one. * {@description.close} */ private List<Runnable> drainQueue() { BlockingQueue<Runnable> q = workQueue; List<Runnable> taskList = new ArrayList<Runnable>(); q.drainTo(taskList); if (!q.isEmpty()) { for (Runnable r : q.toArray(new Runnable[0])) { if (q.remove(r)) taskList.add(r); } } return taskList; } /* * Methods for creating, running and cleaning up after workers */ /** {@collect.stats} * {@description.open} * Checks if a new worker can be added with respect to current * pool state and the given bound (either core or maximum). If so, * the worker count is adjusted accordingly, and, if possible, a * new worker is created and started running firstTask as its * first task. This method returns false if the pool is stopped or * eligible to shut down. It also returns false if the thread * factory fails to create a thread when asked, which requires a * backout of workerCount, and a recheck for termination, in case * the existence of this worker was holding up termination. * {@description.close} * * @param firstTask the task the new thread should run first (or * null if none). Workers are created with an initial first task * (in method execute()) to bypass queuing when there are fewer * than corePoolSize threads (in which case we always start one), * or when the queue is full (in which case we must bypass queue). * Initially idle threads are usually created via * prestartCoreThread or to replace other dying workers. * * @param core if true use corePoolSize as bound, else * maximumPoolSize. (A boolean indicator is used here rather than a * value to ensure reads of fresh values after checking other pool * state). * @return true if successful */ private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())) return false; for (;;) { int wc = workerCountOf(c); if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } Worker w = new Worker(firstTask); Thread t = w.thread; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); int rs = runStateOf(c); if (t == null || (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null))) { decrementWorkerCount(); tryTerminate(); return false; } workers.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; } finally { mainLock.unlock(); } t.start(); // It is possible (but unlikely) for a thread to have been // added to workers, but not yet started, during transition to // STOP, which could result in a rare missed interrupt, // because Thread.interrupt is not guaranteed to have any effect // on a non-yet-started Thread (see Thread#interrupt). if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted()) t.interrupt(); return true; } /** {@collect.stats} * {@description.open} * Performs cleanup and bookkeeping for a dying worker. Called * only from worker threads. Unless completedAbruptly is set, * assumes that workerCount has already been adjusted to account * for exit. This method removes thread from worker set, and * possibly terminates the pool or replaces the worker if either * it exited due to user task exception or if fewer than * corePoolSize workers are running or queue is non-empty but * there are no workers. * {@description.close} * * @param w the worker * @param completedAbruptly if the worker died due to user exception */ private void processWorkerExit(Worker w, boolean completedAbruptly) { if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted decrementWorkerCount(); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { completedTaskCount += w.completedTasks; workers.remove(w); } finally { mainLock.unlock(); } tryTerminate(); int c = ctl.get(); if (runStateLessThan(c, STOP)) { if (!completedAbruptly) { int min = allowCoreThreadTimeOut ? 0 : corePoolSize; if (min == 0 && ! workQueue.isEmpty()) min = 1; if (workerCountOf(c) >= min) return; // replacement not needed } addWorker(null, false); } } /** {@collect.stats} * {@description.open} * Performs blocking or timed wait for a task, depending on * current configuration settings, or returns null if this worker * must exit because of any of: * 1. There are more than maximumPoolSize workers (due to * a call to setMaximumPoolSize). * 2. The pool is stopped. * 3. The pool is shutdown and the queue is empty. * 4. This worker timed out waiting for a task, and timed-out * workers are subject to termination (that is, * {@code allowCoreThreadTimeOut || workerCount > corePoolSize}) * both before and after the timed wait. * {@description.close} * * @return task, or null if the worker must exit, in which case * workerCount is decremented */ private Runnable getTask() { boolean timedOut = false; // Did the last poll() time out? retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; } boolean timed; // Are workers subject to culling? for (;;) { int wc = workerCountOf(c); timed = allowCoreThreadTimeOut || wc > corePoolSize; if (wc <= maximumPoolSize && ! (timedOut && timed)) break; if (compareAndDecrementWorkerCount(c)) return null; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } try { Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } } } /** {@collect.stats} * {@description.open} * Main worker run loop. Repeatedly gets tasks from queue and * executes them, while coping with a number of issues: * * 1. We may start out with an initial task, in which case we * don't need to get the first one. Otherwise, as long as pool is * running, we get tasks from getTask. If it returns null then the * worker exits due to changed pool state or configuration * parameters. Other exits result from exception throws in * external code, in which case completedAbruptly holds, which * usually leads processWorkerExit to replace this thread. * * 2. Before running any task, the lock is acquired to prevent * other pool interrupts while the task is executing, and * clearInterruptsForTaskRun called to ensure that unless pool is * stopping, this thread does not have its interrupt set. * * 3. Each task run is preceded by a call to beforeExecute, which * might throw an exception, in which case we cause thread to die * (breaking loop with completedAbruptly true) without processing * the task. * * 4. Assuming beforeExecute completes normally, we run the task, * gathering any of its thrown exceptions to send to * afterExecute. We separately handle RuntimeException, Error * (both of which the specs guarantee that we trap) and arbitrary * Throwables. Because we cannot rethrow Throwables within * Runnable.run, we wrap them within Errors on the way out (to the * thread's UncaughtExceptionHandler). Any thrown exception also * conservatively causes thread to die. * * 5. After task.run completes, we call afterExecute, which may * also throw an exception, which will also cause thread to * die. According to JLS Sec 14.20, this exception is the one that * will be in effect even if task.run throws. * * The net effect of the exception mechanics is that afterExecute * and the thread's UncaughtExceptionHandler have as accurate * information as we can provide about any problems encountered by * user code. * {@description.close} * * @param w the worker */ final void runWorker(Worker w) { Runnable task = w.firstTask; w.firstTask = null; boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); clearInterruptsForTaskRun(); try { beforeExecute(w.thread, task); Throwable thrown = null; try { task.run(); } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown); } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } // Public constructors and methods /** {@collect.stats} * {@description.open} * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters and default thread factory and rejected execution handler. * It may be more convenient to use one of the {@link Executors} factory * methods instead of this general purpose constructor. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } /** {@collect.stats} * {@description.open} * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters and default rejected execution handler. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @param threadFactory the factory to use when the executor * creates a new thread * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } /** {@collect.stats} * {@description.open} * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters and default thread factory. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code handler} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } /** {@collect.stats} * {@description.open} * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters. * {@description.close} * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @param threadFactory the factory to use when the executor * creates a new thread * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} or {@code handler} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; } /** {@collect.stats} * {@description.open} * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current {@code RejectedExecutionHandler}. * {@description.close} * * @param command the task to execute * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution * @throws NullPointerException if {@code command} is null */ public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); } /** {@collect.stats} * {@description.open} * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. * {@description.close} * {@property.open formal:java.util.concurrent.ThreadPoolExecutor_MultipleShutdown} * Invocation has no additional effect if already shut down. * {@property.close} * * @throws SecurityException {@inheritDoc} */ public void shutdown() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { checkShutdownAccess(); advanceRunState(SHUTDOWN); interruptIdleWorkers(); onShutdown(); // hook for ScheduledThreadPoolExecutor } finally { mainLock.unlock(); } tryTerminate(); } /** {@collect.stats} * {@description.open} * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a list of the tasks * that were awaiting execution. These tasks are drained (removed) * from the task queue upon return from this method. * * <p>There are no guarantees beyond best-effort attempts to stop * processing actively executing tasks. This implementation * cancels tasks via {@link Thread#interrupt}, so any task that * fails to respond to interrupts may never terminate. * {@description.close} * * @throws SecurityException {@inheritDoc} */ public List<Runnable> shutdownNow() { List<Runnable> tasks; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { checkShutdownAccess(); advanceRunState(STOP); interruptWorkers(); tasks = drainQueue(); } finally { mainLock.unlock(); } tryTerminate(); return tasks; } public boolean isShutdown() { return ! isRunning(ctl.get()); } /** {@collect.stats} * {@description.open} * Returns true if this executor is in the process of terminating * after {@link #shutdown} or {@link #shutdownNow} but has not * completely terminated. This method may be useful for * debugging. A return of {@code true} reported a sufficient * period after shutdown may indicate that submitted tasks have * ignored or suppressed interruption, causing this executor not * to properly terminate. * {@description.close} * * @return true if terminating but not yet terminated */ public boolean isTerminating() { int c = ctl.get(); return ! isRunning(c) && runStateLessThan(c, TERMINATED); } public boolean isTerminated() { return runStateAtLeast(ctl.get(), TERMINATED); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (;;) { if (runStateAtLeast(ctl.get(), TERMINATED)) return true; if (nanos <= 0) return false; nanos = termination.awaitNanos(nanos); } } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Invokes {@code shutdown} when this executor is no longer * referenced and it has no threads. * {@description.close} */ protected void finalize() { shutdown(); } /** {@collect.stats} * {@description.open} * Sets the thread factory used to create new threads. * {@description.close} * * @param threadFactory the new thread factory * @throws NullPointerException if threadFactory is null * @see #getThreadFactory */ public void setThreadFactory(ThreadFactory threadFactory) { if (threadFactory == null) throw new NullPointerException(); this.threadFactory = threadFactory; } /** {@collect.stats} * {@description.open} * Returns the thread factory used to create new threads. * {@description.close} * * @return the current thread factory * @see #setThreadFactory */ public ThreadFactory getThreadFactory() { return threadFactory; } /** {@collect.stats} * {@description.open} * Sets a new handler for unexecutable tasks. * {@description.close} * * @param handler the new handler * @throws NullPointerException if handler is null * @see #getRejectedExecutionHandler */ public void setRejectedExecutionHandler(RejectedExecutionHandler handler) { if (handler == null) throw new NullPointerException(); this.handler = handler; } /** {@collect.stats} * {@description.open} * Returns the current handler for unexecutable tasks. * {@description.close} * * @return the current handler * @see #setRejectedExecutionHandler */ public RejectedExecutionHandler getRejectedExecutionHandler() { return handler; } /** {@collect.stats} * {@description.open} * Sets the core number of threads. This overrides any value set * in the constructor. If the new value is smaller than the * current value, excess existing threads will be terminated when * they next become idle. If larger, new threads will, if needed, * be started to execute any queued tasks. * {@description.close} * * @param corePoolSize the new core size * @throws IllegalArgumentException if {@code corePoolSize < 0} * @see #getCorePoolSize */ public void setCorePoolSize(int corePoolSize) { if (corePoolSize < 0) throw new IllegalArgumentException(); int delta = corePoolSize - this.corePoolSize; this.corePoolSize = corePoolSize; if (workerCountOf(ctl.get()) > corePoolSize) interruptIdleWorkers(); else if (delta > 0) { // We don't really know how many new threads are "needed". // As a heuristic, prestart enough new workers (up to new // core size) to handle the current number of tasks in // queue, but stop if queue becomes empty while doing so. int k = Math.min(delta, workQueue.size()); while (k-- > 0 && addWorker(null, true)) { if (workQueue.isEmpty()) break; } } } /** {@collect.stats} * {@description.open} * Returns the core number of threads. * {@description.close} * * @return the core number of threads * @see #setCorePoolSize */ public int getCorePoolSize() { return corePoolSize; } /** {@collect.stats} * {@description.open} * Starts a core thread, causing it to idly wait for work. This * overrides the default policy of starting core threads only when * new tasks are executed. This method will return {@code false} * if all core threads have already been started. * {@description.close} * * @return {@code true} if a thread was started */ public boolean prestartCoreThread() { return workerCountOf(ctl.get()) < corePoolSize && addWorker(null, true); } /** {@collect.stats} * {@description.open} * Starts all core threads, causing them to idly wait for work. This * overrides the default policy of starting core threads only when * new tasks are executed. * {@description.close} * * @return the number of threads started */ public int prestartAllCoreThreads() { int n = 0; while (addWorker(null, true)) ++n; return n; } /** {@collect.stats} * {@description.open} * Returns true if this pool allows core threads to time out and * terminate if no tasks arrive within the keepAlive time, being * replaced if needed when new tasks arrive. When true, the same * keep-alive policy applying to non-core threads applies also to * core threads. When false (the default), core threads are never * terminated due to lack of incoming tasks. * {@description.close} * * @return {@code true} if core threads are allowed to time out, * else {@code false} * * @since 1.6 */ public boolean allowsCoreThreadTimeOut() { return allowCoreThreadTimeOut; } /** {@collect.stats} * {@description.open} * Sets the policy governing whether core threads may time out and * terminate if no tasks arrive within the keep-alive time, being * replaced if needed when new tasks arrive. When false, core * threads are never terminated due to lack of incoming * tasks. When true, the same keep-alive policy applying to * non-core threads applies also to core threads. To avoid * continual thread replacement, the keep-alive time must be * greater than zero when setting {@code true}. This method * should in general be called before the pool is actively used. * {@description.close} * * @param value {@code true} if should time out, else {@code false} * @throws IllegalArgumentException if value is {@code true} * and the current keep-alive time is not greater than zero * * @since 1.6 */ public void allowCoreThreadTimeOut(boolean value) { if (value && keepAliveTime <= 0) throw new IllegalArgumentException("Core threads must have nonzero keep alive times"); if (value != allowCoreThreadTimeOut) { allowCoreThreadTimeOut = value; if (value) interruptIdleWorkers(); } } /** {@collect.stats} * {@description.open} * Sets the maximum allowed number of threads. This overrides any * value set in the constructor. If the new value is smaller than * the current value, excess existing threads will be * terminated when they next become idle. * {@description.close} * * @param maximumPoolSize the new maximum * @throws IllegalArgumentException if the new maximum is * less than or equal to zero, or * less than the {@linkplain #getCorePoolSize core pool size} * @see #getMaximumPoolSize */ public void setMaximumPoolSize(int maximumPoolSize) { if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize) throw new IllegalArgumentException(); this.maximumPoolSize = maximumPoolSize; if (workerCountOf(ctl.get()) > maximumPoolSize) interruptIdleWorkers(); } /** {@collect.stats} * {@description.open} * Returns the maximum allowed number of threads. * {@description.close} * * @return the maximum allowed number of threads * @see #setMaximumPoolSize */ public int getMaximumPoolSize() { return maximumPoolSize; } /** {@collect.stats} * {@description.open} * Sets the time limit for which threads may remain idle before * being terminated. If there are more than the core number of * threads currently in the pool, after waiting this amount of * time without processing a task, excess threads will be * terminated. This overrides any value set in the constructor. * {@description.close} * * @param time the time to wait. A time value of zero will cause * excess threads to terminate immediately after executing tasks. * @param unit the time unit of the {@code time} argument * @throws IllegalArgumentException if {@code time} less than zero or * if {@code time} is zero and {@code allowsCoreThreadTimeOut} * @see #getKeepAliveTime */ public void setKeepAliveTime(long time, TimeUnit unit) { if (time < 0) throw new IllegalArgumentException(); if (time == 0 && allowsCoreThreadTimeOut()) throw new IllegalArgumentException("Core threads must have nonzero keep alive times"); long keepAliveTime = unit.toNanos(time); long delta = keepAliveTime - this.keepAliveTime; this.keepAliveTime = keepAliveTime; if (delta < 0) interruptIdleWorkers(); } /** {@collect.stats} * {@description.open} * Returns the thread keep-alive time, which is the amount of time * that threads in excess of the core pool size may remain * idle before being terminated. * {@description.close} * * @param unit the desired time unit of the result * @return the time limit * @see #setKeepAliveTime */ public long getKeepAliveTime(TimeUnit unit) { return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS); } /* User-level queue utilities */ /** {@collect.stats} * {@description.open} * Returns the task queue used by this executor. Access to the * task queue is intended primarily for debugging and monitoring. * This queue may be in active use. Retrieving the task queue * does not prevent queued tasks from executing. * {@description.close} * * @return the task queue */ public BlockingQueue<Runnable> getQueue() { return workQueue; } /** {@collect.stats} * {@description.open} * Removes this task from the executor's internal queue if it is * present, thus causing it not to be run if it has not already * started. * * <p> This method may be useful as one part of a cancellation * scheme. It may fail to remove tasks that have been converted * into other forms before being placed on the internal queue. For * example, a task entered using {@code submit} might be * converted into a form that maintains {@code Future} status. * However, in such cases, method {@link #purge} may be used to * remove those Futures that have been cancelled. * {@description.close} * * @param task the task to remove * @return true if the task was removed */ public boolean remove(Runnable task) { boolean removed = workQueue.remove(task); tryTerminate(); // In case SHUTDOWN and now empty return removed; } /** {@collect.stats} * {@description.open} * Tries to remove from the work queue all {@link Future} * tasks that have been cancelled. This method can be useful as a * storage reclamation operation, that has no other impact on * functionality. Cancelled tasks are never executed, but may * accumulate in work queues until worker threads can actively * remove them. Invoking this method instead tries to remove them now. * However, this method may fail to remove tasks in * the presence of interference by other threads. * {@description.close} */ public void purge() { final BlockingQueue<Runnable> q = workQueue; try { Iterator<Runnable> it = q.iterator(); while (it.hasNext()) { Runnable r = it.next(); if (r instanceof Future<?> && ((Future<?>)r).isCancelled()) it.remove(); } } catch (ConcurrentModificationException fallThrough) { // Take slow path if we encounter interference during traversal. // Make copy for traversal and call remove for cancelled entries. // The slow path is more likely to be O(N*N). for (Object r : q.toArray()) if (r instanceof Future<?> && ((Future<?>)r).isCancelled()) q.remove(r); } tryTerminate(); // In case SHUTDOWN and now empty } /* Statistics */ /** {@collect.stats} * {@description.open} * Returns the current number of threads in the pool. * {@description.close} * * @return the number of threads */ public int getPoolSize() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Remove rare and surprising possibility of // isTerminated() && getPoolSize() > 0 return runStateAtLeast(ctl.get(), TIDYING) ? 0 : workers.size(); } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the approximate number of threads that are actively * executing tasks. * {@description.close} * * @return the number of threads */ public int getActiveCount() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { int n = 0; for (Worker w : workers) if (w.isLocked()) ++n; return n; } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the largest number of threads that have ever * simultaneously been in the pool. * {@description.close} * * @return the number of threads */ public int getLargestPoolSize() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { return largestPoolSize; } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the approximate total number of tasks that have ever been * scheduled for execution. Because the states of tasks and * threads may change dynamically during computation, the returned * value is only an approximation. * {@description.close} * * @return the number of tasks */ public long getTaskCount() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { long n = completedTaskCount; for (Worker w : workers) { n += w.completedTasks; if (w.isLocked()) ++n; } return n + workQueue.size(); } finally { mainLock.unlock(); } } /** {@collect.stats} * {@description.open} * Returns the approximate total number of tasks that have * completed execution. Because the states of tasks and threads * may change dynamically during computation, the returned value * is only an approximation, but one that does not ever decrease * across successive calls. * {@description.close} * * @return the number of tasks */ public long getCompletedTaskCount() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { long n = completedTaskCount; for (Worker w : workers) n += w.completedTasks; return n; } finally { mainLock.unlock(); } } /* Extension hooks */ /** {@collect.stats} * {@description.open} * Method invoked prior to executing the given Runnable in the * given thread. This method is invoked by thread {@code t} that * will execute task {@code r}, and may be used to re-initialize * ThreadLocals, or to perform logging. * * <p>This implementation does nothing, but may be customized in * subclasses. Note: To properly nest multiple overridings, subclasses * should generally invoke {@code super.beforeExecute} at the end of * this method. * {@description.close} * * @param t the thread that will run task {@code r} * @param r the task that will be executed */ protected void beforeExecute(Thread t, Runnable r) { } /** {@collect.stats} * {@description.open} * Method invoked upon completion of execution of the given Runnable. * This method is invoked by the thread that executed the task. If * non-null, the Throwable is the uncaught {@code RuntimeException} * or {@code Error} that caused execution to terminate abruptly. * * <p>This implementation does nothing, but may be customized in * subclasses. Note: To properly nest multiple overridings, subclasses * should generally invoke {@code super.afterExecute} at the * beginning of this method. * * <p><b>Note:</b> When actions are enclosed in tasks (such as * {@link FutureTask}) either explicitly or via methods such as * {@code submit}, these task objects catch and maintain * computational exceptions, and so they do not cause abrupt * termination, and the internal exceptions are <em>not</em> * passed to this method. If you would like to trap both kinds of * failures in this method, you can further probe for such cases, * as in this sample subclass that prints either the direct cause * or the underlying exception if a task has been aborted: * * <pre> {@code * class ExtendedExecutor extends ThreadPoolExecutor { * // ... * protected void afterExecute(Runnable r, Throwable t) { * super.afterExecute(r, t); * if (t == null && r instanceof Future<?>) { * try { * Object result = ((Future<?>) r).get(); * } catch (CancellationException ce) { * t = ce; * } catch (ExecutionException ee) { * t = ee.getCause(); * } catch (InterruptedException ie) { * Thread.currentThread().interrupt(); // ignore/reset * } * } * if (t != null) * System.out.println(t); * } * }}</pre> * {@description.close} * * @param r the runnable that has completed * @param t the exception that caused termination, or null if * execution completed normally */ protected void afterExecute(Runnable r, Throwable t) { } /** {@collect.stats} * {@description.open} * Method invoked when the Executor has terminated. Default * implementation does nothing. Note: To properly nest multiple * overridings, subclasses should generally invoke * {@code super.terminated} within this method. * {@description.close} */ protected void terminated() { } /* Predefined RejectedExecutionHandlers */ /** {@collect.stats} * {@description.open} * A handler for rejected tasks that runs the rejected task * directly in the calling thread of the {@code execute} method, * unless the executor has been shut down, in which case the task * is discarded. * {@description.close} */ public static class CallerRunsPolicy implements RejectedExecutionHandler { /** {@collect.stats} * {@description.open} * Creates a {@code CallerRunsPolicy}. * {@description.close} */ public CallerRunsPolicy() { } /** {@collect.stats} * {@description.open} * Executes task r in the caller's thread, unless the executor * has been shut down, in which case the task is discarded. * {@description.close} * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); } } } /** {@collect.stats} * {@description.open} * A handler for rejected tasks that throws a * {@code RejectedExecutionException}. * {@description.close} */ public static class AbortPolicy implements RejectedExecutionHandler { /** {@collect.stats} * {@description.open} * Creates an {@code AbortPolicy}. * {@description.close} */ public AbortPolicy() { } /** {@collect.stats} * {@description.open} * Always throws RejectedExecutionException. * {@description.close} * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task * @throws RejectedExecutionException always. */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { throw new RejectedExecutionException(); } } /** {@collect.stats} * {@description.open} * A handler for rejected tasks that silently discards the * rejected task. * {@description.close} */ public static class DiscardPolicy implements RejectedExecutionHandler { /** {@collect.stats} * {@description.open} * Creates a {@code DiscardPolicy}. * {@description.close} */ public DiscardPolicy() { } /** {@collect.stats} * {@description.open} * Does nothing, which has the effect of discarding task r. * {@description.close} * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { } } /** {@collect.stats} * {@description.open} * A handler for rejected tasks that discards the oldest unhandled * request and then retries {@code execute}, unless the executor * is shut down, in which case the task is discarded. * {@description.close} */ public static class DiscardOldestPolicy implements RejectedExecutionHandler { /** {@collect.stats} * {@description.open} * Creates a {@code DiscardOldestPolicy} for the given executor. * {@description.close} */ public DiscardOldestPolicy() { } /** {@collect.stats} * {@description.open} * Obtains and ignores the next task that the executor * would otherwise execute, if one is immediately available, * and then retries execution of task r, unless the executor * is shut down, in which case task r is instead discarded. * {@description.close} * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * Exception thrown when a blocking operation times out. Blocking * operations for which a timeout is specified need a means to * indicate that the timeout has occurred. For many such operations it * is possible to return a value that indicates timeout; when that is * not possible or desirable then <tt>TimeoutException</tt> should be * declared and thrown. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class TimeoutException extends Exception { private static final long serialVersionUID = 1900926677490660714L; /** {@collect.stats} * {@description.open} * Constructs a <tt>TimeoutException</tt> with no specified detail * message. * {@description.close} */ public TimeoutException() {} /** {@collect.stats} * {@description.open} * Constructs a <tt>TimeoutException</tt> with the specified detail * message. * {@description.close} * * @param message the detail message */ public TimeoutException(String message) { super(message); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * Exception thrown by an {@link Executor} when a task cannot be * accepted for execution. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class RejectedExecutionException extends RuntimeException { private static final long serialVersionUID = -375805702767069545L; /** {@collect.stats} * {@description.open} * Constructs a <tt>RejectedExecutionException</tt> with no detail message. * The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause(Throwable) initCause}. * {@description.close} */ public RejectedExecutionException() { } /** {@collect.stats} * {@description.open} * Constructs a <tt>RejectedExecutionException</tt> with the * specified detail message. The cause is not initialized, and may * subsequently be initialized by a call to {@link * #initCause(Throwable) initCause}. * {@description.close} * * @param message the detail message */ public RejectedExecutionException(String message) { super(message); } /** {@collect.stats} * {@description.open} * Constructs a <tt>RejectedExecutionException</tt> with the * specified detail message and cause. * {@description.close} * * @param message the detail message * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method) */ public RejectedExecutionException(String message, Throwable cause) { super(message, cause); } /** {@collect.stats} * {@description.open} * Constructs a <tt>RejectedExecutionException</tt> with the * specified cause. The detail message is set to: <pre> (cause == * null ? null : cause.toString())</pre> (which typically contains * the class and detail message of <tt>cause</tt>). * {@description.close} * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method) */ public RejectedExecutionException(Throwable cause) { super(cause); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import java.util.concurrent.atomic.*; /** {@collect.stats} * {@description.open} * A scalable concurrent {@link ConcurrentNavigableMap} implementation. * The map is sorted according to the {@linkplain Comparable natural * ordering} of its keys, or by a {@link Comparator} provided at map * creation time, depending on which constructor is used. * * <p>This class implements a concurrent variant of <a * href="http://www.cs.umd.edu/~pugh/">SkipLists</a> providing * expected average <i>log(n)</i> time cost for the * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and * <tt>remove</tt> operations and their variants. Insertion, removal, * update, and access operations safely execute concurrently by * multiple threads. * {@description.close} * {@property.open synchronized} * Iterators are <i>weakly consistent</i>, returning * elements reflecting the state of the map at some point at or since * the creation of the iterator. They do <em>not</em> throw {@link * ConcurrentModificationException}, and may proceed concurrently with * other operations. * {@property.close} * {@description.open} * Ascending key ordered views and their iterators * are faster than descending ones. * * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class * and its views represent snapshots of mappings at the time they were * produced. They do <em>not</em> support the <tt>Entry.setValue</tt> * method. (Note however that it is possible to change mappings in the * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or * <tt>replace</tt>, depending on exactly which effect you need.) * * <p>Beware that, unlike in most collections, the <tt>size</tt> * method is <em>not</em> a constant-time operation. Because of the * asynchronous nature of these maps, determining the current number * of elements requires a traversal of the elements. Additionally, * the bulk operations <tt>putAll</tt>, <tt>equals</tt>, and * <tt>clear</tt> are <em>not</em> guaranteed to be performed * atomically. For example, an iterator operating concurrently with a * <tt>putAll</tt> operation might view only some of the added * elements. * * <p>This class and its views and iterators implement all of the * <em>optional</em> methods of the {@link Map} and {@link Iterator} * interfaces. Like most other concurrent collections, this class does * <em>not</em> permit the use of <tt>null</tt> keys or values because some * null return values cannot be reliably distinguished from the absence of * elements. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Doug Lea * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * @since 1.6 */ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V> implements ConcurrentNavigableMap<K,V>, Cloneable, java.io.Serializable { /* * This class implements a tree-like two-dimensionally linked skip * list in which the index levels are represented in separate * nodes from the base nodes holding data. There are two reasons * for taking this approach instead of the usual array-based * structure: 1) Array based implementations seem to encounter * more complexity and overhead 2) We can use cheaper algorithms * for the heavily-traversed index lists than can be used for the * base lists. Here's a picture of some of the basics for a * possible list with 2 levels of index: * * Head nodes Index nodes * +-+ right +-+ +-+ * |2|---------------->| |--------------------->| |->null * +-+ +-+ +-+ * | down | | * v v v * +-+ +-+ +-+ +-+ +-+ +-+ * |1|----------->| |->| |------>| |----------->| |------>| |->null * +-+ +-+ +-+ +-+ +-+ +-+ * v | | | | | * Nodes next v v v v v * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ * * The base lists use a variant of the HM linked ordered set * algorithm. See Tim Harris, "A pragmatic implementation of * non-blocking linked lists" * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged * Michael "High Performance Dynamic Lock-Free Hash Tables and * List-Based Sets" * http://www.research.ibm.com/people/m/michael/pubs.htm. The * basic idea in these lists is to mark the "next" pointers of * deleted nodes when deleting to avoid conflicts with concurrent * insertions, and when traversing to keep track of triples * (predecessor, node, successor) in order to detect when and how * to unlink these deleted nodes. * * Rather than using mark-bits to mark list deletions (which can * be slow and space-intensive using AtomicMarkedReference), nodes * use direct CAS'able next pointers. On deletion, instead of * marking a pointer, they splice in another node that can be * thought of as standing for a marked pointer (indicating this by * using otherwise impossible field values). Using plain nodes * acts roughly like "boxed" implementations of marked pointers, * but uses new nodes only when nodes are deleted, not for every * link. This requires less space and supports faster * traversal. Even if marked references were better supported by * JVMs, traversal using this technique might still be faster * because any search need only read ahead one more node than * otherwise required (to check for trailing marker) rather than * unmasking mark bits or whatever on each read. * * This approach maintains the essential property needed in the HM * algorithm of changing the next-pointer of a deleted node so * that any other CAS of it will fail, but implements the idea by * changing the pointer to point to a different node, not by * marking it. While it would be possible to further squeeze * space by defining marker nodes not to have key/value fields, it * isn't worth the extra type-testing overhead. The deletion * markers are rarely encountered during traversal and are * normally quickly garbage collected. (Note that this technique * would not work well in systems without garbage collection.) * * In addition to using deletion markers, the lists also use * nullness of value fields to indicate deletion, in a style * similar to typical lazy-deletion schemes. If a node's value is * null, then it is considered logically deleted and ignored even * though it is still reachable. This maintains proper control of * concurrent replace vs delete operations -- an attempted replace * must fail if a delete beat it by nulling field, and a delete * must return the last non-null value held in the field. (Note: * Null, rather than some special marker, is used for value fields * here because it just so happens to mesh with the Map API * requirement that method get returns null if there is no * mapping, which allows nodes to remain concurrently readable * even when deleted. Using any other marker value here would be * messy at best.) * * Here's the sequence of events for a deletion of node n with * predecessor b and successor f, initially: * * +------+ +------+ +------+ * ... | b |------>| n |----->| f | ... * +------+ +------+ +------+ * * 1. CAS n's value field from non-null to null. * From this point on, no public operations encountering * the node consider this mapping to exist. However, other * ongoing insertions and deletions might still modify * n's next pointer. * * 2. CAS n's next pointer to point to a new marker node. * From this point on, no other nodes can be appended to n. * which avoids deletion errors in CAS-based linked lists. * * +------+ +------+ +------+ +------+ * ... | b |------>| n |----->|marker|------>| f | ... * +------+ +------+ +------+ +------+ * * 3. CAS b's next pointer over both n and its marker. * From this point on, no new traversals will encounter n, * and it can eventually be GCed. * +------+ +------+ * ... | b |----------------------------------->| f | ... * +------+ +------+ * * A failure at step 1 leads to simple retry due to a lost race * with another operation. Steps 2-3 can fail because some other * thread noticed during a traversal a node with null value and * helped out by marking and/or unlinking. This helping-out * ensures that no thread can become stuck waiting for progress of * the deleting thread. The use of marker nodes slightly * complicates helping-out code because traversals must track * consistent reads of up to four nodes (b, n, marker, f), not * just (b, n, f), although the next field of a marker is * immutable, and once a next field is CAS'ed to point to a * marker, it never again changes, so this requires less care. * * Skip lists add indexing to this scheme, so that the base-level * traversals start close to the locations being found, inserted * or deleted -- usually base level traversals only traverse a few * nodes. This doesn't change the basic algorithm except for the * need to make sure base traversals start at predecessors (here, * b) that are not (structurally) deleted, otherwise retrying * after processing the deletion. * * Index levels are maintained as lists with volatile next fields, * using CAS to link and unlink. Races are allowed in index-list * operations that can (rarely) fail to link in a new index node * or delete one. (We can't do this of course for data nodes.) * However, even when this happens, the index lists remain sorted, * so correctly serve as indices. This can impact performance, * but since skip lists are probabilistic anyway, the net result * is that under contention, the effective "p" value may be lower * than its nominal value. And race windows are kept small enough * that in practice these failures are rare, even under a lot of * contention. * * The fact that retries (for both base and index lists) are * relatively cheap due to indexing allows some minor * simplifications of retry logic. Traversal restarts are * performed after most "helping-out" CASes. This isn't always * strictly necessary, but the implicit backoffs tend to help * reduce other downstream failed CAS's enough to outweigh restart * cost. This worsens the worst case, but seems to improve even * highly contended cases. * * Unlike most skip-list implementations, index insertion and * deletion here require a separate traversal pass occuring after * the base-level action, to add or remove index nodes. This adds * to single-threaded overhead, but improves contended * multithreaded performance by narrowing interference windows, * and allows deletion to ensure that all index nodes will be made * unreachable upon return from a public remove operation, thus * avoiding unwanted garbage retention. This is more important * here than in some other data structures because we cannot null * out node fields referencing user keys since they might still be * read by other ongoing traversals. * * Indexing uses skip list parameters that maintain good search * performance while using sparser-than-usual indices: The * hardwired parameters k=1, p=0.5 (see method randomLevel) mean * that about one-quarter of the nodes have indices. Of those that * do, half have one level, a quarter have two, and so on (see * Pugh's Skip List Cookbook, sec 3.4). The expected total space * requirement for a map is slightly less than for the current * implementation of java.util.TreeMap. * * Changing the level of the index (i.e, the height of the * tree-like structure) also uses CAS. The head index has initial * level/height of one. Creation of an index with height greater * than the current level adds a level to the head index by * CAS'ing on a new top-most head. To maintain good performance * after a lot of removals, deletion methods heuristically try to * reduce the height if the topmost levels appear to be empty. * This may encounter races in which it possible (but rare) to * reduce and "lose" a level just as it is about to contain an * index (that will then never be encountered). This does no * structural harm, and in practice appears to be a better option * than allowing unrestrained growth of levels. * * The code for all this is more verbose than you'd like. Most * operations entail locating an element (or position to insert an * element). The code to do this can't be nicely factored out * because subsequent uses require a snapshot of predecessor * and/or successor and/or value fields which can't be returned * all at once, at least not without creating yet another object * to hold them -- creating such little objects is an especially * bad idea for basic internal search operations because it adds * to GC overhead. (This is one of the few times I've wished Java * had macros.) Instead, some traversal code is interleaved within * insertion and removal operations. The control logic to handle * all the retry conditions is sometimes twisty. Most search is * broken into 2 parts. findPredecessor() searches index nodes * only, returning a base-level predecessor of the key. findNode() * finishes out the base-level search. Even with this factoring, * there is a fair amount of near-duplication of code to handle * variants. * * For explanation of algorithms sharing at least a couple of * features with this one, see Mikhail Fomitchev's thesis * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's * thesis (http://www.cs.chalmers.se/~phs/). * * Given the use of tree-like index nodes, you might wonder why * this doesn't use some kind of search tree instead, which would * support somewhat faster search operations. The reason is that * there are no known efficient lock-free insertion and deletion * algorithms for search trees. The immutability of the "down" * links of index nodes (as opposed to mutable "left" fields in * true trees) makes this tractable using only CAS operations. * * Notation guide for local variables * Node: b, n, f for predecessor, node, successor * Index: q, r, d for index node, right, down. * t for another index node * Head: h * Levels: j * Keys: k, key * Values: v, value * Comparisons: c */ private static final long serialVersionUID = -8627078645895051609L; /** {@collect.stats} * {@description.open} * Generates the initial random seed for the cheaper per-instance * random number generators used in randomLevel. * {@description.close} */ private static final Random seedGenerator = new Random(); /** {@collect.stats} * {@description.open} * Special value used to identify base-level header * {@description.close} */ private static final Object BASE_HEADER = new Object(); /** {@collect.stats} * {@description.open} * The topmost head index of the skiplist. * {@description.close} */ private transient volatile HeadIndex<K,V> head; /** {@collect.stats} * {@description.open} * The comparator used to maintain order in this map, or null * if using natural ordering. * {@description.close} * @serial */ private final Comparator<? super K> comparator; /** {@collect.stats} * {@description.open} * Seed for simple random number generator. Not volatile since it * doesn't matter too much if different threads don't see updates. * {@description.close} */ private transient int randomSeed; /** {@collect.stats} * {@description.open} * Lazily initialized key set * {@description.close} */ private transient KeySet keySet; /** {@collect.stats} * {@description.open} * Lazily initialized entry set * {@description.close} */ private transient EntrySet entrySet; /** {@collect.stats} * {@description.open} * Lazily initialized values collection * {@description.close} */ private transient Values values; /** {@collect.stats} * {@description.open} * Lazily initialized descending key set * {@description.close} */ private transient ConcurrentNavigableMap<K,V> descendingMap; /** {@collect.stats} * {@description.open} * Initializes or resets state. Needed by constructors, clone, * clear, readObject. and ConcurrentSkipListSet.clone. * (Note that comparator must be separately initialized.) * {@description.close} */ final void initialize() { keySet = null; entrySet = null; values = null; descendingMap = null; randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null), null, null, 1); } /** {@collect.stats} * {@description.open} * Updater for casHead * {@description.close} */ private static final AtomicReferenceFieldUpdater<ConcurrentSkipListMap, HeadIndex> headUpdater = AtomicReferenceFieldUpdater.newUpdater (ConcurrentSkipListMap.class, HeadIndex.class, "head"); /** {@collect.stats} * {@description.open} * compareAndSet head node * {@description.close} */ private boolean casHead(HeadIndex<K,V> cmp, HeadIndex<K,V> val) { return headUpdater.compareAndSet(this, cmp, val); } /* ---------------- Nodes -------------- */ /** {@collect.stats} * {@description.open} * Nodes hold keys and values, and are singly linked in sorted * order, possibly with some intervening marker nodes. The list is * headed by a dummy node accessible as head.node. The value field * is declared only as Object because it takes special non-V * values for marker and header nodes. * {@description.close} */ static final class Node<K,V> { final K key; volatile Object value; volatile Node<K,V> next; /** {@collect.stats} * {@description.open} * Creates a new regular node. * {@description.close} */ Node(K key, Object value, Node<K,V> next) { this.key = key; this.value = value; this.next = next; } /** {@collect.stats} * {@description.open} * Creates a new marker node. A marker is distinguished by * having its value field point to itself. Marker nodes also * have null keys, a fact that is exploited in a few places, * but this doesn't distinguish markers from the base-level * header node (head.node), which also has a null key. * {@description.close} */ Node(Node<K,V> next) { this.key = null; this.value = this; this.next = next; } /** {@collect.stats} * {@description.open} * Updater for casNext * {@description.close} */ static final AtomicReferenceFieldUpdater<Node, Node> nextUpdater = AtomicReferenceFieldUpdater.newUpdater (Node.class, Node.class, "next"); /** {@collect.stats} * {@description.open} * Updater for casValue * {@description.close} */ static final AtomicReferenceFieldUpdater<Node, Object> valueUpdater = AtomicReferenceFieldUpdater.newUpdater (Node.class, Object.class, "value"); /** {@collect.stats} * {@description.open} * compareAndSet value field * {@description.close} */ boolean casValue(Object cmp, Object val) { return valueUpdater.compareAndSet(this, cmp, val); } /** {@collect.stats} * {@description.open} * compareAndSet next field * {@description.close} */ boolean casNext(Node<K,V> cmp, Node<K,V> val) { return nextUpdater.compareAndSet(this, cmp, val); } /** {@collect.stats} * {@description.open} * Returns true if this node is a marker. This method isn't * actually called in any current code checking for markers * because callers will have already read value field and need * to use that read (not another done here) and so directly * test if value points to node. * {@description.close} * @param n a possibly null reference to a node * @return true if this node is a marker node */ boolean isMarker() { return value == this; } /** {@collect.stats} * {@description.open} * Returns true if this node is the header of base-level list. * {@description.close} * @return true if this node is header node */ boolean isBaseHeader() { return value == BASE_HEADER; } /** {@collect.stats} * {@description.open} * Tries to append a deletion marker to this node. * {@description.close} * @param f the assumed current successor of this node * @return true if successful */ boolean appendMarker(Node<K,V> f) { return casNext(f, new Node<K,V>(f)); } /** {@collect.stats} * {@description.open} * Helps out a deletion by appending marker or unlinking from * predecessor. This is called during traversals when value * field seen to be null. * {@description.close} * @param b predecessor * @param f successor */ void helpDelete(Node<K,V> b, Node<K,V> f) { /* * Rechecking links and then doing only one of the * help-out stages per call tends to minimize CAS * interference among helping threads. */ if (f == next && this == b.next) { if (f == null || f.value != f) // not already marked appendMarker(f); else b.casNext(this, f.next); } } /** {@collect.stats} * {@description.open} * Returns value if this node contains a valid key-value pair, * else null. * {@description.close} * @return this node's value if it isn't a marker or header or * is deleted, else null. */ V getValidValue() { Object v = value; if (v == this || v == BASE_HEADER) return null; return (V)v; } /** {@collect.stats} * {@description.open} * Creates and returns a new SimpleImmutableEntry holding current * mapping if this node holds a valid value, else null. * {@description.close} * @return new entry or null */ AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() { V v = getValidValue(); if (v == null) return null; return new AbstractMap.SimpleImmutableEntry<K,V>(key, v); } } /* ---------------- Indexing -------------- */ /** {@collect.stats} * {@description.open} * Index nodes represent the levels of the skip list. Note that * even though both Nodes and Indexes have forward-pointing * fields, they have different types and are handled in different * ways, that can't nicely be captured by placing field in a * shared abstract class. * {@description.close} */ static class Index<K,V> { final Node<K,V> node; final Index<K,V> down; volatile Index<K,V> right; /** {@collect.stats} * {@description.open} * Creates index node with given values. * {@description.close} */ Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) { this.node = node; this.down = down; this.right = right; } /** {@collect.stats} * {@description.open} * Updater for casRight * {@description.close} */ static final AtomicReferenceFieldUpdater<Index, Index> rightUpdater = AtomicReferenceFieldUpdater.newUpdater (Index.class, Index.class, "right"); /** {@collect.stats} * {@description.open} * compareAndSet right field * {@description.close} */ final boolean casRight(Index<K,V> cmp, Index<K,V> val) { return rightUpdater.compareAndSet(this, cmp, val); } /** {@collect.stats} * {@description.open} * Returns true if the node this indexes has been deleted. * {@description.close} * @return true if indexed node is known to be deleted */ final boolean indexesDeletedNode() { return node.value == null; } /** {@collect.stats} * {@description.open} * Tries to CAS newSucc as successor. To minimize races with * unlink that may lose this index node, if the node being * indexed is known to be deleted, it doesn't try to link in. * {@description.close} * @param succ the expected current successor * @param newSucc the new successor * @return true if successful */ final boolean link(Index<K,V> succ, Index<K,V> newSucc) { Node<K,V> n = node; newSucc.right = succ; return n.value != null && casRight(succ, newSucc); } /** {@collect.stats} * {@description.open} * Tries to CAS right field to skip over apparent successor * succ. Fails (forcing a retraversal by caller) if this node * is known to be deleted. * {@description.close} * @param succ the expected current successor * @return true if successful */ final boolean unlink(Index<K,V> succ) { return !indexesDeletedNode() && casRight(succ, succ.right); } } /* ---------------- Head nodes -------------- */ /** {@collect.stats} * {@description.open} * Nodes heading each level keep track of their level. * {@description.close} */ static final class HeadIndex<K,V> extends Index<K,V> { final int level; HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) { super(node, down, right); this.level = level; } } /* ---------------- Comparison utilities -------------- */ /** {@collect.stats} * {@description.open} * Represents a key with a comparator as a Comparable. * * Because most sorted collections seem to use natural ordering on * Comparables (Strings, Integers, etc), most internal methods are * geared to use them. This is generally faster than checking * per-comparison whether to use comparator or comparable because * it doesn't require a (Comparable) cast for each comparison. * (Optimizers can only sometimes remove such redundant checks * themselves.) When Comparators are used, * ComparableUsingComparators are created so that they act in the * same way as natural orderings. This penalizes use of * Comparators vs Comparables, which seems like the right * tradeoff. * {@description.close} */ static final class ComparableUsingComparator<K> implements Comparable<K> { final K actualKey; final Comparator<? super K> cmp; ComparableUsingComparator(K key, Comparator<? super K> cmp) { this.actualKey = key; this.cmp = cmp; } public int compareTo(K k2) { return cmp.compare(actualKey, k2); } } /** {@collect.stats} * {@description.open} * If using comparator, return a ComparableUsingComparator, else * cast key as Comparable, which may cause ClassCastException, * which is propagated back to caller. * {@description.close} */ private Comparable<? super K> comparable(Object key) throws ClassCastException { if (key == null) throw new NullPointerException(); if (comparator != null) return new ComparableUsingComparator<K>((K)key, comparator); else return (Comparable<? super K>)key; } /** {@collect.stats} * {@description.open} * Compares using comparator or natural ordering. Used when the * ComparableUsingComparator approach doesn't apply. * {@description.close} */ int compare(K k1, K k2) throws ClassCastException { Comparator<? super K> cmp = comparator; if (cmp != null) return cmp.compare(k1, k2); else return ((Comparable<? super K>)k1).compareTo(k2); } /** {@collect.stats} * {@description.open} * Returns true if given key greater than or equal to least and * strictly less than fence, bypassing either test if least or * fence are null. Needed mainly in submap operations. * {@description.close} */ boolean inHalfOpenRange(K key, K least, K fence) { if (key == null) throw new NullPointerException(); return ((least == null || compare(key, least) >= 0) && (fence == null || compare(key, fence) < 0)); } /** {@collect.stats} * {@description.open} * Returns true if given key greater than or equal to least and less * or equal to fence. Needed mainly in submap operations. * {@description.close} */ boolean inOpenRange(K key, K least, K fence) { if (key == null) throw new NullPointerException(); return ((least == null || compare(key, least) >= 0) && (fence == null || compare(key, fence) <= 0)); } /* ---------------- Traversal -------------- */ /** {@collect.stats} * {@description.open} * Returns a base-level node with key strictly less than given key, * or the base-level header if there is no such node. Also * unlinks indexes to deleted nodes found along the way. Callers * rely on this side-effect of clearing indices to deleted nodes. * {@description.close} * @param key the key * @return a predecessor of key */ private Node<K,V> findPredecessor(Comparable<? super K> key) { if (key == null) throw new NullPointerException(); // don't postpone errors for (;;) { Index<K,V> q = head; Index<K,V> r = q.right; for (;;) { if (r != null) { Node<K,V> n = r.node; K k = n.key; if (n.value == null) { if (!q.unlink(r)) break; // restart r = q.right; // reread r continue; } if (key.compareTo(k) > 0) { q = r; r = r.right; continue; } } Index<K,V> d = q.down; if (d != null) { q = d; r = d.right; } else return q.node; } } } /** {@collect.stats} * {@description.open} * Returns node holding key or null if no such, clearing out any * deleted nodes seen along the way. Repeatedly traverses at * base-level looking for key starting at predecessor returned * from findPredecessor, processing base-level deletions as * encountered. Some callers rely on this side-effect of clearing * deleted nodes. * * Restarts occur, at traversal step centered on node n, if: * * (1) After reading n's next field, n is no longer assumed * predecessor b's current successor, which means that * we don't have a consistent 3-node snapshot and so cannot * unlink any subsequent deleted nodes encountered. * * (2) n's value field is null, indicating n is deleted, in * which case we help out an ongoing structural deletion * before retrying. Even though there are cases where such * unlinking doesn't require restart, they aren't sorted out * here because doing so would not usually outweigh cost of * restarting. * * (3) n is a marker or n's predecessor's value field is null, * indicating (among other possibilities) that * findPredecessor returned a deleted node. We can't unlink * the node because we don't know its predecessor, so rely * on another call to findPredecessor to notice and return * some earlier predecessor, which it will do. This check is * only strictly needed at beginning of loop, (and the * b.value check isn't strictly needed at all) but is done * each iteration to help avoid contention with other * threads by callers that will fail to be able to change * links, and so will retry anyway. * * The traversal loops in doPut, doRemove, and findNear all * include the same three kinds of checks. And specialized * versions appear in findFirst, and findLast and their * variants. They can't easily share code because each uses the * reads of fields held in locals occurring in the orders they * were performed. * {@description.close} * * @param key the key * @return node holding key, or null if no such */ private Node<K,V> findNode(Comparable<? super K> key) { for (;;) { Node<K,V> b = findPredecessor(key); Node<K,V> n = b.next; for (;;) { if (n == null) return null; Node<K,V> f = n.next; if (n != b.next) // inconsistent read break; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; int c = key.compareTo(n.key); if (c == 0) return n; if (c < 0) return null; b = n; n = f; } } } /** {@collect.stats} * {@description.open} * Specialized variant of findNode to perform Map.get. Does a weak * traversal, not bothering to fix any deleted index nodes, * returning early if it happens to see key in index, and passing * over any deleted base nodes, falling back to getUsingFindNode * only if it would otherwise return value from an ongoing * deletion. Also uses "bound" to eliminate need for some * comparisons (see Pugh Cookbook). Also folds uses of null checks * and node-skipping because markers have null keys. * {@description.close} * @param okey the key * @return the value, or null if absent */ private V doGet(Object okey) { Comparable<? super K> key = comparable(okey); Node<K,V> bound = null; Index<K,V> q = head; Index<K,V> r = q.right; Node<K,V> n; K k; int c; for (;;) { Index<K,V> d; // Traverse rights if (r != null && (n = r.node) != bound && (k = n.key) != null) { if ((c = key.compareTo(k)) > 0) { q = r; r = r.right; continue; } else if (c == 0) { Object v = n.value; return (v != null)? (V)v : getUsingFindNode(key); } else bound = n; } // Traverse down if ((d = q.down) != null) { q = d; r = d.right; } else break; } // Traverse nexts for (n = q.node.next; n != null; n = n.next) { if ((k = n.key) != null) { if ((c = key.compareTo(k)) == 0) { Object v = n.value; return (v != null)? (V)v : getUsingFindNode(key); } else if (c < 0) break; } } return null; } /** {@collect.stats} * {@description.open} * Performs map.get via findNode. Used as a backup if doGet * encounters an in-progress deletion. * {@description.close} * @param key the key * @return the value, or null if absent */ private V getUsingFindNode(Comparable<? super K> key) { /* * Loop needed here and elsewhere in case value field goes * null just as it is about to be returned, in which case we * lost a race with a deletion, so must retry. */ for (;;) { Node<K,V> n = findNode(key); if (n == null) return null; Object v = n.value; if (v != null) return (V)v; } } /* ---------------- Insertion -------------- */ /** {@collect.stats} * {@description.open} * Main insertion method. Adds element if not present, or * replaces value if present and onlyIfAbsent is false. * {@description.close} * @param kkey the key * @param value the value that must be associated with key * @param onlyIfAbsent if should not insert if already present * @return the old value, or null if newly inserted */ private V doPut(K kkey, V value, boolean onlyIfAbsent) { Comparable<? super K> key = comparable(kkey); for (;;) { Node<K,V> b = findPredecessor(key); Node<K,V> n = b.next; for (;;) { if (n != null) { Node<K,V> f = n.next; if (n != b.next) // inconsistent read break;; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; int c = key.compareTo(n.key); if (c > 0) { b = n; n = f; continue; } if (c == 0) { if (onlyIfAbsent || n.casValue(v, value)) return (V)v; else break; // restart if lost race to replace value } // else c < 0; fall through } Node<K,V> z = new Node<K,V>(kkey, value, n); if (!b.casNext(n, z)) break; // restart if lost race to append to b int level = randomLevel(); if (level > 0) insertIndex(z, level); return null; } } } /** {@collect.stats} * {@description.open} * Returns a random level for inserting a new node. * Hardwired to k=1, p=0.5, max 31 (see above and * Pugh's "Skip List Cookbook", sec 3.4). * * This uses the simplest of the generators described in George * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality * generator but is acceptable here. * {@description.close} */ private int randomLevel() { int x = randomSeed; x ^= x << 13; x ^= x >>> 17; randomSeed = x ^= x << 5; if ((x & 0x8001) != 0) // test highest and lowest bits return 0; int level = 1; while (((x >>>= 1) & 1) != 0) ++level; return level; } /** {@collect.stats} * {@description.open} * Creates and adds index nodes for the given node. * {@description.close} * @param z the node * @param level the level of the index */ private void insertIndex(Node<K,V> z, int level) { HeadIndex<K,V> h = head; int max = h.level; if (level <= max) { Index<K,V> idx = null; for (int i = 1; i <= level; ++i) idx = new Index<K,V>(z, idx, null); addIndex(idx, h, level); } else { // Add a new level /* * To reduce interference by other threads checking for * empty levels in tryReduceLevel, new levels are added * with initialized right pointers. Which in turn requires * keeping levels in an array to access them while * creating new head index nodes from the opposite * direction. */ level = max + 1; Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1]; Index<K,V> idx = null; for (int i = 1; i <= level; ++i) idxs[i] = idx = new Index<K,V>(z, idx, null); HeadIndex<K,V> oldh; int k; for (;;) { oldh = head; int oldLevel = oldh.level; if (level <= oldLevel) { // lost race to add level k = level; break; } HeadIndex<K,V> newh = oldh; Node<K,V> oldbase = oldh.node; for (int j = oldLevel+1; j <= level; ++j) newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j); if (casHead(oldh, newh)) { k = oldLevel; break; } } addIndex(idxs[k], oldh, k); } } /** {@collect.stats} * {@description.open} * Adds given index nodes from given level down to 1. * {@description.close} * @param idx the topmost index node being inserted * @param h the value of head to use to insert. This must be * snapshotted by callers to provide correct insertion level * @param indexLevel the level of the index */ private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) { // Track next level to insert in case of retries int insertionLevel = indexLevel; Comparable<? super K> key = comparable(idx.node.key); if (key == null) throw new NullPointerException(); // Similar to findPredecessor, but adding index nodes along // path to key. for (;;) { int j = h.level; Index<K,V> q = h; Index<K,V> r = q.right; Index<K,V> t = idx; for (;;) { if (r != null) { Node<K,V> n = r.node; // compare before deletion check avoids needing recheck int c = key.compareTo(n.key); if (n.value == null) { if (!q.unlink(r)) break; r = q.right; continue; } if (c > 0) { q = r; r = r.right; continue; } } if (j == insertionLevel) { // Don't insert index if node already deleted if (t.indexesDeletedNode()) { findNode(key); // cleans up return; } if (!q.link(r, t)) break; // restart if (--insertionLevel == 0) { // need final deletion check before return if (t.indexesDeletedNode()) findNode(key); return; } } if (--j >= insertionLevel && j < indexLevel) t = t.down; q = q.down; r = q.right; } } } /* ---------------- Deletion -------------- */ /** {@collect.stats} * {@description.open} * Main deletion method. Locates node, nulls value, appends a * deletion marker, unlinks predecessor, removes associated index * nodes, and possibly reduces head index level. * * Index nodes are cleared out simply by calling findPredecessor. * which unlinks indexes to deleted nodes found along path to key, * which will include the indexes to this node. This is done * unconditionally. We can't check beforehand whether there are * index nodes because it might be the case that some or all * indexes hadn't been inserted yet for this node during initial * search for it, and we'd like to ensure lack of garbage * retention, so must call to be sure. * {@description.close} * * @param okey the key * @param value if non-null, the value that must be * associated with key * @return the node, or null if not found */ final V doRemove(Object okey, Object value) { Comparable<? super K> key = comparable(okey); for (;;) { Node<K,V> b = findPredecessor(key); Node<K,V> n = b.next; for (;;) { if (n == null) return null; Node<K,V> f = n.next; if (n != b.next) // inconsistent read break; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; int c = key.compareTo(n.key); if (c < 0) return null; if (c > 0) { b = n; n = f; continue; } if (value != null && !value.equals(v)) return null; if (!n.casValue(v, null)) break; if (!n.appendMarker(f) || !b.casNext(n, f)) findNode(key); // Retry via findNode else { findPredecessor(key); // Clean index if (head.right == null) tryReduceLevel(); } return (V)v; } } } /** {@collect.stats} * {@description.open} * Possibly reduce head level if it has no nodes. This method can * (rarely) make mistakes, in which case levels can disappear even * though they are about to contain index nodes. This impacts * performance, not correctness. To minimize mistakes as well as * to reduce hysteresis, the level is reduced by one only if the * topmost three levels look empty. Also, if the removed level * looks non-empty after CAS, we try to change it back quick * before anyone notices our mistake! (This trick works pretty * well because this method will practically never make mistakes * unless current thread stalls immediately before first CAS, in * which case it is very unlikely to stall again immediately * afterwards, so will recover.) * * We put up with all this rather than just let levels grow * because otherwise, even a small map that has undergone a large * number of insertions and removals will have a lot of levels, * slowing down access more than would an occasional unwanted * reduction. * {@description.close} */ private void tryReduceLevel() { HeadIndex<K,V> h = head; HeadIndex<K,V> d; HeadIndex<K,V> e; if (h.level > 3 && (d = (HeadIndex<K,V>)h.down) != null && (e = (HeadIndex<K,V>)d.down) != null && e.right == null && d.right == null && h.right == null && casHead(h, d) && // try to set h.right != null) // recheck casHead(d, h); // try to backout } /* ---------------- Finding and removing first element -------------- */ /** {@collect.stats} * {@description.open} * Specialized variant of findNode to get first valid node. * {@description.close} * @return first node or null if empty */ Node<K,V> findFirst() { for (;;) { Node<K,V> b = head.node; Node<K,V> n = b.next; if (n == null) return null; if (n.value != null) return n; n.helpDelete(b, n.next); } } /** {@collect.stats} * {@description.open} * Removes first entry; returns its snapshot. * {@description.close} * @return null if empty, else snapshot of first entry */ Map.Entry<K,V> doRemoveFirstEntry() { for (;;) { Node<K,V> b = head.node; Node<K,V> n = b.next; if (n == null) return null; Node<K,V> f = n.next; if (n != b.next) continue; Object v = n.value; if (v == null) { n.helpDelete(b, f); continue; } if (!n.casValue(v, null)) continue; if (!n.appendMarker(f) || !b.casNext(n, f)) findFirst(); // retry clearIndexToFirst(); return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v); } } /** {@collect.stats} * {@description.open} * Clears out index nodes associated with deleted first entry. * {@description.close} */ private void clearIndexToFirst() { for (;;) { Index<K,V> q = head; for (;;) { Index<K,V> r = q.right; if (r != null && r.indexesDeletedNode() && !q.unlink(r)) break; if ((q = q.down) == null) { if (head.right == null) tryReduceLevel(); return; } } } } /* ---------------- Finding and removing last element -------------- */ /** {@collect.stats} * {@description.open} * Specialized version of find to get last valid node. * {@description.close} * @return last node or null if empty */ Node<K,V> findLast() { /* * findPredecessor can't be used to traverse index level * because this doesn't use comparisons. So traversals of * both levels are folded together. */ Index<K,V> q = head; for (;;) { Index<K,V> d, r; if ((r = q.right) != null) { if (r.indexesDeletedNode()) { q.unlink(r); q = head; // restart } else q = r; } else if ((d = q.down) != null) { q = d; } else { Node<K,V> b = q.node; Node<K,V> n = b.next; for (;;) { if (n == null) return (b.isBaseHeader())? null : b; Node<K,V> f = n.next; // inconsistent read if (n != b.next) break; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; b = n; n = f; } q = head; // restart } } } /** {@collect.stats} * {@description.open} * Specialized variant of findPredecessor to get predecessor of last * valid node. Needed when removing the last entry. It is possible * that all successors of returned node will have been deleted upon * return, in which case this method can be retried. * {@description.close} * @return likely predecessor of last node */ private Node<K,V> findPredecessorOfLast() { for (;;) { Index<K,V> q = head; for (;;) { Index<K,V> d, r; if ((r = q.right) != null) { if (r.indexesDeletedNode()) { q.unlink(r); break; // must restart } // proceed as far across as possible without overshooting if (r.node.next != null) { q = r; continue; } } if ((d = q.down) != null) q = d; else return q.node; } } } /** {@collect.stats} * {@description.open} * Removes last entry; returns its snapshot. * Specialized variant of doRemove. * {@description.close} * @return null if empty, else snapshot of last entry */ Map.Entry<K,V> doRemoveLastEntry() { for (;;) { Node<K,V> b = findPredecessorOfLast(); Node<K,V> n = b.next; if (n == null) { if (b.isBaseHeader()) // empty return null; else continue; // all b's successors are deleted; retry } for (;;) { Node<K,V> f = n.next; if (n != b.next) // inconsistent read break; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; if (f != null) { b = n; n = f; continue; } if (!n.casValue(v, null)) break; K key = n.key; Comparable<? super K> ck = comparable(key); if (!n.appendMarker(f) || !b.casNext(n, f)) findNode(ck); // Retry via findNode else { findPredecessor(ck); // Clean index if (head.right == null) tryReduceLevel(); } return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v); } } } /* ---------------- Relational operations -------------- */ // Control values OR'ed as arguments to findNear private static final int EQ = 1; private static final int LT = 2; private static final int GT = 0; // Actually checked as !LT /** {@collect.stats} * {@description.open} * Utility for ceiling, floor, lower, higher methods. * {@description.close} * @param kkey the key * @param rel the relation -- OR'ed combination of EQ, LT, GT * @return nearest node fitting relation, or null if no such */ Node<K,V> findNear(K kkey, int rel) { Comparable<? super K> key = comparable(kkey); for (;;) { Node<K,V> b = findPredecessor(key); Node<K,V> n = b.next; for (;;) { if (n == null) return ((rel & LT) == 0 || b.isBaseHeader())? null : b; Node<K,V> f = n.next; if (n != b.next) // inconsistent read break; Object v = n.value; if (v == null) { // n is deleted n.helpDelete(b, f); break; } if (v == n || b.value == null) // b is deleted break; int c = key.compareTo(n.key); if ((c == 0 && (rel & EQ) != 0) || (c < 0 && (rel & LT) == 0)) return n; if ( c <= 0 && (rel & LT) != 0) return (b.isBaseHeader())? null : b; b = n; n = f; } } } /** {@collect.stats} * {@description.open} * Returns SimpleImmutableEntry for results of findNear. * {@description.close} * @param key the key * @param rel the relation -- OR'ed combination of EQ, LT, GT * @return Entry fitting relation, or null if no such */ AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) { for (;;) { Node<K,V> n = findNear(key, rel); if (n == null) return null; AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); if (e != null) return e; } } /* ---------------- Constructors -------------- */ /** {@collect.stats} * {@description.open} * Constructs a new, empty map, sorted according to the * {@linkplain Comparable natural ordering} of the keys. * {@description.close} */ public ConcurrentSkipListMap() { this.comparator = null; initialize(); } /** {@collect.stats} * {@description.open} * Constructs a new, empty map, sorted according to the specified * comparator. * {@description.close} * * @param comparator the comparator that will be used to order this map. * If <tt>null</tt>, the {@linkplain Comparable natural * ordering} of the keys will be used. */ public ConcurrentSkipListMap(Comparator<? super K> comparator) { this.comparator = comparator; initialize(); } /** {@collect.stats} * {@description.open} * Constructs a new map containing the same mappings as the given map, * sorted according to the {@linkplain Comparable natural ordering} of * the keys. * {@description.close} * * @param m the map whose mappings are to be placed in this map * @throws ClassCastException if the keys in <tt>m</tt> are not * {@link Comparable}, or are not mutually comparable * @throws NullPointerException if the specified map or any of its keys * or values are null */ public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) { this.comparator = null; initialize(); putAll(m); } /** {@collect.stats} * {@description.open} * Constructs a new map containing the same mappings and using the * same ordering as the specified sorted map. * {@description.close} * * @param m the sorted map whose mappings are to be placed in this * map, and whose comparator is to be used to sort this map * @throws NullPointerException if the specified sorted map or any of * its keys or values are null */ public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) { this.comparator = m.comparator(); initialize(); buildFromSorted(m); } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt> * instance. (The keys and values themselves are not cloned.) * {@description.close} * * @return a shallow copy of this map */ public ConcurrentSkipListMap<K,V> clone() { ConcurrentSkipListMap<K,V> clone = null; try { clone = (ConcurrentSkipListMap<K,V>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } clone.initialize(); clone.buildFromSorted(this); return clone; } /** {@collect.stats} * {@description.open} * Streamlined bulk insertion to initialize from elements of * given sorted map. Call only from constructor or clone * method. * {@description.close} */ private void buildFromSorted(SortedMap<K, ? extends V> map) { if (map == null) throw new NullPointerException(); HeadIndex<K,V> h = head; Node<K,V> basepred = h.node; // Track the current rightmost node at each level. Uses an // ArrayList to avoid committing to initial or maximum level. ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>(); // initialize for (int i = 0; i <= h.level; ++i) preds.add(null); Index<K,V> q = h; for (int i = h.level; i > 0; --i) { preds.set(i, q); q = q.down; } Iterator<? extends Map.Entry<? extends K, ? extends V>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<? extends K, ? extends V> e = it.next(); int j = randomLevel(); if (j > h.level) j = h.level + 1; K k = e.getKey(); V v = e.getValue(); if (k == null || v == null) throw new NullPointerException(); Node<K,V> z = new Node<K,V>(k, v, null); basepred.next = z; basepred = z; if (j > 0) { Index<K,V> idx = null; for (int i = 1; i <= j; ++i) { idx = new Index<K,V>(z, idx, null); if (i > h.level) h = new HeadIndex<K,V>(h.node, h, idx, i); if (i < preds.size()) { preds.get(i).right = idx; preds.set(i, idx); } else preds.add(idx); } } } head = h; } /* ---------------- Serialization -------------- */ /** {@collect.stats} * {@description.open} * Save the state of this map to a stream. * {@description.close} * * @serialData The key (Object) and value (Object) for each * key-value mapping represented by the map, followed by * <tt>null</tt>. The key-value mappings are emitted in key-order * (as determined by the Comparator, or by the keys' natural * ordering if no Comparator). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out keys and values (alternating) for (Node<K,V> n = findFirst(); n != null; n = n.next) { V v = n.getValidValue(); if (v != null) { s.writeObject(n.key); s.writeObject(v); } } s.writeObject(null); } /** {@collect.stats} * {@description.open} * Reconstitute the map from a stream. * {@description.close} */ private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Reset transients initialize(); /* * This is nearly identical to buildFromSorted, but is * distinct because readObject calls can't be nicely adapted * as the kind of iterator needed by buildFromSorted. (They * can be, but doing so requires type cheats and/or creation * of adaptor classes.) It is simpler to just adapt the code. */ HeadIndex<K,V> h = head; Node<K,V> basepred = h.node; ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>(); for (int i = 0; i <= h.level; ++i) preds.add(null); Index<K,V> q = h; for (int i = h.level; i > 0; --i) { preds.set(i, q); q = q.down; } for (;;) { Object k = s.readObject(); if (k == null) break; Object v = s.readObject(); if (v == null) throw new NullPointerException(); K key = (K) k; V val = (V) v; int j = randomLevel(); if (j > h.level) j = h.level + 1; Node<K,V> z = new Node<K,V>(key, val, null); basepred.next = z; basepred = z; if (j > 0) { Index<K,V> idx = null; for (int i = 1; i <= j; ++i) { idx = new Index<K,V>(z, idx, null); if (i > h.level) h = new HeadIndex<K,V>(h.node, h, idx, i); if (i < preds.size()) { preds.get(i).right = idx; preds.set(i, idx); } else preds.add(idx); } } } head = h; } /* ------ Map API methods ------ */ /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the specified * key. * {@description.close} * * @param key key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null */ public boolean containsKey(Object key) { return doGet(key) != null; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code key} compares * equal to {@code k} according to the map's ordering, then this * method returns {@code v}; otherwise it returns {@code null}. * (There can be at most one such mapping.) * {@description.close} * * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null */ public V get(Object key) { return doGet(key); } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * {@description.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * <tt>null</tt> if there was no mapping for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key or value is null */ public V put(K key, V value) { if (value == null) throw new NullPointerException(); return doPut(key, value, false); } /** {@collect.stats} * {@description.open} * Removes the mapping for the specified key from this map if present. * {@description.close} * * @param key key for which mapping should be removed * @return the previous value associated with the specified key, or * <tt>null</tt> if there was no mapping for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null */ public V remove(Object key) { return doRemove(key, null); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. This operation requires time linear in the * map size. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; * <tt>false</tt> otherwise * @throws NullPointerException if the specified value is null */ public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); for (Node<K,V> n = findFirst(); n != null; n = n.next) { V v = n.getValidValue(); if (v != null && value.equals(v)) return true; } return false; } /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. If this map * contains more than <tt>Integer.MAX_VALUE</tt> elements, it * returns <tt>Integer.MAX_VALUE</tt>. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these maps, determining the current * number of elements requires traversing them all to count them. * Additionally, it is possible for the size to change during * execution of this method, in which case the returned result * will be inaccurate. Thus, this method is typically not very * useful in concurrent applications. * {@description.close} * * @return the number of elements in this map */ public int size() { long count = 0; for (Node<K,V> n = findFirst(); n != null; n = n.next) { if (n.getValidValue() != null) ++count; } return (count >= Integer.MAX_VALUE)? Integer.MAX_VALUE : (int)count; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains no key-value mappings. * {@description.close} * @return <tt>true</tt> if this map contains no key-value mappings */ public boolean isEmpty() { return findFirst() == null; } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * {@description.close} */ public void clear() { initialize(); } /* ---------------- View methods -------------- */ /* * Note: Lazy initialization works for views because view classes * are stateless/immutable so it doesn't matter wrt correctness if * more than one is created (which will only rarely happen). Even * so, the following idiom conservatively ensures that the method * returns the one it created if it does so, not one created by * another racing thread. */ /** {@collect.stats} * {@description.open} * Returns a {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} * operations. It does not support the {@code add} or {@code addAll} * operations. * {@description.close} * * {@property.open synchronized} * <p>The view's {@code 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. * {@property.close} * * {@description.open} * <p>This method is equivalent to method {@code navigableKeySet}. * {@description.close} * * @return a navigable set view of the keys in this map */ public NavigableSet<K> keySet() { KeySet ks = keySet; return (ks != null) ? ks : (keySet = new KeySet(this)); } public NavigableSet<K> navigableKeySet() { KeySet ks = keySet; return (ks != null) ? ks : (keySet = new KeySet(this)); } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection's iterator returns the values in ascending order * of the corresponding keys. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@description.close} * * {@property.open synchronized} * <p>The view's <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. * {@property.close} */ public Collection<V> values() { Values vs = values; return (vs != null) ? vs : (values = new Values(this)); } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set's iterator returns the entries in ascending key order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or * <tt>addAll</tt> operations. * {@description.close} * * {@property.open synchronized} * <p>The view's <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. * {@property.close} * * {@description.open} * <p>The <tt>Map.Entry</tt> elements returned by * <tt>iterator.next()</tt> do <em>not</em> support the * <tt>setValue</tt> operation. * {@description.close} * * @return a set view of the mappings contained in this map, * sorted in ascending key order */ public Set<Map.Entry<K,V>> entrySet() { EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet(this)); } public ConcurrentNavigableMap<K,V> descendingMap() { ConcurrentNavigableMap<K,V> dm = descendingMap; return (dm != null) ? dm : (descendingMap = new SubMap<K,V> (this, null, false, null, false, true)); } public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /* ---------------- AbstractMap Overrides -------------- */ /** {@collect.stats} * {@description.open} * Compares the specified object with this map for equality. * Returns <tt>true</tt> if the given object is also a map and the * two maps represent the same mappings. More formally, two maps * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if * <tt>m1.entrySet().equals(m2.entrySet())</tt>. * {@description.close} * {@property.open synchronized} * This * operation may return misleading results if either map is * concurrently modified during execution of this method. * {@property.close} * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map<?,?> m = (Map<?,?>) o; try { for (Map.Entry<K,V> e : this.entrySet()) if (! e.getValue().equals(m.get(e.getKey()))) return false; for (Map.Entry<?,?> e : m.entrySet()) { Object k = e.getKey(); Object v = e.getValue(); if (k == null || v == null || !v.equals(get(k))) return false; } return true; } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } /* ------ ConcurrentMap API methods ------ */ /** {@collect.stats} * {@inheritDoc} * * @return the previous value associated with the specified key, * or <tt>null</tt> if there was no mapping for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) throw new NullPointerException(); return doPut(key, value, true); } /** {@collect.stats} * {@inheritDoc} * * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { if (key == null) throw new NullPointerException(); if (value == null) return false; return doRemove(key, value) != null; } /** {@collect.stats} * {@inheritDoc} * * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) throw new NullPointerException(); Comparable<? super K> k = comparable(key); for (;;) { Node<K,V> n = findNode(k); if (n == null) return false; Object v = n.value; if (v != null) { if (!oldValue.equals(v)) return false; if (n.casValue(v, newValue)) return true; } } } /** {@collect.stats} * {@inheritDoc} * * @return the previous value associated with the specified key, * or <tt>null</tt> if there was no mapping for the key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) throw new NullPointerException(); Comparable<? super K> k = comparable(key); for (;;) { Node<K,V> n = findNode(k); if (n == null) return null; Object v = n.value; if (v != null && n.casValue(v, value)) return (V)v; } } /* ------ SortedMap API methods ------ */ public Comparator<? super K> comparator() { return comparator; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public K firstKey() { Node<K,V> n = findFirst(); if (n == null) throw new NoSuchElementException(); return n.key; } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public K lastKey() { Node<K,V> n = findLast(); if (n == null) throw new NoSuchElementException(); return n.key; } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromKey} or {@code toKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (fromKey == null || toKey == null) throw new NullPointerException(); return new SubMap<K,V> (this, fromKey, fromInclusive, toKey, toInclusive, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return new SubMap<K,V> (this, null, false, toKey, inclusive, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return new SubMap<K,V> (this, fromKey, inclusive, null, false, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromKey} or {@code toKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> headMap(K toKey) { return headMap(toKey, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromKey} is null * @throws IllegalArgumentException {@inheritDoc} */ public ConcurrentNavigableMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } /* ---------------- Relational operations -------------- */ /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest key * strictly less than the given key, or <tt>null</tt> if there is * no such key. The returned entry does <em>not</em> support the * <tt>Entry.setValue</tt> method. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public Map.Entry<K,V> lowerEntry(K key) { return getNear(key, LT); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public K lowerKey(K key) { Node<K,V> n = findNear(key, LT); return (n == null)? null : n.key; } /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest key * less than or equal to the given key, or <tt>null</tt> if there * is no such key. The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} * * @param key the key * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public Map.Entry<K,V> floorEntry(K key) { return getNear(key, LT|EQ); } /** {@collect.stats} * @param key the key * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public K floorKey(K key) { Node<K,V> n = findNear(key, LT|EQ); return (n == null)? null : n.key; } /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least key * greater than or equal to the given key, or <tt>null</tt> if * there is no such entry. The returned entry does <em>not</em> * support the <tt>Entry.setValue</tt> method. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public Map.Entry<K,V> ceilingEntry(K key) { return getNear(key, GT|EQ); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public K ceilingKey(K key) { Node<K,V> n = findNear(key, GT|EQ); return (n == null)? null : n.key; } /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least key * strictly greater than the given key, or <tt>null</tt> if there * is no such key. The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} * * @param key the key * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public Map.Entry<K,V> higherEntry(K key) { return getNear(key, GT); } /** {@collect.stats} * @param key the key * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified key is null */ public K higherKey(K key) { Node<K,V> n = findNear(key, GT); return (n == null)? null : n.key; } /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least * key in this map, or <tt>null</tt> if the map is empty. * The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} */ public Map.Entry<K,V> firstEntry() { for (;;) { Node<K,V> n = findFirst(); if (n == null) return null; AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); if (e != null) return e; } } /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest * key in this map, or <tt>null</tt> if the map is empty. * The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} */ public Map.Entry<K,V> lastEntry() { for (;;) { Node<K,V> n = findLast(); if (n == null) return null; AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); if (e != null) return e; } } /** {@collect.stats} * {@description.open} * Removes and returns a key-value mapping associated with * the least key in this map, or <tt>null</tt> if the map is empty. * The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} */ public Map.Entry<K,V> pollFirstEntry() { return doRemoveFirstEntry(); } /** {@collect.stats} * {@description.open} * Removes and returns a key-value mapping associated with * the greatest key in this map, or <tt>null</tt> if the map is empty. * The returned entry does <em>not</em> support * the <tt>Entry.setValue</tt> method. * {@description.close} */ public Map.Entry<K,V> pollLastEntry() { return doRemoveLastEntry(); } /* ---------------- Iterators -------------- */ /** {@collect.stats} * {@description.open} * Base of iterator classes: * {@description.close} */ abstract class Iter<T> implements Iterator<T> { /** {@collect.stats} * {@description.open} * the last node returned by next() * {@description.close} */ Node<K,V> lastReturned; /** {@collect.stats} * {@description.open} * the next node to return from next(); * {@description.close} */ Node<K,V> next; /** {@collect.stats} * {@description.open} * Cache of next value field to maintain weak consistency * {@description.close} */ V nextValue; /** {@collect.stats} * {@description.open} * Initializes ascending iterator for entire range. * {@description.close} */ Iter() { for (;;) { next = findFirst(); if (next == null) break; Object x = next.value; if (x != null && x != next) { nextValue = (V) x; break; } } } public final boolean hasNext() { return next != null; } /** {@collect.stats} * {@description.open} * Advances next to higher entry. * {@description.close} */ final void advance() { if (next == null) throw new NoSuchElementException(); lastReturned = next; for (;;) { next = next.next; if (next == null) break; Object x = next.value; if (x != null && x != next) { nextValue = (V) x; break; } } } public void remove() { Node<K,V> l = lastReturned; if (l == null) throw new IllegalStateException(); // It would not be worth all of the overhead to directly // unlink from here. Using remove is fast enough. ConcurrentSkipListMap.this.remove(l.key); lastReturned = null; } } final class ValueIterator extends Iter<V> { public V next() { V v = nextValue; advance(); return v; } } final class KeyIterator extends Iter<K> { public K next() { Node<K,V> n = next; advance(); return n.key; } } final class EntryIterator extends Iter<Map.Entry<K,V>> { public Map.Entry<K,V> next() { Node<K,V> n = next; V v = nextValue; advance(); return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); } } // Factory methods for iterators needed by ConcurrentSkipListSet etc Iterator<K> keyIterator() { return new KeyIterator(); } Iterator<V> valueIterator() { return new ValueIterator(); } Iterator<Map.Entry<K,V>> entryIterator() { return new EntryIterator(); } /* ---------------- View Classes -------------- */ /* * View classes are static, delegating to a ConcurrentNavigableMap * to allow use by SubMaps, which outweighs the ugliness of * needing type-tests for Iterator methods. */ static final <E> List<E> toList(Collection<E> c) { // Using size() here would be a pessimization. List<E> list = new ArrayList<E>(); for (E e : c) list.add(e); return list; } static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> { private final ConcurrentNavigableMap<E,Object> m; KeySet(ConcurrentNavigableMap<E,Object> map) { m = map; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public boolean remove(Object o) { return m.remove(o) != null; } public void clear() { m.clear(); } public E lower(E e) { return m.lowerKey(e); } public E floor(E e) { return m.floorKey(e); } public E ceiling(E e) { return m.ceilingKey(e); } public E higher(E e) { return m.higherKey(e); } public Comparator<? super E> comparator() { return m.comparator(); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public E pollFirst() { Map.Entry<E,Object> e = m.pollFirstEntry(); return e == null? null : e.getKey(); } public E pollLast() { Map.Entry<E,Object> e = m.pollLastEntry(); return e == null? null : e.getKey(); } public Iterator<E> iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap<E,Object>)m).keyIterator(); else return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator(); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; try { return containsAll(c) && c.containsAll(this); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } public Object[] toArray() { return toList(this).toArray(); } public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } public Iterator<E> descendingIterator() { return descendingSet().iterator(); } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new KeySet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new KeySet<E>(m.headMap(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new KeySet<E>(m.tailMap(fromElement, inclusive)); } public NavigableSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } public NavigableSet<E> headSet(E toElement) { return headSet(toElement, false); } public NavigableSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public NavigableSet<E> descendingSet() { return new KeySet(m.descendingMap()); } } static final class Values<E> extends AbstractCollection<E> { private final ConcurrentNavigableMap<Object, E> m; Values(ConcurrentNavigableMap<Object, E> map) { m = map; } public Iterator<E> iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap<Object,E>)m).valueIterator(); else return ((SubMap<Object,E>)m).valueIterator(); } public boolean isEmpty() { return m.isEmpty(); } public int size() { return m.size(); } public boolean contains(Object o) { return m.containsValue(o); } public void clear() { m.clear(); } public Object[] toArray() { return toList(this).toArray(); } public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } } static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> { private final ConcurrentNavigableMap<K1, V1> m; EntrySet(ConcurrentNavigableMap<K1, V1> map) { m = map; } public Iterator<Map.Entry<K1,V1>> iterator() { if (m instanceof ConcurrentSkipListMap) return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator(); else return ((SubMap<K1,V1>)m).entryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o; V1 v = m.get(e.getKey()); return v != null && v.equals(e.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o; return m.remove(e.getKey(), e.getValue()); } public boolean isEmpty() { return m.isEmpty(); } public int size() { return m.size(); } public void clear() { m.clear(); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; try { return containsAll(c) && c.containsAll(this); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } public Object[] toArray() { return toList(this).toArray(); } public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } } /** {@collect.stats} * {@description.open} * Submaps returned by {@link ConcurrentSkipListMap} submap operations * represent a subrange of mappings of their underlying * maps. Instances of this class support all methods of their * underlying maps, differing in that mappings outside their range are * ignored, and attempts to add mappings outside their ranges result * in {@link IllegalArgumentException}. Instances of this class are * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and * <tt>tailMap</tt> methods of their underlying maps. * {@description.close} * * @serial include */ static final class SubMap<K,V> extends AbstractMap<K,V> implements ConcurrentNavigableMap<K,V>, Cloneable, java.io.Serializable { private static final long serialVersionUID = -7647078645895051609L; /** {@collect.stats} * {@description.open} * Underlying map * {@description.close} */ private final ConcurrentSkipListMap<K,V> m; /** {@collect.stats} * {@description.open} * lower bound key, or null if from start * {@description.close} */ private final K lo; /** {@collect.stats} * {@description.open} * upper bound key, or null if to end * {@description.close} */ private final K hi; /** {@collect.stats} * {@description.open} * inclusion flag for lo * {@description.close} */ private final boolean loInclusive; /** {@collect.stats} * {@description.open} * inclusion flag for hi * {@description.close} */ private final boolean hiInclusive; /** {@collect.stats} * {@description.open} * direction * {@description.close} */ private final boolean isDescending; // Lazily initialized view holders private transient KeySet<K> keySetView; private transient Set<Map.Entry<K,V>> entrySetView; private transient Collection<V> valuesView; /** {@collect.stats} * {@description.open} * Creates a new submap, initializing all fields * {@description.close} */ SubMap(ConcurrentSkipListMap<K,V> map, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, boolean isDescending) { if (fromKey != null && toKey != null && map.compare(fromKey, toKey) > 0) throw new IllegalArgumentException("inconsistent range"); this.m = map; this.lo = fromKey; this.hi = toKey; this.loInclusive = fromInclusive; this.hiInclusive = toInclusive; this.isDescending = isDescending; } /* ---------------- Utilities -------------- */ private boolean tooLow(K key) { if (lo != null) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } private boolean tooHigh(K key) { if (hi != null) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } private boolean inBounds(K key) { return !tooLow(key) && !tooHigh(key); } private void checkKeyBounds(K key) throws IllegalArgumentException { if (key == null) throw new NullPointerException(); if (!inBounds(key)) throw new IllegalArgumentException("key out of range"); } /** {@collect.stats} * {@description.open} * Returns true if node key is less than upper bound of range * {@description.close} */ private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) { if (n == null) return false; if (hi == null) return true; K k = n.key; if (k == null) // pass by markers and headers return true; int c = m.compare(k, hi); if (c > 0 || (c == 0 && !hiInclusive)) return false; return true; } /** {@collect.stats} * {@description.open} * Returns lowest node. This node might not be in range, so * most usages need to check bounds * {@description.close} */ private ConcurrentSkipListMap.Node<K,V> loNode() { if (lo == null) return m.findFirst(); else if (loInclusive) return m.findNear(lo, m.GT|m.EQ); else return m.findNear(lo, m.GT); } /** {@collect.stats} * {@description.open} * Returns highest node. This node might not be in range, so * most usages need to check bounds * {@description.close} */ private ConcurrentSkipListMap.Node<K,V> hiNode() { if (hi == null) return m.findLast(); else if (hiInclusive) return m.findNear(hi, m.LT|m.EQ); else return m.findNear(hi, m.LT); } /** {@collect.stats} * {@description.open} * Returns lowest absolute key (ignoring directonality) * {@description.close} */ private K lowestKey() { ConcurrentSkipListMap.Node<K,V> n = loNode(); if (isBeforeEnd(n)) return n.key; else throw new NoSuchElementException(); } /** {@collect.stats} * {@description.open} * Returns highest absolute key (ignoring directonality) * {@description.close} */ private K highestKey() { ConcurrentSkipListMap.Node<K,V> n = hiNode(); if (n != null) { K last = n.key; if (inBounds(last)) return last; } throw new NoSuchElementException(); } private Map.Entry<K,V> lowestEntry() { for (;;) { ConcurrentSkipListMap.Node<K,V> n = loNode(); if (!isBeforeEnd(n)) return null; Map.Entry<K,V> e = n.createSnapshot(); if (e != null) return e; } } private Map.Entry<K,V> highestEntry() { for (;;) { ConcurrentSkipListMap.Node<K,V> n = hiNode(); if (n == null || !inBounds(n.key)) return null; Map.Entry<K,V> e = n.createSnapshot(); if (e != null) return e; } } private Map.Entry<K,V> removeLowest() { for (;;) { Node<K,V> n = loNode(); if (n == null) return null; K k = n.key; if (!inBounds(k)) return null; V v = m.doRemove(k, null); if (v != null) return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); } } private Map.Entry<K,V> removeHighest() { for (;;) { Node<K,V> n = hiNode(); if (n == null) return null; K k = n.key; if (!inBounds(k)) return null; V v = m.doRemove(k, null); if (v != null) return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); } } /** {@collect.stats} * {@description.open} * Submap version of ConcurrentSkipListMap.getNearEntry * {@description.close} */ private Map.Entry<K,V> getNearEntry(K key, int rel) { if (isDescending) { // adjust relation for direction if ((rel & m.LT) == 0) rel |= m.LT; else rel &= ~m.LT; } if (tooLow(key)) return ((rel & m.LT) != 0)? null : lowestEntry(); if (tooHigh(key)) return ((rel & m.LT) != 0)? highestEntry() : null; for (;;) { Node<K,V> n = m.findNear(key, rel); if (n == null || !inBounds(n.key)) return null; K k = n.key; V v = n.getValidValue(); if (v != null) return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); } } // Almost the same as getNearEntry, except for keys private K getNearKey(K key, int rel) { if (isDescending) { // adjust relation for direction if ((rel & m.LT) == 0) rel |= m.LT; else rel &= ~m.LT; } if (tooLow(key)) { if ((rel & m.LT) == 0) { ConcurrentSkipListMap.Node<K,V> n = loNode(); if (isBeforeEnd(n)) return n.key; } return null; } if (tooHigh(key)) { if ((rel & m.LT) != 0) { ConcurrentSkipListMap.Node<K,V> n = hiNode(); if (n != null) { K last = n.key; if (inBounds(last)) return last; } } return null; } for (;;) { Node<K,V> n = m.findNear(key, rel); if (n == null || !inBounds(n.key)) return null; K k = n.key; V v = n.getValidValue(); if (v != null) return k; } } /* ---------------- Map API methods -------------- */ public boolean containsKey(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return inBounds(k) && m.containsKey(k); } public V get(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return ((!inBounds(k)) ? null : m.get(k)); } public V put(K key, V value) { checkKeyBounds(key); return m.put(key, value); } public V remove(Object key) { K k = (K)key; return (!inBounds(k))? null : m.remove(k); } public int size() { long count = 0; for (ConcurrentSkipListMap.Node<K,V> n = loNode(); isBeforeEnd(n); n = n.next) { if (n.getValidValue() != null) ++count; } return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count; } public boolean isEmpty() { return !isBeforeEnd(loNode()); } public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); for (ConcurrentSkipListMap.Node<K,V> n = loNode(); isBeforeEnd(n); n = n.next) { V v = n.getValidValue(); if (v != null && value.equals(v)) return true; } return false; } public void clear() { for (ConcurrentSkipListMap.Node<K,V> n = loNode(); isBeforeEnd(n); n = n.next) { if (n.getValidValue() != null) m.remove(n.key); } } /* ---------------- ConcurrentMap API methods -------------- */ public V putIfAbsent(K key, V value) { checkKeyBounds(key); return m.putIfAbsent(key, value); } public boolean remove(Object key, Object value) { K k = (K)key; return inBounds(k) && m.remove(k, value); } public boolean replace(K key, V oldValue, V newValue) { checkKeyBounds(key); return m.replace(key, oldValue, newValue); } public V replace(K key, V value) { checkKeyBounds(key); return m.replace(key, value); } /* ---------------- SortedMap API methods -------------- */ public Comparator<? super K> comparator() { Comparator<? super K> cmp = m.comparator(); if (isDescending) return Collections.reverseOrder(cmp); else return cmp; } /** {@collect.stats} * {@description.open} * Utility to create submaps, where given bounds override * unbounded(null) ones and/or are checked against bounded ones. * {@description.close} */ private SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (isDescending) { // flip senses K tk = fromKey; fromKey = toKey; toKey = tk; boolean ti = fromInclusive; fromInclusive = toInclusive; toInclusive = ti; } if (lo != null) { if (fromKey == null) { fromKey = lo; fromInclusive = loInclusive; } else { int c = m.compare(fromKey, lo); if (c < 0 || (c == 0 && !loInclusive && fromInclusive)) throw new IllegalArgumentException("key out of range"); } } if (hi != null) { if (toKey == null) { toKey = hi; toInclusive = hiInclusive; } else { int c = m.compare(toKey, hi); if (c > 0 || (c == 0 && !hiInclusive && toInclusive)) throw new IllegalArgumentException("key out of range"); } } return new SubMap<K,V>(m, fromKey, fromInclusive, toKey, toInclusive, isDescending); } public SubMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (fromKey == null || toKey == null) throw new NullPointerException(); return newSubMap(fromKey, fromInclusive, toKey, toInclusive); } public SubMap<K,V> headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return newSubMap(null, false, toKey, inclusive); } public SubMap<K,V> tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return newSubMap(fromKey, inclusive, null, false); } public SubMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } public SubMap<K,V> headMap(K toKey) { return headMap(toKey, false); } public SubMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } public SubMap<K,V> descendingMap() { return new SubMap<K,V>(m, lo, loInclusive, hi, hiInclusive, !isDescending); } /* ---------------- Relational methods -------------- */ public Map.Entry<K,V> ceilingEntry(K key) { return getNearEntry(key, (m.GT|m.EQ)); } public K ceilingKey(K key) { return getNearKey(key, (m.GT|m.EQ)); } public Map.Entry<K,V> lowerEntry(K key) { return getNearEntry(key, (m.LT)); } public K lowerKey(K key) { return getNearKey(key, (m.LT)); } public Map.Entry<K,V> floorEntry(K key) { return getNearEntry(key, (m.LT|m.EQ)); } public K floorKey(K key) { return getNearKey(key, (m.LT|m.EQ)); } public Map.Entry<K,V> higherEntry(K key) { return getNearEntry(key, (m.GT)); } public K higherKey(K key) { return getNearKey(key, (m.GT)); } public K firstKey() { return isDescending? highestKey() : lowestKey(); } public K lastKey() { return isDescending? lowestKey() : highestKey(); } public Map.Entry<K,V> firstEntry() { return isDescending? highestEntry() : lowestEntry(); } public Map.Entry<K,V> lastEntry() { return isDescending? lowestEntry() : highestEntry(); } public Map.Entry<K,V> pollFirstEntry() { return isDescending? removeHighest() : removeLowest(); } public Map.Entry<K,V> pollLastEntry() { return isDescending? removeLowest() : removeHighest(); } /* ---------------- Submap Views -------------- */ public NavigableSet<K> keySet() { KeySet<K> ks = keySetView; return (ks != null) ? ks : (keySetView = new KeySet(this)); } public NavigableSet<K> navigableKeySet() { KeySet<K> ks = keySetView; return (ks != null) ? ks : (keySetView = new KeySet(this)); } public Collection<V> values() { Collection<V> vs = valuesView; return (vs != null) ? vs : (valuesView = new Values(this)); } public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySetView; return (es != null) ? es : (entrySetView = new EntrySet(this)); } public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } Iterator<K> keyIterator() { return new SubMapKeyIterator(); } Iterator<V> valueIterator() { return new SubMapValueIterator(); } Iterator<Map.Entry<K,V>> entryIterator() { return new SubMapEntryIterator(); } /** {@collect.stats} * {@description.open} * Variant of main Iter class to traverse through submaps. * {@description.close} */ abstract class SubMapIter<T> implements Iterator<T> { /** {@collect.stats} * {@description.open} * the last node returned by next() * {@description.close} */ Node<K,V> lastReturned; /** {@collect.stats} * {@description.open} * the next node to return from next(); * {@description.close} */ Node<K,V> next; /** {@collect.stats} * {@description.open} * Cache of next value field to maintain weak consistency * {@description.close} */ V nextValue; SubMapIter() { for (;;) { next = isDescending ? hiNode() : loNode(); if (next == null) break; Object x = next.value; if (x != null && x != next) { if (! inBounds(next.key)) next = null; else nextValue = (V) x; break; } } } public final boolean hasNext() { return next != null; } final void advance() { if (next == null) throw new NoSuchElementException(); lastReturned = next; if (isDescending) descend(); else ascend(); } private void ascend() { for (;;) { next = next.next; if (next == null) break; Object x = next.value; if (x != null && x != next) { if (tooHigh(next.key)) next = null; else nextValue = (V) x; break; } } } private void descend() { for (;;) { next = m.findNear(lastReturned.key, LT); if (next == null) break; Object x = next.value; if (x != null && x != next) { if (tooLow(next.key)) next = null; else nextValue = (V) x; break; } } } public void remove() { Node<K,V> l = lastReturned; if (l == null) throw new IllegalStateException(); m.remove(l.key); lastReturned = null; } } final class SubMapValueIterator extends SubMapIter<V> { public V next() { V v = nextValue; advance(); return v; } } final class SubMapKeyIterator extends SubMapIter<K> { public K next() { Node<K,V> n = next; advance(); return n.key; } } final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> { public Map.Entry<K,V> next() { Node<K,V> n = next; V v = nextValue; advance(); return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); } } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.atomic.*; import java.util.*; /** {@collect.stats} * {@description.open} * An {@link ExecutorService} that can schedule commands to run after a given * delay, or to execute periodically. * * <p> The <tt>schedule</tt> methods create tasks with various delays * and return a task object that can be used to cancel or check * execution. The <tt>scheduleAtFixedRate</tt> and * <tt>scheduleWithFixedDelay</tt> methods create and execute tasks * that run periodically until cancelled. * * <p> Commands submitted using the {@link Executor#execute} and * {@link ExecutorService} <tt>submit</tt> methods are scheduled with * a requested delay of zero. Zero and negative delays (but not * periods) are also allowed in <tt>schedule</tt> methods, and are * treated as requests for immediate execution. * * <p>All <tt>schedule</tt> methods accept <em>relative</em> delays and * periods as arguments, not absolute times or dates. It is a simple * matter to transform an absolute time represented as a {@link * java.util.Date} to the required form. For example, to schedule at * a certain future <tt>date</tt>, you can use: <tt>schedule(task, * date.getTime() - System.currentTimeMillis(), * TimeUnit.MILLISECONDS)</tt>. Beware however that expiration of a * relative delay need not coincide with the current <tt>Date</tt> at * which the task is enabled due to network time synchronization * protocols, clock drift, or other factors. * * The {@link Executors} class provides convenient factory methods for * the ScheduledExecutorService implementations provided in this package. * * <h3>Usage Example</h3> * * Here is a class with a method that sets up a ScheduledExecutorService * to beep every ten seconds for an hour: * * <pre> * import static java.util.concurrent.TimeUnit.*; * class BeeperControl { * private final ScheduledExecutorService scheduler = * Executors.newScheduledThreadPool(1); * * public void beepForAnHour() { * final Runnable beeper = new Runnable() { * public void run() { System.out.println("beep"); } * }; * final ScheduledFuture&lt;?&gt; beeperHandle = * scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); * scheduler.schedule(new Runnable() { * public void run() { beeperHandle.cancel(true); } * }, 60 * 60, SECONDS); * } * } * </pre> * {@description.close} * * @since 1.5 * @author Doug Lea */ public interface ScheduledExecutorService extends ExecutorService { /** {@collect.stats} * {@description.open} * Creates and executes a one-shot action that becomes enabled * after the given delay. * {@description.close} * * @param command the task to execute * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter * @return a ScheduledFuture representing pending completion of * the task and whose <tt>get()</tt> method will return * <tt>null</tt> upon completion * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if command is null */ public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); /** {@collect.stats} * {@description.open} * Creates and executes a ScheduledFuture that becomes enabled after the * given delay. * {@description.close} * * @param callable the function to execute * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter * @return a ScheduledFuture that can be used to extract result or cancel * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if callable is null */ public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); /** {@collect.stats} * {@description.open} * Creates and executes a periodic action that becomes enabled first * after the given initial delay, and subsequently with the given * period; that is executions will commence after * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then * <tt>initialDelay + 2 * period</tt>, and so on. * If any execution of the task * encounters an exception, subsequent executions are suppressed. * Otherwise, the task will only terminate via cancellation or * termination of the executor. If any execution of this task * takes longer than its period, then subsequent executions * may start late, but will not concurrently execute. * {@description.close} * * @param command the task to execute * @param initialDelay the time to delay first execution * @param period the period between successive executions * @param unit the time unit of the initialDelay and period parameters * @return a ScheduledFuture representing pending completion of * the task, and whose <tt>get()</tt> method will throw an * exception upon cancellation * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if command is null * @throws IllegalArgumentException if period less than or equal to zero */ public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); /** {@collect.stats} * {@description.open} * Creates and executes a periodic action that becomes enabled first * after the given initial delay, and subsequently with the * given delay between the termination of one execution and the * commencement of the next. If any execution of the task * encounters an exception, subsequent executions are suppressed. * Otherwise, the task will only terminate via cancellation or * termination of the executor. * {@description.close} * * @param command the task to execute * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one * execution and the commencement of the next * @param unit the time unit of the initialDelay and delay parameters * @return a ScheduledFuture representing pending completion of * the task, and whose <tt>get()</tt> method will throw an * exception upon cancellation * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if command is null * @throws IllegalArgumentException if delay less than or equal to zero */ public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A service that decouples the production of new asynchronous tasks * from the consumption of the results of completed tasks. Producers * <tt>submit</tt> tasks for execution. Consumers <tt>take</tt> * completed tasks and process their results in the order they * complete. A <tt>CompletionService</tt> can for example be used to * manage asynchronous IO, in which tasks that perform reads are * submitted in one part of a program or system, and then acted upon * in a different part of the program when the reads complete, * possibly in a different order than they were requested. * * <p>Typically, a <tt>CompletionService</tt> relies on a separate * {@link Executor} to actually execute the tasks, in which case the * <tt>CompletionService</tt> only manages an internal completion * queue. The {@link ExecutorCompletionService} class provides an * implementation of this approach. * * <p>Memory consistency effects: Actions in a thread prior to * submitting a task to a {@code CompletionService} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions taken by that task, which in turn <i>happen-before</i> * actions following a successful return from the corresponding {@code take()}. * * {@description.close} */ public interface CompletionService<V> { /** {@collect.stats} * {@description.open} * Submits a value-returning task for execution and returns a Future * representing the pending results of the task. Upon completion, * this task may be taken or polled. * {@description.close} * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ Future<V> submit(Callable<V> task); /** {@collect.stats} * {@description.open} * Submits a Runnable task for execution and returns a Future * representing that task. Upon completion, this task may be * taken or polled. * {@description.close} * * @param task the task to submit * @param result the result to return upon successful completion * @return a Future representing pending completion of the task, * and whose <tt>get()</tt> method will return the given * result value upon completion * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ Future<V> submit(Runnable task, V result); /** {@collect.stats} * {@description.open} * Retrieves and removes the Future representing the next * completed task, waiting if none are yet present. * {@description.close} * * @return the Future representing the next completed task * @throws InterruptedException if interrupted while waiting */ Future<V> take() throws InterruptedException; /** {@collect.stats} * {@description.open} * Retrieves and removes the Future representing the next * completed task or <tt>null</tt> if none are present. * {@description.close} * * @return the Future representing the next completed task, or * <tt>null</tt> if none are present */ Future<V> poll(); /** {@collect.stats} * {@description.open} * Retrieves and removes the Future representing the next * completed task, waiting if necessary up to the specified wait * time if none are yet present. * {@description.close} * * @param timeout how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter * @return the Future representing the next completed task or * <tt>null</tt> if the specified waiting time elapses * before one is present * @throws InterruptedException if interrupted while waiting */ Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException; }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import java.security.AccessControlException; import sun.security.util.SecurityConstants; /** {@collect.stats} * {@description.open} * Factory and utility methods for {@link Executor}, {@link * ExecutorService}, {@link ScheduledExecutorService}, {@link * ThreadFactory}, and {@link Callable} classes defined in this * package. This class supports the following kinds of methods: * * <ul> * <li> Methods that create and return an {@link ExecutorService} * set up with commonly useful configuration settings. * <li> Methods that create and return a {@link ScheduledExecutorService} * set up with commonly useful configuration settings. * <li> Methods that create and return a "wrapped" ExecutorService, that * disables reconfiguration by making implementation-specific methods * inaccessible. * <li> Methods that create and return a {@link ThreadFactory} * that sets newly created threads to a known state. * <li> Methods that create and return a {@link Callable} * out of other closure-like forms, so they can be used * in execution methods requiring <tt>Callable</tt>. * </ul> * {@description.close} * * @since 1.5 * @author Doug Lea */ public class Executors { /** {@collect.stats} * {@description.open} * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. At any point, at most * <tt>nThreads</tt> threads will be active processing tasks. * If additional tasks are submitted when all threads are active, * they will wait in the queue until a thread is available. * If any thread terminates due to a failure during execution * prior to shutdown, a new one will take its place if needed to * execute subsequent tasks. The threads in the pool will exist * until it is explicitly {@link ExecutorService#shutdown shutdown}. * {@description.close} * * @param nThreads the number of threads in the pool * @return the newly created thread pool * @throws IllegalArgumentException if <tt>nThreads &lt;= 0</tt> */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } /** {@collect.stats} * {@description.open} * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue, using the provided * ThreadFactory to create new threads when needed. At any point, * at most <tt>nThreads</tt> threads will be active processing * tasks. If additional tasks are submitted when all threads are * active, they will wait in the queue until a thread is * available. If any thread terminates due to a failure during * execution prior to shutdown, a new one will take its place if * needed to execute subsequent tasks. The threads in the pool will * exist until it is explicitly {@link ExecutorService#shutdown * shutdown}. * {@description.close} * * @param nThreads the number of threads in the pool * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool * @throws NullPointerException if threadFactory is null * @throws IllegalArgumentException if <tt>nThreads &lt;= 0</tt> */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } /** {@collect.stats} * {@description.open} * Creates an Executor that uses a single worker thread operating * off an unbounded queue. (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * <tt>newFixedThreadPool(1)</tt> the returned executor is * guaranteed not to be reconfigurable to use additional threads. * {@description.close} * * @return the newly created single-threaded Executor */ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } /** {@collect.stats} * {@description.open} * Creates an Executor that uses a single worker thread operating * off an unbounded queue, and uses the provided ThreadFactory to * create a new thread when needed. Unlike the otherwise * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the * returned executor is guaranteed not to be reconfigurable to use * additional threads. * {@description.close} * * @param threadFactory the factory to use when creating new * threads * * @return the newly created single-threaded Executor * @throws NullPointerException if threadFactory is null */ public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory)); } /** {@collect.stats} * {@description.open} * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available. These pools will typically improve the performance * of programs that execute many short-lived asynchronous tasks. * Calls to <tt>execute</tt> will reuse previously constructed * threads if available. If no existing thread is available, a new * thread will be created and added to the pool. Threads that have * not been used for sixty seconds are terminated and removed from * the cache. Thus, a pool that remains idle for long enough will * not consume any resources. Note that pools with similar * properties but different details (for example, timeout parameters) * may be created using {@link ThreadPoolExecutor} constructors. * {@description.close} * * @return the newly created thread pool */ public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } /** {@collect.stats} * {@description.open} * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available, and uses the provided * ThreadFactory to create new threads when needed. * {@description.close} * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool * @throws NullPointerException if threadFactory is null */ public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); } /** {@collect.stats} * {@description.open} * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. * (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * <tt>newScheduledThreadPool(1)</tt> the returned executor is * guaranteed not to be reconfigurable to use additional threads. * {@description.close} * @return the newly created scheduled executor */ public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); } /** {@collect.stats} * {@description.open} * Creates a single-threaded executor that can schedule commands * to run after a given delay, or to execute periodically. (Note * however that if this single thread terminates due to a failure * during execution prior to shutdown, a new one will take its * place if needed to execute subsequent tasks.) Tasks are * guaranteed to execute sequentially, and no more than one task * will be active at any given time. Unlike the otherwise * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt> * the returned executor is guaranteed not to be reconfigurable to * use additional threads. * {@description.close} * @param threadFactory the factory to use when creating new * threads * @return a newly created scheduled executor * @throws NullPointerException if threadFactory is null */ public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1, threadFactory)); } /** {@collect.stats} * {@description.open} * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * {@description.close} * @param corePoolSize the number of threads to keep in the pool, * even if they are idle. * @return a newly created scheduled thread pool * @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt> */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } /** {@collect.stats} * {@description.open} * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * {@description.close} * @param corePoolSize the number of threads to keep in the pool, * even if they are idle. * @param threadFactory the factory to use when the executor * creates a new thread. * @return a newly created scheduled thread pool * @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt> * @throws NullPointerException if threadFactory is null */ public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } /** {@collect.stats} * {@description.open} * Returns an object that delegates all defined {@link * ExecutorService} methods to the given executor, but not any * other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * {@description.close} * @param executor the underlying implementation * @return an <tt>ExecutorService</tt> instance * @throws NullPointerException if executor null */ public static ExecutorService unconfigurableExecutorService(ExecutorService executor) { if (executor == null) throw new NullPointerException(); return new DelegatedExecutorService(executor); } /** {@collect.stats} * {@description.open} * Returns an object that delegates all defined {@link * ScheduledExecutorService} methods to the given executor, but * not any other methods that might otherwise be accessible using * casts. This provides a way to safely "freeze" configuration and * disallow tuning of a given concrete implementation. * {@description.close} * @param executor the underlying implementation * @return a <tt>ScheduledExecutorService</tt> instance * @throws NullPointerException if executor null */ public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) { if (executor == null) throw new NullPointerException(); return new DelegatedScheduledExecutorService(executor); } /** {@collect.stats} * {@description.open} * Returns a default thread factory used to create new threads. * This factory creates all new threads used by an Executor in the * same {@link ThreadGroup}. If there is a {@link * java.lang.SecurityManager}, it uses the group of {@link * System#getSecurityManager}, else the group of the thread * invoking this <tt>defaultThreadFactory</tt> method. Each new * thread is created as a non-daemon thread with priority set to * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum * priority permitted in the thread group. New threads have names * accessible via {@link Thread#getName} of * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence * number of this factory, and <em>M</em> is the sequence number * of the thread created by this factory. * {@description.close} * @return a thread factory */ public static ThreadFactory defaultThreadFactory() { return new DefaultThreadFactory(); } /** {@collect.stats} * {@description.open} * Returns a thread factory used to create new threads that * have the same permissions as the current thread. * This factory creates threads with the same settings as {@link * Executors#defaultThreadFactory}, additionally setting the * AccessControlContext and contextClassLoader of new threads to * be the same as the thread invoking this * <tt>privilegedThreadFactory</tt> method. A new * <tt>privilegedThreadFactory</tt> can be created within an * {@link AccessController#doPrivileged} action setting the * current thread's access control context to create threads with * the selected permission settings holding within that action. * * <p> Note that while tasks running within such threads will have * the same access control and class loader settings as the * current thread, they need not have the same {@link * java.lang.ThreadLocal} or {@link * java.lang.InheritableThreadLocal} values. If necessary, * particular values of thread locals can be set or reset before * any task runs in {@link ThreadPoolExecutor} subclasses using * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is * necessary to initialize worker threads to have the same * InheritableThreadLocal settings as some other designated * thread, you can create a custom ThreadFactory in which that * thread waits for and services requests to create others that * will inherit its values. * {@description.close} * * @return a thread factory * @throws AccessControlException if the current access control * context does not have permission to both get and set context * class loader. */ public static ThreadFactory privilegedThreadFactory() { return new PrivilegedThreadFactory(); } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that, when * called, runs the given task and returns the given result. This * can be useful when applying methods requiring a * <tt>Callable</tt> to an otherwise resultless action. * {@description.close} * @param task the task to run * @param result the result to return * @return a callable object * @throws NullPointerException if task null */ public static <T> Callable<T> callable(Runnable task, T result) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<T>(task, result); } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that, when * called, runs the given task and returns <tt>null</tt>. * {@description.close} * @param task the task to run * @return a callable object * @throws NullPointerException if task null */ public static Callable<Object> callable(Runnable task) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<Object>(task, null); } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that, when * called, runs the given privileged action and returns its result. * {@description.close} * @param action the privileged action to run * @return a callable object * @throws NullPointerException if action null */ public static Callable<Object> callable(final PrivilegedAction<?> action) { if (action == null) throw new NullPointerException(); return new Callable<Object>() { public Object call() { return action.run(); }}; } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that, when * called, runs the given privileged exception action and returns * its result. * {@description.close} * @param action the privileged exception action to run * @return a callable object * @throws NullPointerException if action null */ public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) { if (action == null) throw new NullPointerException(); return new Callable<Object>() { public Object call() throws Exception { return action.run(); }}; } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that will, when * called, execute the given <tt>callable</tt> under the current * access control context. This method should normally be * invoked within an {@link AccessController#doPrivileged} action * to create callables that will, if possible, execute under the * selected permission settings holding within that action; or if * not possible, throw an associated {@link * AccessControlException}. * {@description.close} * @param callable the underlying task * @return a callable object * @throws NullPointerException if callable null * */ public static <T> Callable<T> privilegedCallable(Callable<T> callable) { if (callable == null) throw new NullPointerException(); return new PrivilegedCallable<T>(callable); } /** {@collect.stats} * {@description.open} * Returns a {@link Callable} object that will, when * called, execute the given <tt>callable</tt> under the current * access control context, with the current context class loader * as the context class loader. This method should normally be * invoked within an {@link AccessController#doPrivileged} action * to create callables that will, if possible, execute under the * selected permission settings holding within that action; or if * not possible, throw an associated {@link * AccessControlException}. * {@description.close} * @param callable the underlying task * * @return a callable object * @throws NullPointerException if callable null * @throws AccessControlException if the current access control * context does not have permission to both set and get context * class loader. */ public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) { if (callable == null) throw new NullPointerException(); return new PrivilegedCallableUsingCurrentClassLoader<T>(callable); } // Non-public classes supporting the public methods /** {@collect.stats} * {@description.open} * A callable that runs given task and returns given result * {@description.close} */ static final class RunnableAdapter<T> implements Callable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } } /** {@collect.stats} * {@description.open} * A callable that runs under established access control settings * {@description.close} */ static final class PrivilegedCallable<T> implements Callable<T> { private final Callable<T> task; private final AccessControlContext acc; PrivilegedCallable(Callable<T> task) { this.task = task; this.acc = AccessController.getContext(); } public T call() throws Exception { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<T>() { public T run() throws Exception { return task.call(); } }, acc); } catch (PrivilegedActionException e) { throw e.getException(); } } } /** {@collect.stats} * {@description.open} * A callable that runs under established access control settings and * current ClassLoader * {@description.close} */ static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> { private final Callable<T> task; private final AccessControlContext acc; private final ClassLoader ccl; PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Calls to getContextClassLoader from this class // never trigger a security check, but we check // whether our callers have this permission anyways. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); // Whether setContextClassLoader turns out to be necessary // or not, we fail fast if permission is not available. sm.checkPermission(new RuntimePermission("setContextClassLoader")); } this.task = task; this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } public T call() throws Exception { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<T>() { public T run() throws Exception { ClassLoader savedcl = null; Thread t = Thread.currentThread(); try { ClassLoader cl = t.getContextClassLoader(); if (ccl != cl) { t.setContextClassLoader(ccl); savedcl = cl; } return task.call(); } finally { if (savedcl != null) t.setContextClassLoader(savedcl); } } }, acc); } catch (PrivilegedActionException e) { throw e.getException(); } } } /** {@collect.stats} * {@description.open} * The default thread factory * {@description.close} */ static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null)? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } /** {@collect.stats} * {@description.open} * Thread factory capturing access control context and class loader * {@description.close} */ static class PrivilegedThreadFactory extends DefaultThreadFactory { private final AccessControlContext acc; private final ClassLoader ccl; PrivilegedThreadFactory() { super(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Calls to getContextClassLoader from this class // never trigger a security check, but we check // whether our callers have this permission anyways. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); // Fail fast sm.checkPermission(new RuntimePermission("setContextClassLoader")); } this.acc = AccessController.getContext(); this.ccl = Thread.currentThread().getContextClassLoader(); } public Thread newThread(final Runnable r) { return super.newThread(new Runnable() { public void run() { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { Thread.currentThread().setContextClassLoader(ccl); r.run(); return null; } }, acc); } }); } } /** {@collect.stats} * {@description.open} * A wrapper class that exposes only the ExecutorService methods * of an ExecutorService implementation. * {@description.close} */ static class DelegatedExecutorService extends AbstractExecutorService { private final ExecutorService e; DelegatedExecutorService(ExecutorService executor) { e = executor; } public void execute(Runnable command) { e.execute(command); } public void shutdown() { e.shutdown(); } public List<Runnable> shutdownNow() { return e.shutdownNow(); } public boolean isShutdown() { return e.isShutdown(); } public boolean isTerminated() { return e.isTerminated(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return e.awaitTermination(timeout, unit); } public Future<?> submit(Runnable task) { return e.submit(task); } public <T> Future<T> submit(Callable<T> task) { return e.submit(task); } public <T> Future<T> submit(Runnable task, T result) { return e.submit(task, result); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return e.invokeAll(tasks); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return e.invokeAll(tasks, timeout, unit); } public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return e.invokeAny(tasks); } public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return e.invokeAny(tasks, timeout, unit); } } static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } protected void finalize() { super.shutdown(); } } /** {@collect.stats} * {@description.open} * A wrapper class that exposes only the ScheduledExecutorService * methods of a ScheduledExecutorService implementation. * {@description.close} */ static class DelegatedScheduledExecutorService extends DelegatedExecutorService implements ScheduledExecutorService { private final ScheduledExecutorService e; DelegatedScheduledExecutorService(ScheduledExecutorService executor) { super(executor); e = executor; } public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return e.schedule(command, delay, unit); } public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return e.schedule(callable, delay, unit); } public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return e.scheduleAtFixedRate(command, initialDelay, period, unit); } public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return e.scheduleWithFixedDelay(command, initialDelay, delay, unit); } } /** {@collect.stats} * {@description.open} * Cannot instantiate. * {@description.close} */ private Executors() {} }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.*; /** {@collect.stats} * {@description.open} * A {@link ConcurrentMap} supporting {@link NavigableMap} operations, * and recursively so for its navigable sub-maps. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Doug Lea * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * @since 1.6 */ public interface ConcurrentNavigableMap<K,V> extends ConcurrentMap<K,V>, NavigableMap<K,V> { /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive); /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> headMap(K toKey, boolean inclusive); /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> tailMap(K fromKey, boolean inclusive); /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey); /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> headMap(K toKey); /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ ConcurrentNavigableMap<K,V> tailMap(K fromKey); /** {@collect.stats} * {@description.open} * Returns a reverse order view of the mappings contained in this map. * The descending map is backed by this map, so changes to the map are * reflected in the descending map, and vice-versa. * * <p>The returned map has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. * The expression {@code m.descendingMap().descendingMap()} returns a * view of {@code m} essentially equivalent to {@code m}. * {@description.close} * * @return a reverse order view of this map */ ConcurrentNavigableMap<K,V> descendingMap(); /** {@collect.stats} * {@description.open} * Returns a {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} * operations. It does not support the {@code add} or {@code addAll} * operations. * {@description.close} * * {@property.open synchronized} * <p>The view's {@code 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. * {@property.close} * * @return a navigable set view of the keys in this map */ public NavigableSet<K> navigableKeySet(); /** {@collect.stats} * {@description.open} * Returns a {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} * operations. It does not support the {@code add} or {@code addAll} * operations. * {@description.close} * * {@property.open synchronized} * <p>The view's {@code 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. * {@property.close} * * {@description.open} * <p>This method is equivalent to method {@code navigableKeySet}. * {@description.close} * * @return a navigable set view of the keys in this map */ NavigableSet<K> keySet(); /** {@collect.stats} * {@description.open} * Returns a reverse order {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in descending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} * operations. It does not support the {@code add} or {@code addAll} * operations. * {@description.close} * * {@property.open synchronized} * <p>The view's {@code 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. * {@property.close} * * @return a reverse order navigable set view of the keys in this map */ public NavigableSet<K> descendingKeySet(); }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * A delayed result-bearing action that can be cancelled. * Usually a scheduled future is the result of scheduling * a task with a {@link ScheduledExecutorService}. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <V> The result type returned by this Future */ public interface ScheduledFuture<V> extends Delayed, Future<V> { }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; import java.util.concurrent.locks.*; import java.util.*; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** {@collect.stats} * {@description.open} * A hash table supporting full concurrency of retrievals and * adjustable expected concurrency for updates. This class obeys the * same functional specification as {@link java.util.Hashtable}, and * includes versions of methods corresponding to each method of * <tt>Hashtable</tt>. However, even though all operations are * thread-safe, retrieval operations do <em>not</em> entail locking, * and there is <em>not</em> any support for locking the entire table * in a way that prevents all access. This class is fully * interoperable with <tt>Hashtable</tt> in programs that rely on its * thread safety but not on its synchronization details. * * <p> Retrieval operations (including <tt>get</tt>) generally do not * block, so may overlap with update operations (including * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results * of the most recently <em>completed</em> update operations holding * upon their onset. For aggregate operations such as <tt>putAll</tt> * and <tt>clear</tt>, concurrent retrievals may reflect insertion or * removal of only some entries. Similarly, Iterators and * Enumerations return elements reflecting the state of the hash table * at some point at or since the creation of the iterator/enumeration. * {@description.close} * {@property.open synchronized} * They do <em>not</em> throw {@link ConcurrentModificationException}. * However, iterators are designed to be used by only one thread at a time. * {@property.close} * * {@description.open} * <p> The allowed concurrency among update operations is guided by * the optional <tt>concurrencyLevel</tt> constructor argument * (default <tt>16</tt>), which is used as a hint for internal sizing. The * table is internally partitioned to try to permit the indicated * number of concurrent updates without contention. Because placement * in hash tables is essentially random, the actual concurrency will * vary. Ideally, you should choose a value to accommodate as many * threads as will ever concurrently modify the table. Using a * significantly higher value than you need can waste space and time, * and a significantly lower value can lead to thread contention. But * overestimates and underestimates within an order of magnitude do * not usually have much noticeable impact. A value of one is * appropriate when it is known that only one thread will modify and * all others will only read. Also, resizing this or any other kind of * hash table is a relatively slow operation, so, when possible, it is * a good idea to provide estimates of expected table sizes in * constructors. * * <p>This class and its views and iterators implement all of the * <em>optional</em> methods of the {@link Map} and {@link Iterator} * interfaces. * {@description.close} * * {@property.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class * does <em>not</em> allow <tt>null</tt> to be used as a key or value. * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Doug Lea * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values */ public class ConcurrentHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable { private static final long serialVersionUID = 7249069246763182397L; /* * The basic strategy is to subdivide the table among Segments, * each of which itself is a concurrently readable hash table. */ /* ---------------- Constants -------------- */ /** {@collect.stats} * {@description.open} * The default initial capacity for this table, * used when not otherwise specified in a constructor. * {@description.close} */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** {@collect.stats} * {@description.open} * The default load factor for this table, used when not * otherwise specified in a constructor. * {@description.close} */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** {@collect.stats} * {@description.open} * The default concurrency level for this table, used when not * otherwise specified in a constructor. * {@description.close} */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** {@collect.stats} * {@description.open} * The maximum capacity, used if a higher value is implicitly * specified by either of the constructors with arguments. MUST * be a power of two <= 1<<30 to ensure that entries are indexable * using ints. * {@description.close} */ static final int MAXIMUM_CAPACITY = 1 << 30; /** {@collect.stats} * {@description.open} * The maximum number of segments to allow; used to bound * constructor arguments. * {@description.close} */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** {@collect.stats} * {@description.open} * Number of unsynchronized retries in size and containsValue * methods before resorting to locking. This is used to avoid * unbounded retries if tables undergo continuous modification * which would make it impossible to obtain an accurate result. * {@description.close} */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** {@collect.stats} * {@description.open} * Mask value for indexing into segments. The upper bits of a * key's hash code are used to choose the segment. * {@description.close} */ final int segmentMask; /** {@collect.stats} * {@description.open} * Shift value for indexing within segments. * {@description.close} */ final int segmentShift; /** {@collect.stats} * {@description.open} * The segments, each of which is a specialized hash table * {@description.close} */ final Segment<K,V>[] segments; transient Set<K> keySet; transient Set<Map.Entry<K,V>> entrySet; transient Collection<V> values; /* ---------------- Small Utilities -------------- */ /** {@collect.stats} * {@description.open} * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because ConcurrentHashMap uses power-of-two length hash tables, * that otherwise encounter collisions for hashCodes that do not * differ in lower or upper bits. * {@description.close} */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } /** {@collect.stats} * {@description.open} * Returns the segment that should be used for key with given hash * {@description.close} * @param hash the hash code for the key * @return the segment */ final Segment<K,V> segmentFor(int hash) { return segments[(hash >>> segmentShift) & segmentMask]; } /* ---------------- Inner Classes -------------- */ /** {@collect.stats} * {@description.open} * ConcurrentHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. * {@description.close} */ static final class HashEntry<K,V> { final K key; final int hash; volatile V value; final HashEntry<K,V> next; HashEntry(K key, int hash, HashEntry<K,V> next, V value) { this.key = key; this.hash = hash; this.next = next; this.value = value; } @SuppressWarnings("unchecked") static final <K,V> HashEntry<K,V>[] newArray(int i) { return new HashEntry[i]; } } /** {@collect.stats} * {@description.open} * Segments are specialized versions of hash tables. This * subclasses from ReentrantLock opportunistically, just to * simplify some locking and avoid separate construction. * {@description.close} */ static final class Segment<K,V> extends ReentrantLock implements Serializable { /* * Segments maintain a table of entry lists that are ALWAYS * kept in a consistent state, so can be read without locking. * Next fields of nodes are immutable (final). All list * additions are performed at the front of each bin. This * makes it easy to check changes, and also fast to traverse. * When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables * since the bin lists tend to be short. (The average length * is less than two for the default load factor threshold.) * * Read operations can thus proceed without locking, but rely * on selected uses of volatiles to ensure that completed * write operations performed by other threads are * noticed. For most purposes, the "count" field, tracking the * number of elements, serves as that volatile variable * ensuring visibility. This is convenient because this field * needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the * count field are marked in code comments. */ private static final long serialVersionUID = 2249069246763182397L; /** {@collect.stats} * {@description.open} * The number of elements in this segment's region. * {@description.close} */ transient volatile int count; /** {@collect.stats} * {@description.open} * Number of updates that alter the size of the table. This is * used during bulk-read methods to make sure they see a * consistent snapshot: If modCounts change during a traversal * of segments computing size or checking containsValue, then * we might have an inconsistent view of state so (usually) * must retry. * {@description.close} */ transient int modCount; /** {@collect.stats} * {@description.open} * The table is rehashed when its size exceeds this threshold. * (The value of this field is always <tt>(int)(capacity * * loadFactor)</tt>.) * {@description.close} */ transient int threshold; /** {@collect.stats} * {@description.open} * The per-segment table. * {@description.close} */ transient volatile HashEntry<K,V>[] table; /** {@collect.stats} * {@description.open} * The load factor for the hash table. Even though this value * is same for all segments, it is replicated to avoid needing * links to outer object. * {@description.close} * @serial */ final float loadFactor; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry.<K,V>newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final <K,V> Segment<K,V>[] newArray(int i) { return new Segment[i]; } /** {@collect.stats} * {@description.open} * Sets table to new HashEntry array. * Call only while holding lock or in constructor. * {@description.close} */ void setTable(HashEntry<K,V>[] newTable) { threshold = (int)(newTable.length * loadFactor); table = newTable; } /** {@collect.stats} * {@description.open} * Returns properly casted first entry of bin for given hash. * {@description.close} */ HashEntry<K,V> getFirst(int hash) { HashEntry<K,V>[] tab = table; return tab[hash & (tab.length - 1)]; } /** {@collect.stats} * {@description.open} * Reads value field of an entry under lock. Called if value * field ever appears to be null. This is possible only if a * compiler happens to reorder a HashEntry initialization with * its table assignment, which is legal under memory model * but is not known to ever occur. * {@description.close} */ V readValueUnderLock(HashEntry<K,V> e) { lock(); try { return e.value; } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry<K,V> e = getFirst(hash); while (e != null) { if (e.hash == hash && key.equals(e.key)) { V v = e.value; if (v != null) return v; return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry<K,V> e = getFirst(hash); while (e != null) { if (e.hash == hash && key.equals(e.key)) return true; e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry<K,V>[] tab = table; int len = tab.length; for (int i = 0 ; i < len; i++) { for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) { V v = e.value; if (v == null) // recheck v = readValueUnderLock(e); if (value.equals(v)) return true; } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { HashEntry<K,V> e = getFirst(hash); while (e != null && (e.hash != hash || !key.equals(e.key))) e = e.next; boolean replaced = false; if (e != null && oldValue.equals(e.value)) { replaced = true; e.value = newValue; } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { HashEntry<K,V> e = getFirst(hash); while (e != null && (e.hash != hash || !key.equals(e.key))) e = e.next; V oldValue = null; if (e != null) { oldValue = e.value; e.value = newValue; } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { int c = count; if (c++ > threshold) // ensure capacity rehash(); HashEntry<K,V>[] tab = table; int index = hash & (tab.length - 1); HashEntry<K,V> first = tab[index]; HashEntry<K,V> e = first; while (e != null && (e.hash != hash || !key.equals(e.key))) e = e.next; V oldValue; if (e != null) { oldValue = e.value; if (!onlyIfAbsent) e.value = value; } else { oldValue = null; ++modCount; tab[index] = new HashEntry<K,V>(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } void rehash() { HashEntry<K,V>[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) return; /* * Reclassify nodes in each list to new Map. Because we are * using power-of-two expansion, the elements from each bin * must either stay at same index, or move with a power of two * offset. We eliminate unnecessary node creation by catching * cases where old nodes can be reused because their next * fields won't change. Statistically, at the default * threshold, only about one-sixth of them need cloning when * a table doubles. The nodes they replace will be garbage * collectable as soon as they are no longer referenced by any * reader thread that may be in the midst of traversing table * right now. */ HashEntry<K,V>[] newTable = HashEntry.newArray(oldCapacity<<1); threshold = (int)(newTable.length * loadFactor); int sizeMask = newTable.length - 1; for (int i = 0; i < oldCapacity ; i++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry<K,V> e = oldTable[i]; if (e != null) { HashEntry<K,V> next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) newTable[idx] = e; else { // Reuse trailing consecutive sequence at same slot HashEntry<K,V> lastRun = e; int lastIdx = idx; for (HashEntry<K,V> last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry<K,V> p = e; p != lastRun; p = p.next) { int k = p.hash & sizeMask; HashEntry<K,V> n = newTable[k]; newTable[k] = new HashEntry<K,V>(p.key, p.hash, n, p.value); } } } } table = newTable; } /** {@collect.stats} * {@description.open} * Remove; match on key only if value null, else match both. * {@description.close} */ V remove(Object key, int hash, Object value) { lock(); try { int c = count - 1; HashEntry<K,V>[] tab = table; int index = hash & (tab.length - 1); HashEntry<K,V> first = tab[index]; HashEntry<K,V> e = first; while (e != null && (e.hash != hash || !key.equals(e.key))) e = e.next; V oldValue = null; if (e != null) { V v = e.value; if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay // in list, but all preceding ones need to be // cloned. ++modCount; HashEntry<K,V> newFirst = e.next; for (HashEntry<K,V> p = first; p != e; p = p.next) newFirst = new HashEntry<K,V>(p.key, p.hash, newFirst, p.value); tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } void clear() { if (count != 0) { lock(); try { HashEntry<K,V>[] tab = table; for (int i = 0; i < tab.length ; i++) tab[i] = null; ++modCount; count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** {@collect.stats} * {@description.open} * Creates a new, empty map with the specified initial * capacity, load factor and concurrency level. * {@description.close} * * @param initialCapacity the initial capacity. The implementation * performs internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of elements per * bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently * updating threads. The implementation performs internal sizing * to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is * negative or the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) throw new IllegalArgumentException(); if (concurrencyLevel > MAX_SEGMENTS) concurrencyLevel = MAX_SEGMENTS; // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; int c = initialCapacity / ssize; if (c * ssize < initialCapacity) ++c; int cap = 1; while (cap < c) cap <<= 1; for (int i = 0; i < this.segments.length; ++i) this.segments[i] = new Segment<K,V>(cap, loadFactor); } /** {@collect.stats} * {@description.open} * Creates a new, empty map with the specified initial capacity * and load factor and with the default concurrencyLevel (16). * {@description.close} * * @param initialCapacity The implementation performs internal * sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of elements per * bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of * elements is negative or the load factor is nonpositive * * @since 1.6 */ public ConcurrentHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** {@collect.stats} * {@description.open} * Creates a new, empty map with the specified initial capacity, * and with default load factor (0.75) and concurrencyLevel (16). * {@description.close} * * @param initialCapacity the initial capacity. The implementation * performs internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of * elements is negative. */ public ConcurrentHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** {@collect.stats} * {@description.open} * Creates a new, empty map with a default initial capacity (16), * load factor (0.75) and concurrencyLevel (16). * {@description.close} */ public ConcurrentHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** {@collect.stats} * {@description.open} * Creates a new map with the same mappings as the given map. * The map is created with a capacity of 1.5 times the number * of mappings in the given map or 16 (whichever is greater), * and a default load factor (0.75) and concurrencyLevel (16). * {@description.close} * * @param m the map */ public ConcurrentHashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains no key-value mappings. * {@description.close} * * @return <tt>true</tt> if this map contains no key-value mappings */ public boolean isEmpty() { final Segment<K,V>[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA * problems in which an element in one segment was added and * in another removed during traversal, in which case the * table was never actually empty at any point. Note the * similar use of modCounts in the size() and containsValue() * methods, which are the only other methods also susceptible * to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++i) { if (segments[i].count != 0) return false; else mcsum += mc[i] = segments[i].modCount; } // If mcsum happens to be zero, then we know we got a snapshot // before any modifications at all were made. This is // probably common enough to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) return false; } } return true; } /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. If the * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * {@description.close} * * @return the number of key-value mappings in this map */ public int size() { final Segment<K,V>[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to // continuous async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) break; } if (check != sum) { // Resort to locking all segments sum = 0; for (int i = 0; i < segments.length; ++i) segments[i].lock(); for (int i = 0; i < segments.length; ++i) sum += segments[i].count; for (int i = 0; i < segments.length; ++i) segments[i].unlock(); } if (sum > Integer.MAX_VALUE) return Integer.MAX_VALUE; else return (int)sum; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code key.equals(k)}, * then this method returns {@code v}; otherwise it returns * {@code null}. (There can be at most one such mapping.) * {@description.close} * * @throws NullPointerException if the specified key is null */ public V get(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).get(key, hash); } /** {@collect.stats} * {@description.open} * Tests if the specified object is a key in this table. * {@description.close} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @param key possible key * @return <tt>true</tt> if and only if the specified object * is a key in this table, as determined by the * <tt>equals</tt> method; <tt>false</tt> otherwise. * @throws NullPointerException if the specified key is null */ public boolean containsKey(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).containsKey(key, hash); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. Note: This method requires a full internal * traversal of the hash table, and so is much slower than * method <tt>containsKey</tt>. * {@description.close} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified value is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value * @throws NullPointerException if the specified value is null */ public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); // See explanation of modCount use above final Segment<K,V>[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) { int sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++i) { int c = segments[i].count; mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) return true; } boolean cleanSweep = true; if (mcsum != 0) { for (int i = 0; i < segments.length; ++i) { int c = segments[i].count; if (mc[i] != segments[i].modCount) { cleanSweep = false; break; } } } if (cleanSweep) return false; } // Resort to locking all segments for (int i = 0; i < segments.length; ++i) segments[i].lock(); boolean found = false; try { for (int i = 0; i < segments.length; ++i) { if (segments[i].containsValue(value)) { found = true; break; } } } finally { for (int i = 0; i < segments.length; ++i) segments[i].unlock(); } return found; } /** {@collect.stats} * {@description.open} * Legacy method testing if some key maps into the specified value * in this table. This method is identical in functionality to * {@link #containsValue}, and exists solely to ensure * full compatibility with class {@link java.util.Hashtable}, * which supported this method prior to introduction of the * Java Collections framework. * {@description.close} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified value is null, a runtime exception is raised. * {@new.close} * {@property.close} * @param value a value to search for * @return <tt>true</tt> if and only if some key maps to the * <tt>value</tt> argument in this table as * determined by the <tt>equals</tt> method; * <tt>false</tt> otherwise * @throws NullPointerException if the specified value is null */ public boolean contains(Object value) { return containsValue(value); } /** {@collect.stats} * {@description.open} * Maps the specified key to the specified value in this table. * Neither the key nor the value can be null. * * <p> The value can be retrieved by calling the <tt>get</tt> method * with a key that is equal to the original key. * {@description.close} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key or value is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt> * @throws NullPointerException if the specified key or value is null */ public V put(K key, V value) { if (value == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).put(key, hash, value, false); } /** {@collect.stats} * {@inheritDoc} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key or value is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @return the previous value associated with the specified key, * or <tt>null</tt> if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).put(key, hash, value, true); } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this one. * These mappings replace any mappings that this map had for any of the * keys currently in the specified map. * {@description.close} * * @param m mappings to be stored in this map */ public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** {@collect.stats} * {@description.open} * Removes the key (and its corresponding value) from this map. * This method does nothing if the key is not in the map. * {@description.close} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @param key the key that needs to be removed * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt> * @throws NullPointerException if the specified key is null */ public V remove(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).remove(key, hash, null); } /** {@collect.stats} * {@inheritDoc} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { int hash = hash(key.hashCode()); if (value == null) return false; return segmentFor(hash).remove(key, hash, value) != null; } /** {@collect.stats} * {@inheritDoc} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key or value is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).replace(key, hash, oldValue, newValue); } /** {@collect.stats} * {@inheritDoc} * {@property.open} * {@new.open formal:java.util.concurrent.ConcurrentHashMap_NonNull} * If the specified key or value is null, a runtime exception is raised. * {@new.close} * {@property.close} * * @return the previous value associated with the specified key, * or <tt>null</tt> if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) throw new NullPointerException(); int hash = hash(key.hashCode()); return segmentFor(hash).replace(key, hash, value); } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * {@description.close} */ public void clear() { for (int i = 0; i < segments.length; ++i) segments[i].clear(); } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from this map, * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or * <tt>addAll</tt> operations. * {@description.close} * * {@property.open synchronized} * <p>The view's <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. * {@property.close} */ public Set<K> keySet() { Set<K> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. The collection * supports element removal, which removes the corresponding * mapping from this map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@description.close} * * {@property.open synchronized} * <p>The view's <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. * {@property.close} */ public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. The set supports element * removal, which removes the corresponding mapping from the map, * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or * <tt>addAll</tt> operations. * {@description.close} * * {@property.open synchronized} * <p>The view's <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. * {@property.close} */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** {@collect.stats} * {@description.open} * Returns an enumeration of the keys in this table. * {@description.close} * * @return an enumeration of the keys in this table * @see #keySet() */ public Enumeration<K> keys() { return new KeyIterator(); } /** {@collect.stats} * {@description.open} * Returns an enumeration of the values in this table. * {@description.close} * * @return an enumeration of the values in this table * @see #values() */ public Enumeration<V> elements() { return new ValueIterator(); } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex; int nextTableIndex; HashEntry<K,V>[] currentTable; HashEntry<K, V> nextEntry; HashEntry<K, V> lastReturned; HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } public boolean hasMoreElements() { return hasNext(); } final void advance() { if (nextEntry != null && (nextEntry = nextEntry.next) != null) return; while (nextTableIndex >= 0) { if ( (nextEntry = currentTable[nextTableIndex--]) != null) return; } while (nextSegmentIndex >= 0) { Segment<K,V> seg = segments[nextSegmentIndex--]; if (seg.count != 0) { currentTable = seg.table; for (int j = currentTable.length - 1; j >= 0; --j) { if ( (nextEntry = currentTable[j]) != null) { nextTableIndex = j - 1; return; } } } } } public boolean hasNext() { return nextEntry != null; } HashEntry<K,V> nextEntry() { if (nextEntry == null) throw new NoSuchElementException(); lastReturned = nextEntry; advance(); return lastReturned; } public void remove() { if (lastReturned == null) throw new IllegalStateException(); ConcurrentHashMap.this.remove(lastReturned.key); lastReturned = null; } } final class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> { public K next() { return super.nextEntry().key; } public K nextElement() { return super.nextEntry().key; } } final class ValueIterator extends HashIterator implements Iterator<V>, Enumeration<V> { public V next() { return super.nextEntry().value; } public V nextElement() { return super.nextEntry().value; } } /** {@collect.stats} * {@description.open} * Custom Entry class used by EntryIterator.next(), that relays * setValue changes to the underlying map. * {@description.close} */ final class WriteThroughEntry extends AbstractMap.SimpleEntry<K,V> { WriteThroughEntry(K k, V v) { super(k,v); } /** {@collect.stats} * {@description.open} * Set our entry's value and write through to the map. The * value to return is somewhat arbitrary here. Since a * WriteThroughEntry does not necessarily track asynchronous * changes, the most recent "previous" value could be * different from what we return (or could even have been * removed in which case the put will re-establish). We do not * and cannot guarantee more. * {@description.close} */ public V setValue(V value) { if (value == null) throw new NullPointerException(); V v = super.setValue(value); ConcurrentHashMap.this.put(getKey(), value); return v; } } final class EntryIterator extends HashIterator implements Iterator<Entry<K,V>> { public Map.Entry<K,V> next() { HashEntry<K,V> e = super.nextEntry(); return new WriteThroughEntry(e.key, e.value); } } final class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return new KeyIterator(); } public int size() { return ConcurrentHashMap.this.size(); } public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } public boolean contains(Object o) { return ConcurrentHashMap.this.containsKey(o); } public boolean remove(Object o) { return ConcurrentHashMap.this.remove(o) != null; } public void clear() { ConcurrentHashMap.this.clear(); } } final class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(); } public int size() { return ConcurrentHashMap.this.size(); } public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } public boolean contains(Object o) { return ConcurrentHashMap.this.containsValue(o); } public void clear() { ConcurrentHashMap.this.clear(); } } final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; V v = ConcurrentHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ConcurrentHashMap.this.remove(e.getKey(), e.getValue()); } public int size() { return ConcurrentHashMap.this.size(); } public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } public void clear() { ConcurrentHashMap.this.clear(); } } /* ---------------- Serialization Support -------------- */ /** {@collect.stats} * {@description.open} * Save the state of the <tt>ConcurrentHashMap</tt> instance to a * stream (i.e., serialize it). * {@description.close} * @param s the stream * @serialData * the key (Object) and value (Object) * for each key-value mapping, followed by a null pair. * The key-value mappings are emitted in no particular order. */ private void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); for (int k = 0; k < segments.length; ++k) { Segment<K,V> seg = segments[k]; seg.lock(); try { HashEntry<K,V>[] tab = seg.table; for (int i = 0; i < tab.length; ++i) { for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) { s.writeObject(e.key); s.writeObject(e.value); } } } finally { seg.unlock(); } } s.writeObject(null); s.writeObject(null); } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>ConcurrentHashMap</tt> instance from a * stream (i.e., deserialize it). * {@description.close} * @param s the stream */ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Initialize each segment to be minimally sized, and let grow. for (int i = 0; i < segments.length; ++i) { segments[i].setTable(new HashEntry[1]); } // Read the keys and values, and put the mappings in the table for (;;) { K key = (K) s.readObject(); V value = (V) s.readObject(); if (key == null) break; put(key, value); } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * Exception indicating that the result of a value-producing task, * such as a {@link FutureTask}, cannot be retrieved because the task * was cancelled. * {@description.close} * * @since 1.5 * @author Doug Lea */ public class CancellationException extends IllegalStateException { private static final long serialVersionUID = -9202173006928992231L; /** {@collect.stats} * {@description.open} * Constructs a <tt>CancellationException</tt> with no detail message. * {@description.close} */ public CancellationException() {} /** {@collect.stats} * {@description.open} * Constructs a <tt>CancellationException</tt> with the specified detail * message. * {@description.close} * * @param message the detail message */ public CancellationException(String message) { super(message); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** {@collect.stats} * {@description.open} * Exception thrown when a thread tries to wait upon a barrier that is * in a broken state, or which enters the broken state while the thread * is waiting. * {@description.close} * * @see CyclicBarrier * * @since 1.5 * @author Doug Lea * */ public class BrokenBarrierException extends Exception { private static final long serialVersionUID = 7117394618823254244L; /** {@collect.stats} * {@description.open} * Constructs a <tt>BrokenBarrierException</tt> with no specified detail * message. * {@description.close} */ public BrokenBarrierException() {} /** {@collect.stats} * {@description.open} * Constructs a <tt>BrokenBarrierException</tt> with the specified * detail message. * {@description.close} * * @param message the detail message */ public BrokenBarrierException(String message) { super(message); } }
Java