Академический Документы
Профессиональный Документы
Культура Документы
y ]
pt ll
Additional methods in enum declaration supplement auto-generated methods: public class Foo2 implements Callable<Bar2> { (add|get|remove)[First|Last]
m [A
>
sE s)
<E
public final static E [ ] values ( ) ; public final static E valueOf (String name) ; public Bar2 call ( ) throws Exception { [statement]* }
e,i ain
Queue AbstractQueue PriorityQueue
ic
}
siz nt
public final String name ( ) ; public String toString ( ) ;
er
offer comparator
ll, |co
en
G
public final int ordinal ( ) ; public final int hashCode ( ) ; Instantiate a Callable and pass it to a ThreadPool, receiving a Future: remove/poll AbstractCollection
nA ve
AbstractSequentialList
ai o
element/peek
et em
public final int compareTo (E o) ; public final boolean equals (Object o) ; import java . util . concurrent .∗;
r,r |r
AbstractList ArrayList
ea dd
[public] enum enum-name [ implements interface-id [ , interface-id ]* ] { ExecutorService pool = Executors .newFixedThreadPool (10);
cl (a
Collection ensureCapacity,trimToSize
[ NAME [ [ (constructor-args) ] [ { [method]* } ] ] // value body Future<Bar2> f = pool . submit ( new Foo2 (args) );
[ , NAME [ [ (constructor-args) ] [ { [method]* } ] ] ]* // value body Subsequently acquire result from the Future: List RandomAccess
[,] ] // value list try { Bar2 b = f .get ( ); } catch (Exception e) { } Iterable [last]indexOf Vector Stack
[ ; [field]* [initializer]* [constructor]* [method]* ] // class body ............................................................................... subList contains,elements push
} iterator get,set copyInto,removeAllElements pop
java . util . concurrent .Executors also offers: Iterator listIterator (add|first|last|remove)Element peek
newSingleThreadExecutor ( ) hasNext Set AbstractSet elementAt,(insert|set|remove)ElementAt empty
Annotations
.............................................................. newCachedThreadPool ( ) finished threads retained 60 seconds for reuse next capacity,ensureCapacity,(set|trimTo)Size search
remove EnumSet
For tools (execution unaffected) & reflection. Limited retention: SOURCE, CLASS, RUNTIME newScheduledThreadPool (num) delay/repeat executes Callables/Runnables SortedSet TreeSet of, (all|copy/none/complement)Of, range
Hold named non-null compile-time constants (e.g. annotations) and 1-D arrays of them using schedule[AtFixedRate|WithFixedDelay] first,last,(head|sub|tail)Set,comparator
HashSet LinkedHashSet
At most one annotation of each sort per allowed target; targets are subset of: java . util . Timer instances offer schedule[AtFixedRate] to run TimerTask instances ListIterator − returned by listIterator method
TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL VARIABLE, ANNOTATION TYPE, PACKAGE a java . util . concurrent . DelayQueue holds Delayed (e.g. ScheduledFuture) objects hasPrevious,previous,(next|previous)Index,add,set BitSet − not generic, not a Set
............................................................................... set,clear,flip,and[Not],[x]or
NB: Local variables and catch clause parameters only accept SOURCE annotations. Enumeration − returned by elements/keys methods length,size,cardinality,isEmpty,intersects
Protect shared objects/state by locking instance/class monitors for critical sections; hasMoreElements,nextElement
@interface creates a new annotation (extending an annotation creates an interface): get,next(Set|Clear)Bit
import java .lang .annotation .∗; import static ElementType .∗ ; threads interact by waiting for / notifying monitors: Dictionary Hashtable
>
,V
public class Bar { put,get,remove,keys,elements,isEmpty contains
@Retention ( RetentionPolicy . RUNTIME ) @Target ( { TYPE, CONSTRUCTOR, METHOD } )
<K
ic
public @interface QualityCheck { [field-declaration]* Map AbstractMap WeakHashMap
er
y
Ke extended by
en
public static enum Quality { BROKEN, POOR, SHIPPABLE } ; public Bar (args) { [statement]* } put[All],get,remove,clear
G
IdentityHashMap row
String checkerName ( ) ; size,isEmpty,values Ar implemented by
synchronized public type methodname (args) { [statement]* } (key|entry)Set,contains(Key|Value) EnumMap
} Quality quality ( ) default Quality . POOR ; [static field-declaration]* Map.Entry getKey,(get|set)Value HashMap LinkedHashMap
Each method signature specifies a name-value pair, where value is of return-type synchronized public static type methodname (args) { [statement]* } SortedMap TreeMap − put calls removeEldestEntry
Standard Annotations: public type methodname (args) { (first|last)Key,(head|sub|tail)Map,comparator
@Deprecated @Override @SuppressWarnings (String [ ] ) [statement]* In java.util.concurrent:
Standard Meta-Annotations (annotations with target ANNOTATION TYPE): synchronized (this) { [statement]* } / / Can limit extent of exclusion Map ConcurrentMap ConcurrentHashMap
@Documented @Inherited @Retention ( RetentionPolicy ) @Target ( ElementType [ ] ) remove,replace,putIfAbsent contains,elements,keys
[statement]*
When applying an annotation, can omit: any items for which a default is specified,
“value=” if item name is “value”, ( ) if no items, and { } for single entry array values
Assertions
}
synchronized public type methodname (args) {
while ( /∗ prevented-from-progressing ∗/ )
Queue BlockingQueue
put,take,offer,poll,add
drainTo,remainingCapacity
{ SynchronousQueue LinkedBlockingQueue
DelayQueue
ArrayBlockingQueue
PriorityBlockingQueue
comparator
.............................................................. try { this . wait ( ); } catch (InterruptedException e) {} AbstractSet CopyOnWriteArraySet List CopyOnWriteArrayList
RandomAccess add(All|If)Absent
assert bool-expr [ : any ] ; ⇒ if ( ! bool-expr ) throw new AssertionError ( [any] ); }
assertions are enabled (–ea) or disabled (–da) at runtime using interpreter flags synchronized public type methodname (args) { Collection<T>: T [ ] toArray ( ); java .util . Arrays: static List<T> asList ( T . . . a);
–ea enable assertions in application classes this . notifyAll ( ); / / having enabled others to progress java . util . Collections statics: nCopies singleton[List|Map] addAll replaceAll rotate
–ea:package-name . . . enable assertions throughout specified package } shuffle sort swap reverse[Order] fill copy disjoint empty(List|Map|Set) min max
–ea:class-name enable assertions for specified class } (checked|synchronized|unmodifiable)(Collection|List|Map|SortedMap|Set|SortedSet)
–esa enable system assertions ............................................................................... list enumeration frequency binarySearch [last]indexOfSubList E MPTY (L IST|M AP|S ET )
long form of flags: –enableassertions –disableassertions etc java . util . concurrent gives additional concurrency control, e.g. instances of:
Semaphore offer acquire[Uninterruptibly] tryAcquire release Simple Text I/O Essentials
..............................................................
Reflection & Instrumentation
..............................................................
locks .ReentrantReadWriteLock offer readLock writeLock
locks .Lock offer lock[Interruptibly] tryLock unlock newCondition Output to a java . io .PrintStream using: print println append format printf
object .getClass ( ), Class .forName ( classname ). class can get[Generic]Superclass locks .Condition offer signal[All] await[Nanos|Until|Uninterruptibly] Example targets: System . out System . err new PrintStream(new File(pathname))
get[Generic]Interfaces get[Declared](Field|Constructor|Method)[s]. Instantiate CountDownLatch offer await countDown getCount java . util . Formatter can format to any Appendable, e.g. File String PrintStream
with: class .newInstance ( ), constructor .newInstance ( [args] ). field can get/set value, CyclicBarrier offer await getNumberWaiting reset isBroken Enriched C-style formats: %% %n %[arg][flags][width][ . precision] type
getType. method can get[Generic](ParameterTypes|ExceptionTypes|ReturnType) Exchanger offer exchange two threads swap values, re-usable arg: < reuse previous, n$ use arg n flags: −#+ (0, type: cs b dox efga t?
and is invocable: method .invoke ( Object obj, Object . . . args ) ⇒ obj .method(args) and LockSupport has static park[Nanos|Until] unpark to suspend / resume threads java . util . Scanner reads Readable, e.g. File String InputStream (e.g. System . in), by
All members can getModifiers (then test for declaration modifiers & interface-ness), [has] next [Line|Boolean|Double|Float|Byte|Int|Short|Long|BigInteger|BigDecimal]
java . util . concurrent .atomic offers atomic operations:
get[Declared|Parameter]Annotation[s] (RUNTIME retention), getDeclaringClass. Atomic(Integer|Long|Reference)[Array], AtomicBoolean for wrapped values Reference Sheet Notation: [ ] ⇒ optional; [ ]* ⇒ ≥ 0; [ ]+ ⇒ ≥ 1; ( | ) ⇒ choice
A Proxy dynamically implements interfaces, delegating invocations to a handler: Atomic(Integer|Long|Reference)FieldUpdater on named volatile fields Related Java Notation: [ ] ⇒ array index/decl; ∗ ⇒ asterisk; + ⇒ plus; | ⇒ or
newProxyInstance ( ClassLoader l, Class<?> [ ] interfaces, InvocationHandler ih ) all have set, get[AndSet], [weak]compareAndSet, and the numbers also have
usage: if ( Proxy .isProxyClass ( object . getClass ( ) ) )
c 2007: Dr Peter Dickman, Dept of Computing Science, University of Glasgow, UK
(add|decrement|increment)AndGet, getAnd(Add|Decrement|Increment)
Proxy .getInvocationHandler ( object ) . invoke ( object, method [ , args ] ) Atomic[Markable|Stamped]Reference combine a boolean or int with a reference Permission is granted to copy for personal, professional, and non-profit educational use.
both offer set, getReference, [weak]compareAndSet Permission is not granted for re-sale or re-publication (e.g. on servers or in books).
java –javaagent flag specifies JAR file whose manifest indicates premain class with:
public static void premain ( String args, Instrumentation instrument ) and isMarked, attemptMark or getStamp, attemptStamp respectively
put ClassFileTransformers into instrument to inspect/change bytecodes during loading. Use java .lang . [Inheritable]ThreadLocal<T> to set, get, remove per-thread values Available online at http://www.dcs.gla.ac.uk/∼pd/JavaRefCard/ v6.0 r8 (2007/10)