New chapters and Netbeans mods
This commit is contained in:
parent
e413ad9a83
commit
d5cf2b7364
@ -1,4 +1,5 @@
|
||||
This computer source code is Copyright (c)2006 MindView, Inc.
|
||||
//: Copyright.txt
|
||||
This computer source code is Copyright 2015 MindView LLC
|
||||
All Rights Reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this
|
||||
@ -20,47 +21,54 @@ Java" is cited as the origin.
|
||||
3. Permission to incorporate the Source Code into printed
|
||||
media may be obtained by contacting:
|
||||
|
||||
MindView, Inc. 5343 Valle Vista La Mesa, California 91941
|
||||
Wayne@MindView.net
|
||||
MindView LLC, PO Box 969, Crested Butte, CO 81224
|
||||
MindViewInc@gmail.com
|
||||
|
||||
4. The Source Code and documentation are copyrighted by
|
||||
MindView, Inc. The Source code is provided without express
|
||||
MindView LLC. The Source code is provided without express
|
||||
or implied warranty of any kind, including any implied
|
||||
warranty of merchantability, fitness for a particular
|
||||
purpose or non-infringement. MindView, Inc. does not
|
||||
warrant that the operation of any program that includes the Source Code will be uninterrupted or error-free. MindView,
|
||||
Inc. makes no representation about the suitability of the
|
||||
purpose or non-infringement. MindView LLC does not
|
||||
warrant that the operation of any program that includes the
|
||||
Source Code will be uninterrupted or error-free. MindView
|
||||
LLC makes no representation about the suitability of the
|
||||
Source Code or of any software that includes the Source
|
||||
Code for any purpose. The entire risk as to the quality
|
||||
and performance of any program that includes the Source
|
||||
Code is with the user of the Source Code. The user
|
||||
understands that the Source Code was developed for research and instructional purposes and is advised not to rely
|
||||
understands that the Source Code was developed for research
|
||||
and instructional purposes and is advised not to rely
|
||||
exclusively for any reason on the Source Code or any
|
||||
program that includes the Source Code. Should the Source
|
||||
Code or any resulting software prove defective, the user
|
||||
assumes the cost of all necessary servicing, repair, or
|
||||
correction.
|
||||
|
||||
5. IN NO EVENT SHALL MINDVIEW, INC., OR ITS PUBLISHER BE
|
||||
5. IN NO EVENT SHALL MINDVIEW LLC, OR ITS PUBLISHER BE
|
||||
LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT,
|
||||
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||
INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF
|
||||
BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR
|
||||
PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE
|
||||
CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW, INC., OR
|
||||
CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY
|
||||
TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW LLC, OR
|
||||
ITS PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGE. MINDVIEW, INC. SPECIFICALLY DISCLAIMS ANY
|
||||
DAMAGE. MINDVIEW LLC SPECIFICALLY DISCLAIMS ANY
|
||||
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED
|
||||
HEREUNDER IS ON AN "AS IS" BASIS, WITHOUT ANY ACCOMPANYING
|
||||
SERVICES FROM MINDVIEW, INC., AND MINDVIEW, INC. HAS NO
|
||||
SERVICES FROM MINDVIEW LLC, AND MINDVIEW LLC HAS NO
|
||||
OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
|
||||
ENHANCEMENTS, OR MODIFICATIONS.
|
||||
|
||||
Please note that MindView, Inc. maintains a Web site which
|
||||
is the sole distribution point for electronic copies of the Source Code, http://www.MindView.net (and official mirror
|
||||
sites), where it is freely available under the terms stated above.
|
||||
Please note that MindView LLC maintains a Web site which
|
||||
is the sole distribution point for electronic copies of the
|
||||
Source Code, http://www.MindView.net (and official mirror
|
||||
sites), where it is freely available under the terms stated
|
||||
above.
|
||||
|
||||
If you think you've found an error in the Source Code,
|
||||
please submit a correction using the feedback system that you will find at http://www.MindView.net.
|
||||
please submit a correction using the feedback system that
|
||||
you will find at http://www.MindView.net.
|
||||
///:~
|
||||
|
24
access/build.xml
Normal file
24
access/build.xml
Normal file
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="access"/>
|
||||
<property name="excludedfiles" value=""/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<touch file="failures"/>
|
||||
<jrun cls="Cake" />
|
||||
<jrun cls="ChocolateChip" />
|
||||
<jrun cls="ChocolateChip2" />
|
||||
<jrun cls="Dinner" />
|
||||
<jrun cls="FullQualification" />
|
||||
<jrun cls="IceCream" />
|
||||
<jrun cls="ImportedMyClass" />
|
||||
<jrun cls="LibTest" />
|
||||
<jrun cls="PrintTest" />
|
||||
<jrun cls="QualifiedMyClass" />
|
||||
<jrun cls="SingleImport" />
|
||||
<delete file="failures"/>
|
||||
</target>
|
||||
|
||||
</project>
|
@ -14,7 +14,7 @@ public class AtUnitExample4 {
|
||||
public AtUnitExample4(String word) { this.word = word; }
|
||||
public String getWord() { return word; }
|
||||
public String scrambleWord() {
|
||||
List<Character> chars = new ArrayList<Character>();
|
||||
List<Character> chars = new ArrayList<>();
|
||||
for(Character c : word.toCharArray())
|
||||
chars.add(c);
|
||||
Collections.shuffle(chars, rand);
|
||||
|
@ -7,6 +7,7 @@ import net.mindview.util.*;
|
||||
public class AtUnitExample5 {
|
||||
private String text;
|
||||
public AtUnitExample5(String text) { this.text = text; }
|
||||
@Override
|
||||
public String toString() { return text; }
|
||||
@TestProperty static PrintWriter output;
|
||||
@TestProperty static int counter;
|
||||
|
@ -5,7 +5,7 @@ import net.mindview.atunit.*;
|
||||
import net.mindview.util.*;
|
||||
|
||||
public class HashSetTest {
|
||||
HashSet<String> testObject = new HashSet<String>();
|
||||
HashSet<String> testObject = new HashSet<>();
|
||||
@Test void initialization() {
|
||||
assert testObject.isEmpty();
|
||||
}
|
||||
|
@ -14,7 +14,7 @@ public class InterfaceExtractorProcessor
|
||||
implements AnnotationProcessor {
|
||||
private final AnnotationProcessorEnvironment env;
|
||||
private ArrayList<MethodDeclaration> interfaceMethods =
|
||||
new ArrayList<MethodDeclaration>();
|
||||
new ArrayList<>();
|
||||
public InterfaceExtractorProcessor(
|
||||
AnnotationProcessorEnvironment env) { this.env = env; }
|
||||
public void process() {
|
||||
|
@ -4,7 +4,7 @@ package annotations;
|
||||
import java.util.*;
|
||||
|
||||
public class StackL<T> {
|
||||
private LinkedList<T> list = new LinkedList<T>();
|
||||
private LinkedList<T> list = new LinkedList<>();
|
||||
public void push(T v) { list.addFirst(v); }
|
||||
public T top() { return list.getFirst(); }
|
||||
public T pop() { return list.removeFirst(); }
|
||||
|
@ -18,7 +18,7 @@ public class UseCaseTracker {
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
List<Integer> useCases = new ArrayList<Integer>();
|
||||
List<Integer> useCases = new ArrayList<>();
|
||||
Collections.addAll(useCases, 47, 48, 49, 50);
|
||||
trackUseCases(useCases, PasswordUtils.class);
|
||||
}
|
||||
|
25
annotations/build.xml
Normal file
25
annotations/build.xml
Normal file
@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="annotations"/>
|
||||
<property name="excludedfiles" value="InterfaceExtractorProcessor.java InterfaceExtractorProcessorFactory.java database/TableCreationProcessorFactory.java"/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<touch file="failures"/>
|
||||
<jrun cls="annotations.AtUnitComposition" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExample1" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExample2" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExample3" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExample4" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExample5" dirpath="../annotations" />
|
||||
<jrun cls="annotations.AtUnitExternalTest" dirpath="../annotations" />
|
||||
<jrun cls="annotations.HashSetTest" dirpath="../annotations" />
|
||||
<jrun cls="annotations.Multiplier" dirpath="../annotations" />
|
||||
<jrun cls="annotations.StackLStringTest" dirpath="../annotations" />
|
||||
<jrun cls="UseCaseTracker" />
|
||||
<jrun cls="annotations.database.TableCreator" dirpath="../annotations/database" arguments='annotations.database.Member' />
|
||||
<delete file="failures"/>
|
||||
</target>
|
||||
|
||||
</project>
|
@ -13,6 +13,7 @@ public class Member {
|
||||
public String getHandle() { return handle; }
|
||||
public String getFirstName() { return firstName; }
|
||||
public String getLastName() { return lastName; }
|
||||
@Override
|
||||
public String toString() { return handle; }
|
||||
public Integer getAge() { return age; }
|
||||
} ///:~
|
||||
|
@ -24,7 +24,7 @@ public class TableCreator {
|
||||
// If the name is empty, use the Class name:
|
||||
if(tableName.length() < 1)
|
||||
tableName = cl.getName().toUpperCase();
|
||||
List<String> columnDefs = new ArrayList<String>();
|
||||
List<String> columnDefs = new ArrayList<>();
|
||||
for(Field field : cl.getDeclaredFields()) {
|
||||
String columnName = null;
|
||||
Annotation[] anns = field.getDeclaredAnnotations();
|
||||
|
@ -8,14 +8,14 @@ public class ArrayOfGenerics {
|
||||
List<String>[] ls;
|
||||
List[] la = new List[10];
|
||||
ls = (List<String>[])la; // "Unchecked" warning
|
||||
ls[0] = new ArrayList<String>();
|
||||
ls[0] = new ArrayList<>();
|
||||
// Compile-time checking produces an error:
|
||||
//! ls[1] = new ArrayList<Integer>();
|
||||
|
||||
// The problem: List<String> is a subtype of Object
|
||||
Object[] objects = ls; // So assignment is OK
|
||||
// Compiles and runs without complaint:
|
||||
objects[1] = new ArrayList<Integer>();
|
||||
objects[1] = new ArrayList<>();
|
||||
|
||||
// However, if your needs are straightforward it is
|
||||
// possible to create an array of generics, albeit
|
||||
@ -23,6 +23,6 @@ public class ArrayOfGenerics {
|
||||
List<BerylliumSphere>[] spheres =
|
||||
(List<BerylliumSphere>[])new List[10];
|
||||
for(int i = 0; i < spheres.length; i++)
|
||||
spheres[i] = new ArrayList<BerylliumSphere>();
|
||||
spheres[i] = new ArrayList<>();
|
||||
}
|
||||
} ///:~
|
||||
|
@ -12,18 +12,21 @@ public class CompType implements Comparable<CompType> {
|
||||
i = n1;
|
||||
j = n2;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
String result = "[i = " + i + ", j = " + j + "]";
|
||||
if(count++ % 3 == 0)
|
||||
result += "\n";
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public int compareTo(CompType rv) {
|
||||
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
|
||||
}
|
||||
private static Random r = new Random(47);
|
||||
public static Generator<CompType> generator() {
|
||||
return new Generator<CompType>() {
|
||||
@Override
|
||||
public CompType next() {
|
||||
return new CompType(r.nextInt(100),r.nextInt(100));
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ import static net.mindview.util.Print.*;
|
||||
class BerylliumSphere {
|
||||
private static long counter;
|
||||
private final long id = counter++;
|
||||
@Override
|
||||
public String toString() { return "Sphere " + id; }
|
||||
}
|
||||
|
||||
@ -16,8 +17,7 @@ public class ContainerComparison {
|
||||
print(Arrays.toString(spheres));
|
||||
print(spheres[4]);
|
||||
|
||||
List<BerylliumSphere> sphereList =
|
||||
new ArrayList<BerylliumSphere>();
|
||||
List<BerylliumSphere> sphereList= new ArrayList<>();
|
||||
for(int i = 0; i < 5; i++)
|
||||
sphereList.add(new BerylliumSphere());
|
||||
print(sphereList);
|
||||
@ -27,7 +27,7 @@ public class ContainerComparison {
|
||||
print(Arrays.toString(integers));
|
||||
print(integers[4]);
|
||||
|
||||
List<Integer> intList = new ArrayList<Integer>(
|
||||
List<Integer> intList = new ArrayList<>(
|
||||
Arrays.asList(0, 1, 2, 3, 4, 5));
|
||||
intList.add(97);
|
||||
print(intList);
|
||||
|
23
arrays/PythonLists.py
Normal file
23
arrays/PythonLists.py
Normal file
@ -0,0 +1,23 @@
|
||||
#: arrays/PythonLists.py
|
||||
|
||||
aList = [1, 2, 3, 4, 5]
|
||||
print(type(aList)) # <type 'list'>
|
||||
print(aList) # [1, 2, 3, 4, 5]
|
||||
print(aList[4]) # 5 Basic list indexing
|
||||
aList.append(6) # lists can be resized
|
||||
aList += [7, 8] # Add a list to a list
|
||||
print(aList) # [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
aSlice = aList[2:4]
|
||||
print(aSlice) # [3, 4]
|
||||
|
||||
class MyList(list): # Inherit from list
|
||||
# Define a method, 'this' pointer is explicit:
|
||||
def getReversed(self):
|
||||
reversed = self[:] # Copy list using slices
|
||||
reversed.reverse() # Built-in list method
|
||||
return reversed
|
||||
|
||||
list2 = MyList(aList) # No 'new' needed for object creation
|
||||
print(type(list2)) # <class '__main__.MyList'>
|
||||
print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1]
|
||||
#:~
|
39
arrays/build.xml
Normal file
39
arrays/build.xml
Normal file
@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="arrays"/>
|
||||
<property name="excludedfiles" value=""/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<touch file="failures"/>
|
||||
<jrun cls="AlphabeticSearch" />
|
||||
<jrun cls="ArrayOfGenerics" />
|
||||
<jrun cls="ArrayOptions" />
|
||||
<jrun cls="ArraySearching" />
|
||||
<jrun cls="AssemblingMultidimensionalArrays" />
|
||||
<jrun cls="AutoboxingArrays" />
|
||||
<jrun cls="ComparatorTest" />
|
||||
<jrun cls="ComparingArrays" />
|
||||
<jrun cls="CompType" />
|
||||
<jrun cls="ContainerComparison" />
|
||||
<jrun cls="CopyingArrays" />
|
||||
<jrun cls="FillingArrays" />
|
||||
<jrun cls="GeneratorsTest" />
|
||||
<jrun cls="IceCream" />
|
||||
<jrun cls="MultidimensionalObjectArrays" />
|
||||
<jrun cls="MultidimensionalPrimitiveArray" />
|
||||
<jrun cls="MultiDimWrapperArray" />
|
||||
<jrun cls="ParameterizedArrayType" />
|
||||
<jrun cls="PrimitiveConversionDemonstration" />
|
||||
<jrun cls="RaggedArray" />
|
||||
<jrun cls="RandomGeneratorsTest" />
|
||||
<jrun cls="Reverse" />
|
||||
<jrun cls="StringSorting" />
|
||||
<jrun cls="TestArrayGeneration" />
|
||||
<jrun cls="TestGenerated" />
|
||||
<jrun cls="ThreeDWithNew" />
|
||||
<delete file="failures"/>
|
||||
</target>
|
||||
|
||||
</project>
|
11
assertions/Assert1.java
Normal file
11
assertions/Assert1.java
Normal file
@ -0,0 +1,11 @@
|
||||
//: assertions/Assert1.java
|
||||
// Non-informative style of assert
|
||||
// Compile with: javac -source 1.4 Assert1.java
|
||||
// {JVMArgs: -ea} // Must run with -ea
|
||||
// {ThrowsException}
|
||||
|
||||
public class Assert1 {
|
||||
public static void main(String[] args) {
|
||||
assert false;
|
||||
}
|
||||
} ///:~
|
10
assertions/Assert2.java
Normal file
10
assertions/Assert2.java
Normal file
@ -0,0 +1,10 @@
|
||||
//: assertions/Assert2.java
|
||||
// Assert with an informative message
|
||||
// {JVMArgs: -ea}
|
||||
// {ThrowsException}
|
||||
|
||||
public class Assert2 {
|
||||
public static void main(String[] args) {
|
||||
assert false: "Here's a message saying what happened";
|
||||
}
|
||||
} ///:~
|
18
assertions/LoaderAssertions.java
Normal file
18
assertions/LoaderAssertions.java
Normal file
@ -0,0 +1,18 @@
|
||||
//: assertions/LoaderAssertions.java
|
||||
// Using the class loader to enable assertions
|
||||
// Compile with: javac -source 1.4 LoaderAssertions.java
|
||||
// {ThrowsException}
|
||||
|
||||
public class LoaderAssertions {
|
||||
public static void main(String[] args) {
|
||||
ClassLoader.getSystemClassLoader()
|
||||
.setDefaultAssertionStatus(true);
|
||||
new Loaded().go();
|
||||
}
|
||||
}
|
||||
|
||||
class Loaded {
|
||||
public void go() {
|
||||
assert false: "Loaded.go()";
|
||||
}
|
||||
} ///:~
|
172
assertions/Queue.java
Normal file
172
assertions/Queue.java
Normal file
@ -0,0 +1,172 @@
|
||||
//: assertions/Queue.java
|
||||
// Demonstration of Design by Contract (DBC) combined
|
||||
// with white-box unit testing.
|
||||
// {Depends: junit.jar}
|
||||
import junit.framework.*;
|
||||
import java.util.*;
|
||||
|
||||
public class Queue {
|
||||
private Object[] data;
|
||||
private int
|
||||
in = 0, // Next available storage space
|
||||
out = 0; // Next gettable object
|
||||
// Has it wrapped around the circular queue?
|
||||
private boolean wrapped = false;
|
||||
public static class
|
||||
QueueException extends RuntimeException {
|
||||
public QueueException(String why) { super(why); }
|
||||
}
|
||||
public Queue(int size) {
|
||||
data = new Object[size];
|
||||
assert invariant(); // Must be true after construction
|
||||
}
|
||||
public boolean empty() {
|
||||
return !wrapped && in == out;
|
||||
}
|
||||
public boolean full() {
|
||||
return wrapped && in == out;
|
||||
}
|
||||
public void put(Object item) {
|
||||
precondition(item != null, "put() null item");
|
||||
precondition(!full(), "put() into full Queue");
|
||||
assert invariant();
|
||||
data[in++] = item;
|
||||
if(in >= data.length) {
|
||||
in = 0;
|
||||
wrapped = true;
|
||||
}
|
||||
assert invariant();
|
||||
}
|
||||
public Object get() {
|
||||
precondition(!empty(), "get() from empty Queue");
|
||||
assert invariant();
|
||||
Object returnVal = data[out];
|
||||
data[out] = null;
|
||||
out++;
|
||||
if(out >= data.length) {
|
||||
out = 0;
|
||||
wrapped = false;
|
||||
}
|
||||
assert postcondition(
|
||||
returnVal != null, "Null item in Queue");
|
||||
assert invariant();
|
||||
return returnVal;
|
||||
}
|
||||
// Design-by-contract support methods:
|
||||
private static void
|
||||
precondition(boolean cond, String msg) {
|
||||
if(!cond) throw new QueueException(msg);
|
||||
}
|
||||
private static boolean
|
||||
postcondition(boolean cond, String msg) {
|
||||
if(!cond) throw new QueueException(msg);
|
||||
return true;
|
||||
}
|
||||
private boolean invariant() {
|
||||
// Guarantee that no null values are in the
|
||||
// region of 'data' that holds objects:
|
||||
for(int i = out; i != in; i = (i + 1) % data.length)
|
||||
if(data[i] == null)
|
||||
throw new QueueException("null in queue");
|
||||
// Guarantee that only null values are outside the
|
||||
// region of 'data' that holds objects:
|
||||
if(full()) return true;
|
||||
for(int i = in; i != out; i = (i + 1) % data.length)
|
||||
if(data[i] != null)
|
||||
throw new QueueException(
|
||||
"non-null outside of queue range: " + dump());
|
||||
return true;
|
||||
}
|
||||
private String dump() {
|
||||
return "in = " + in +
|
||||
", out = " + out +
|
||||
", full() = " + full() +
|
||||
", empty() = " + empty() +
|
||||
", queue = " + Arrays.asList(data);
|
||||
}
|
||||
// JUnit testing.
|
||||
// As an inner class, this has access to privates:
|
||||
public static class WhiteBoxTest extends TestCase {
|
||||
private Queue queue = new Queue(10);
|
||||
private int i = 0;
|
||||
public WhiteBoxTest(String name) {
|
||||
super(name);
|
||||
while(i < 5) // Preload with some data
|
||||
queue.put("" + i++);
|
||||
}
|
||||
// Support methods:
|
||||
private void showFullness() {
|
||||
assertTrue(queue.full());
|
||||
assertFalse(queue.empty());
|
||||
// Dump is private, white-box testing allows access:
|
||||
System.out.println(queue.dump());
|
||||
}
|
||||
private void showEmptiness() {
|
||||
assertFalse(queue.full());
|
||||
assertTrue(queue.empty());
|
||||
System.out.println(queue.dump());
|
||||
}
|
||||
public void testFull() {
|
||||
System.out.println("testFull");
|
||||
System.out.println(queue.dump());
|
||||
System.out.println(queue.get());
|
||||
System.out.println(queue.get());
|
||||
while(!queue.full())
|
||||
queue.put("" + i++);
|
||||
String msg = "";
|
||||
try {
|
||||
queue.put("");
|
||||
} catch(QueueException e) {
|
||||
msg = e.getMessage();
|
||||
System.out.println(msg);
|
||||
}
|
||||
assertEquals(msg, "put() into full Queue");
|
||||
showFullness();
|
||||
}
|
||||
public void testEmpty() {
|
||||
System.out.println("testEmpty");
|
||||
while(!queue.empty())
|
||||
System.out.println(queue.get());
|
||||
String msg = "";
|
||||
try {
|
||||
queue.get();
|
||||
} catch(QueueException e) {
|
||||
msg = e.getMessage();
|
||||
System.out.println(msg);
|
||||
}
|
||||
assertEquals(msg, "get() from empty Queue");
|
||||
showEmptiness();
|
||||
}
|
||||
public void testNullPut() {
|
||||
System.out.println("testNullPut");
|
||||
String msg = "";
|
||||
try {
|
||||
queue.put(null);
|
||||
} catch(QueueException e) {
|
||||
msg = e.getMessage();
|
||||
System.out.println(msg);
|
||||
}
|
||||
assertEquals(msg, "put() null item");
|
||||
}
|
||||
public void testCircularity() {
|
||||
System.out.println("testCircularity");
|
||||
while(!queue.full())
|
||||
queue.put("" + i++);
|
||||
showFullness();
|
||||
// White-box testing accesses private field:
|
||||
assertTrue(queue.wrapped);
|
||||
while(!queue.empty())
|
||||
System.out.println(queue.get());
|
||||
showEmptiness();
|
||||
while(!queue.full())
|
||||
queue.put("" + i++);
|
||||
showFullness();
|
||||
while(!queue.empty())
|
||||
System.out.println(queue.get());
|
||||
showEmptiness();
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(Queue.WhiteBoxTest.class);
|
||||
}
|
||||
} ///:~
|
17
assertions/build.xml
Normal file
17
assertions/build.xml
Normal file
@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="assertions"/>
|
||||
<property name="excludedfiles" value=""/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<touch file="failures"/>
|
||||
<jrun cls="Assert1" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="Assert2" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="LoaderAssertions" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="Queue" />
|
||||
<delete file="failures"/>
|
||||
</target>
|
||||
|
||||
</project>
|
@ -23,6 +23,7 @@ public class ActiveObjectDemo {
|
||||
public Future<Integer>
|
||||
calculateInt(final int x, final int y) {
|
||||
return ex.submit(new Callable<Integer>() {
|
||||
@Override
|
||||
public Integer call() {
|
||||
print("starting " + x + " + " + y);
|
||||
pause(500);
|
||||
@ -33,6 +34,7 @@ public class ActiveObjectDemo {
|
||||
public Future<Float>
|
||||
calculateFloat(final float x, final float y) {
|
||||
return ex.submit(new Callable<Float>() {
|
||||
@Override
|
||||
public Float call() {
|
||||
print("starting " + x + " + " + y);
|
||||
pause(2000);
|
||||
@ -45,7 +47,7 @@ public class ActiveObjectDemo {
|
||||
ActiveObjectDemo d1 = new ActiveObjectDemo();
|
||||
// Prevents ConcurrentModificationException:
|
||||
List<Future<?>> results =
|
||||
new CopyOnWriteArrayList<Future<?>>();
|
||||
new CopyOnWriteArrayList<>();
|
||||
for(float f = 0.0f; f < 1.0f; f += 0.2f)
|
||||
results.add(d1.calculateFloat(f, f));
|
||||
for(int i = 0; i < 5; i++)
|
||||
|
@ -1,11 +1,12 @@
|
||||
//: concurrency/AtomicEvenGenerator.java
|
||||
// Atomic classes are occasionally useful in regular code.
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
public class AtomicEvenGenerator extends IntGenerator {
|
||||
private AtomicInteger currentEvenValue =
|
||||
new AtomicInteger(0);
|
||||
@Override
|
||||
public int next() {
|
||||
return currentEvenValue.addAndGet(2);
|
||||
}
|
||||
|
@ -7,12 +7,14 @@ public class AtomicIntegerTest implements Runnable {
|
||||
private AtomicInteger i = new AtomicInteger(0);
|
||||
public int getValue() { return i.get(); }
|
||||
private void evenIncrement() { i.addAndGet(2); }
|
||||
@Override
|
||||
public void run() {
|
||||
while(true)
|
||||
evenIncrement();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
new Timer().schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
System.err.println("Aborting");
|
||||
System.exit(0);
|
||||
|
@ -5,6 +5,7 @@ public class AtomicityTest implements Runnable {
|
||||
private int i = 0;
|
||||
public int getValue() { return i; }
|
||||
private synchronized void evenIncrement() { i++; i++; }
|
||||
@Override
|
||||
public void run() {
|
||||
while(true)
|
||||
evenIncrement();
|
||||
|
@ -37,6 +37,7 @@ public class AttemptLocking {
|
||||
// Now create a separate task to grab the lock:
|
||||
new Thread() {
|
||||
{ setDaemon(true); }
|
||||
@Override
|
||||
public void run() {
|
||||
al.lock.lock();
|
||||
System.out.println("acquired");
|
||||
|
@ -19,6 +19,7 @@ class CustomerLine extends ArrayBlockingQueue<Customer> {
|
||||
public CustomerLine(int maxLineSize) {
|
||||
super(maxLineSize);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
if(this.size() == 0)
|
||||
return "[Empty]";
|
||||
@ -36,6 +37,7 @@ class CustomerGenerator implements Runnable {
|
||||
public CustomerGenerator(CustomerLine cq) {
|
||||
customers = cq;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -96,9 +98,9 @@ class TellerManager implements Runnable {
|
||||
private ExecutorService exec;
|
||||
private CustomerLine customers;
|
||||
private PriorityQueue<Teller> workingTellers =
|
||||
new PriorityQueue<Teller>();
|
||||
new PriorityQueue<>();
|
||||
private Queue<Teller> tellersDoingOtherThings =
|
||||
new LinkedList<Teller>();
|
||||
new LinkedList<>();
|
||||
private int adjustmentPeriod;
|
||||
|
||||
public TellerManager(ExecutorService e,
|
||||
@ -146,6 +148,7 @@ class TellerManager implements Runnable {
|
||||
teller.doSomethingElse();
|
||||
tellersDoingOtherThings.offer(teller);
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -161,6 +164,7 @@ class TellerManager implements Runnable {
|
||||
}
|
||||
System.out.println(this + "terminating");
|
||||
}
|
||||
@Override
|
||||
public String toString() { return "TellerManager "; }
|
||||
}
|
||||
|
||||
|
@ -7,6 +7,7 @@ class TaskWithResult implements Callable<String> {
|
||||
public TaskWithResult(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
@Override
|
||||
public String call() {
|
||||
return "result of TaskWithResult " + id;
|
||||
}
|
||||
@ -15,8 +16,7 @@ class TaskWithResult implements Callable<String> {
|
||||
public class CallableDemo {
|
||||
public static void main(String[] args) {
|
||||
ExecutorService exec = Executors.newCachedThreadPool();
|
||||
ArrayList<Future<String>> results =
|
||||
new ArrayList<Future<String>>();
|
||||
ArrayList<Future<String>> results = new ArrayList<>();
|
||||
for(int i = 0; i < 10; i++)
|
||||
results.add(exec.submit(new TaskWithResult(i)));
|
||||
for(Future<String> fs : results)
|
||||
|
@ -1,8 +1,9 @@
|
||||
//: concurrency/CaptureUncaughtException.java
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.util.concurrent.*;
|
||||
|
||||
class ExceptionThread2 implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
Thread t = Thread.currentThread();
|
||||
System.out.println("run() by " + t);
|
||||
@ -14,12 +15,14 @@ class ExceptionThread2 implements Runnable {
|
||||
|
||||
class MyUncaughtExceptionHandler implements
|
||||
Thread.UncaughtExceptionHandler {
|
||||
@Override
|
||||
public void uncaughtException(Thread t, Throwable e) {
|
||||
System.out.println("caught " + e);
|
||||
}
|
||||
}
|
||||
|
||||
class HandlerThreadFactory implements ThreadFactory {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
System.out.println(this + " creating new Thread");
|
||||
Thread t = new Thread(r);
|
||||
|
@ -30,6 +30,7 @@ class ChassisBuilder implements Runnable {
|
||||
private CarQueue carQueue;
|
||||
private int counter = 0;
|
||||
public ChassisBuilder(CarQueue cq) { carQueue = cq; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -59,6 +60,7 @@ class Assembler implements Runnable {
|
||||
}
|
||||
public Car car() { return car; }
|
||||
public CyclicBarrier barrier() { return barrier; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -85,6 +87,7 @@ class Assembler implements Runnable {
|
||||
class Reporter implements Runnable {
|
||||
private CarQueue carQueue;
|
||||
public Reporter(CarQueue cq) { carQueue = cq; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -167,7 +170,7 @@ class WheelRobot extends Robot {
|
||||
|
||||
class RobotPool {
|
||||
// Quietly prevents identical entries:
|
||||
private Set<Robot> pool = new HashSet<Robot>();
|
||||
private Set<Robot> pool = new HashSet<>();
|
||||
public synchronized void add(Robot r) {
|
||||
pool.add(r);
|
||||
notifyAll();
|
||||
|
@ -1,7 +1,7 @@
|
||||
//: concurrency/CloseResource.java
|
||||
// Interrupting a blocked task by
|
||||
// closing the underlying resource.
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.net.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.io.*;
|
||||
|
@ -12,6 +12,7 @@ class TaskPortion implements Runnable {
|
||||
TaskPortion(CountDownLatch latch) {
|
||||
this.latch = latch;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
doWork();
|
||||
@ -24,6 +25,7 @@ class TaskPortion implements Runnable {
|
||||
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
|
||||
print(this + "completed");
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%1$-3d ", id);
|
||||
}
|
||||
@ -37,6 +39,7 @@ class WaitingTask implements Runnable {
|
||||
WaitingTask(CountDownLatch latch) {
|
||||
this.latch = latch;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
latch.await();
|
||||
@ -45,6 +48,7 @@ class WaitingTask implements Runnable {
|
||||
print(this + " interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("WaitingTask %1$-3d ", id);
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
//: concurrency/CriticalSection.java
|
||||
// {RunByHand} (Behavior may have changed in Java 8).
|
||||
// {TimeOutDuringTesting}
|
||||
// (Behavior may have changed in Java 8).
|
||||
// Synchronizing blocks instead of entire methods. Also
|
||||
// demonstrates protection of a non-thread-safe class
|
||||
// with a thread-safe one.
|
||||
@ -19,6 +20,7 @@ class Pair { // Not thread-safe
|
||||
public int getY() { return y; }
|
||||
public void incrementX() { x++; }
|
||||
public void incrementY() { y++; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return "x: " + x + ", y: " + y;
|
||||
}
|
||||
@ -40,7 +42,7 @@ abstract class PairManager {
|
||||
AtomicInteger checkCounter = new AtomicInteger(0);
|
||||
protected Pair p = new Pair();
|
||||
private List<Pair> storage =
|
||||
Collections.synchronizedList(new ArrayList<Pair>());
|
||||
Collections.synchronizedList(new ArrayList<>());
|
||||
public synchronized Pair getPair() {
|
||||
// Make a copy to keep the original safe:
|
||||
return new Pair(p.getX(), p.getY());
|
||||
@ -57,6 +59,7 @@ abstract class PairManager {
|
||||
|
||||
// Synchronize the entire method:
|
||||
class PairManager1 extends PairManager {
|
||||
@Override
|
||||
public synchronized void increment() {
|
||||
p.incrementX();
|
||||
p.incrementY();
|
||||
@ -66,6 +69,7 @@ class PairManager1 extends PairManager {
|
||||
|
||||
// Use a critical section:
|
||||
class PairManager2 extends PairManager {
|
||||
@Override
|
||||
public void increment() {
|
||||
Pair temp;
|
||||
synchronized(this) {
|
||||
@ -82,10 +86,12 @@ class PairManipulator implements Runnable {
|
||||
public PairManipulator(PairManager pm) {
|
||||
this.pm = pm;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(true)
|
||||
pm.increment();
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Pair: " + pm.getPair() +
|
||||
" checkCounter = " + pm.checkCounter.get();
|
||||
@ -97,6 +103,7 @@ class PairChecker implements Runnable {
|
||||
public PairChecker(PairManager pm) {
|
||||
this.pm = pm;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
pm.checkCounter.incrementAndGet();
|
||||
|
@ -5,6 +5,7 @@ import net.mindview.util.*;
|
||||
import static net.mindview.util.Print.*;
|
||||
|
||||
public class DaemonFromFactory implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
|
@ -5,6 +5,7 @@ import static net.mindview.util.Print.*;
|
||||
|
||||
class Daemon implements Runnable {
|
||||
private Thread[] t = new Thread[10];
|
||||
@Override
|
||||
public void run() {
|
||||
for(int i = 0; i < t.length; i++) {
|
||||
t[i] = new Thread(new DaemonSpawn());
|
||||
@ -20,6 +21,7 @@ class Daemon implements Runnable {
|
||||
}
|
||||
|
||||
class DaemonSpawn implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
while(true)
|
||||
Thread.yield();
|
||||
|
@ -4,6 +4,7 @@ import java.util.concurrent.*;
|
||||
import static net.mindview.util.Print.*;
|
||||
|
||||
class ADaemon implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
print("Starting ADaemon");
|
||||
|
@ -10,24 +10,28 @@ class DelayedTask implements Runnable, Delayed {
|
||||
private final int delta;
|
||||
private final long trigger;
|
||||
protected static List<DelayedTask> sequence =
|
||||
new ArrayList<DelayedTask>();
|
||||
new ArrayList<>();
|
||||
public DelayedTask(int delayInMilliseconds) {
|
||||
delta = delayInMilliseconds;
|
||||
trigger = System.nanoTime() +
|
||||
NANOSECONDS.convert(delta, MILLISECONDS);
|
||||
sequence.add(this);
|
||||
}
|
||||
@Override
|
||||
public long getDelay(TimeUnit unit) {
|
||||
return unit.convert(
|
||||
trigger - System.nanoTime(), NANOSECONDS);
|
||||
}
|
||||
@Override
|
||||
public int compareTo(Delayed arg) {
|
||||
DelayedTask that = (DelayedTask)arg;
|
||||
if(trigger < that.trigger) return -1;
|
||||
if(trigger > that.trigger) return 1;
|
||||
return 0;
|
||||
}
|
||||
@Override
|
||||
public void run() { printnb(this + " "); }
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("[%1$-4d]", delta) +
|
||||
" Task " + id;
|
||||
@ -41,6 +45,7 @@ class DelayedTask implements Runnable, Delayed {
|
||||
super(delay);
|
||||
exec = e;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
for(DelayedTask pt : sequence) {
|
||||
printnb(pt.summary() + " ");
|
||||
@ -57,6 +62,7 @@ class DelayedTaskConsumer implements Runnable {
|
||||
public DelayedTaskConsumer(DelayQueue<DelayedTask> q) {
|
||||
this.q = q;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted())
|
||||
@ -73,7 +79,7 @@ public class DelayQueueDemo {
|
||||
Random rand = new Random(47);
|
||||
ExecutorService exec = Executors.newCachedThreadPool();
|
||||
DelayQueue<DelayedTask> queue =
|
||||
new DelayQueue<DelayedTask>();
|
||||
new DelayQueue<>();
|
||||
// Fill with tasks that have random delays:
|
||||
for(int i = 0; i < 20; i++)
|
||||
queue.put(new DelayedTask(rand.nextInt(5000)));
|
||||
|
@ -8,6 +8,7 @@ public class EvenChecker implements Runnable {
|
||||
generator = g;
|
||||
id = ident;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(!generator.isCanceled()) {
|
||||
int val = generator.next();
|
||||
|
@ -3,6 +3,7 @@
|
||||
|
||||
public class EvenGenerator extends IntGenerator {
|
||||
private int currentEvenValue = 0;
|
||||
@Override
|
||||
public int next() {
|
||||
++currentEvenValue; // Danger point here!
|
||||
++currentEvenValue;
|
||||
|
@ -3,6 +3,7 @@
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class ExceptionThread implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
@ -13,6 +13,7 @@ class ExchangerProducer<T> implements Runnable {
|
||||
generator = gen;
|
||||
this.holder = holder;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -35,6 +36,7 @@ class ExchangerConsumer<T> implements Runnable {
|
||||
exchanger = ex;
|
||||
this.holder = holder;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -60,14 +62,14 @@ public class ExchangerDemo {
|
||||
if(args.length > 1)
|
||||
delay = new Integer(args[1]);
|
||||
ExecutorService exec = Executors.newCachedThreadPool();
|
||||
Exchanger<List<Fat>> xc = new Exchanger<List<Fat>>();
|
||||
Exchanger<List<Fat>> xc = new Exchanger<>();
|
||||
List<Fat>
|
||||
producerList = new CopyOnWriteArrayList<Fat>(),
|
||||
consumerList = new CopyOnWriteArrayList<Fat>();
|
||||
exec.execute(new ExchangerProducer<Fat>(xc,
|
||||
producerList = new CopyOnWriteArrayList<>(),
|
||||
consumerList = new CopyOnWriteArrayList<>();
|
||||
exec.execute(new ExchangerProducer<>(xc,
|
||||
BasicGenerator.create(Fat.class), producerList));
|
||||
exec.execute(
|
||||
new ExchangerConsumer<Fat>(xc,consumerList));
|
||||
new ExchangerConsumer<>(xc,consumerList));
|
||||
TimeUnit.SECONDS.sleep(delay);
|
||||
exec.shutdownNow();
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ import java.util.concurrent.locks.*;
|
||||
// Synchronize the entire method:
|
||||
class ExplicitPairManager1 extends PairManager {
|
||||
private Lock lock = new ReentrantLock();
|
||||
@Override
|
||||
public void increment() {
|
||||
lock.lock();
|
||||
try {
|
||||
@ -22,6 +23,7 @@ class ExplicitPairManager1 extends PairManager {
|
||||
// Use a critical section:
|
||||
class ExplicitPairManager2 extends PairManager {
|
||||
private Lock lock = new ReentrantLock();
|
||||
@Override
|
||||
public void increment() {
|
||||
Pair temp;
|
||||
lock.lock();
|
||||
|
@ -12,6 +12,7 @@ public class FastSimulation {
|
||||
new AtomicInteger[N_ELEMENTS][N_GENES];
|
||||
static Random rand = new Random(47);
|
||||
static class Evolver implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
while(!Thread.interrupted()) {
|
||||
// Randomly select an element to work on:
|
||||
|
@ -12,5 +12,6 @@ public class Fat {
|
||||
}
|
||||
}
|
||||
public void operation() { System.out.println(this); }
|
||||
@Override
|
||||
public String toString() { return "Fat id: " + id; }
|
||||
} ///:~
|
||||
|
@ -26,6 +26,7 @@ public class GreenhouseScheduler {
|
||||
event, initialDelay, period, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
class LightOn implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here to
|
||||
// physically turn on the light.
|
||||
@ -34,6 +35,7 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class LightOff implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here to
|
||||
// physically turn off the light.
|
||||
@ -42,6 +44,7 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class WaterOn implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here.
|
||||
System.out.println("Turning greenhouse water on");
|
||||
@ -49,6 +52,7 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class WaterOff implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here.
|
||||
System.out.println("Turning greenhouse water off");
|
||||
@ -56,6 +60,7 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class ThermostatNight implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here.
|
||||
System.out.println("Thermostat to night setting");
|
||||
@ -63,6 +68,7 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class ThermostatDay implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Put hardware control code here.
|
||||
System.out.println("Thermostat to day setting");
|
||||
@ -70,15 +76,18 @@ public class GreenhouseScheduler {
|
||||
}
|
||||
}
|
||||
class Bell implements Runnable {
|
||||
@Override
|
||||
public void run() { System.out.println("Bing!"); }
|
||||
}
|
||||
class Terminate implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Terminating");
|
||||
scheduler.shutdownNow();
|
||||
// Must start a separate task to do this job,
|
||||
// since the scheduler was shut down:
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
for(DataPoint d : data)
|
||||
System.out.println(d);
|
||||
@ -96,6 +105,7 @@ public class GreenhouseScheduler {
|
||||
temperature = temp;
|
||||
humidity = hum;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return time.getTime() +
|
||||
String.format(
|
||||
@ -114,8 +124,9 @@ public class GreenhouseScheduler {
|
||||
private int humidityDirection = +1;
|
||||
private Random rand = new Random(47);
|
||||
List<DataPoint> data = Collections.synchronizedList(
|
||||
new ArrayList<DataPoint>());
|
||||
new ArrayList<>());
|
||||
class CollectData implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Collecting data");
|
||||
synchronized(GreenhouseScheduler.this) {
|
||||
|
@ -12,6 +12,7 @@ class Horse implements Runnable {
|
||||
private static CyclicBarrier barrier;
|
||||
public Horse(CyclicBarrier b) { barrier = b; }
|
||||
public synchronized int getStrides() { return strides; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -27,6 +28,7 @@ class Horse implements Runnable {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() { return "Horse " + id + " "; }
|
||||
public String tracks() {
|
||||
StringBuilder s = new StringBuilder();
|
||||
@ -39,12 +41,13 @@ class Horse implements Runnable {
|
||||
|
||||
public class HorseRace {
|
||||
static final int FINISH_LINE = 75;
|
||||
private List<Horse> horses = new ArrayList<Horse>();
|
||||
private List<Horse> horses = new ArrayList<>();
|
||||
private ExecutorService exec =
|
||||
Executors.newCachedThreadPool();
|
||||
private CyclicBarrier barrier;
|
||||
public HorseRace(int nHorses, final int pause) {
|
||||
barrier = new CyclicBarrier(nHorses, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
StringBuilder s = new StringBuilder();
|
||||
for(int i = 0; i < FINISH_LINE; i++)
|
||||
|
@ -5,6 +5,7 @@ import java.io.*;
|
||||
import static net.mindview.util.Print.*;
|
||||
|
||||
class SleepBlocked implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(100);
|
||||
@ -18,6 +19,7 @@ class SleepBlocked implements Runnable {
|
||||
class IOBlocked implements Runnable {
|
||||
private InputStream in;
|
||||
public IOBlocked(InputStream is) { in = is; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
print("Waiting for read():");
|
||||
@ -40,11 +42,13 @@ class SynchronizedBlocked implements Runnable {
|
||||
}
|
||||
public SynchronizedBlocked() {
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
f(); // Lock acquired by this thread
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
print("Trying to call f()");
|
||||
f();
|
||||
|
@ -24,6 +24,7 @@ class BlockedMutex {
|
||||
|
||||
class Blocked2 implements Runnable {
|
||||
BlockedMutex blocked = new BlockedMutex();
|
||||
@Override
|
||||
public void run() {
|
||||
print("Waiting for f() in BlockedMutex");
|
||||
blocked.f();
|
||||
|
@ -17,6 +17,7 @@ class NeedsCleanup {
|
||||
|
||||
class Blocked3 implements Runnable {
|
||||
private volatile double d = 0.0;
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -9,6 +9,7 @@ class Sleeper extends Thread {
|
||||
duration = sleepTime;
|
||||
start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
sleep(duration);
|
||||
@ -28,6 +29,7 @@ class Joiner extends Thread {
|
||||
this.sleeper = sleeper;
|
||||
start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
sleeper.join();
|
||||
|
@ -13,6 +13,7 @@ public class LiftOff implements Runnable {
|
||||
return "#" + id + "(" +
|
||||
(countDown > 0 ? countDown : "Liftoff!") + "), ";
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(countDown-- > 0) {
|
||||
System.out.print(status());
|
||||
|
@ -42,7 +42,7 @@ abstract class ListTest extends Tester<List<Integer>> {
|
||||
class SynchronizedArrayListTest extends ListTest {
|
||||
List<Integer> containerInitializer() {
|
||||
return Collections.synchronizedList(
|
||||
new ArrayList<Integer>(
|
||||
new ArrayList<>(
|
||||
new CountingIntegerList(containerSize)));
|
||||
}
|
||||
SynchronizedArrayListTest(int nReaders, int nWriters) {
|
||||
@ -52,7 +52,7 @@ class SynchronizedArrayListTest extends ListTest {
|
||||
|
||||
class CopyOnWriteArrayListTest extends ListTest {
|
||||
List<Integer> containerInitializer() {
|
||||
return new CopyOnWriteArrayList<Integer>(
|
||||
return new CopyOnWriteArrayList<>(
|
||||
new CountingIntegerList(containerSize));
|
||||
}
|
||||
CopyOnWriteArrayListTest(int nReaders, int nWriters) {
|
||||
|
@ -43,7 +43,7 @@ extends Tester<Map<Integer,Integer>> {
|
||||
class SynchronizedHashMapTest extends MapTest {
|
||||
Map<Integer,Integer> containerInitializer() {
|
||||
return Collections.synchronizedMap(
|
||||
new HashMap<Integer,Integer>(
|
||||
new HashMap<>(
|
||||
MapData.map(
|
||||
new CountingGenerator.Integer(),
|
||||
new CountingGenerator.Integer(),
|
||||
@ -56,7 +56,7 @@ class SynchronizedHashMapTest extends MapTest {
|
||||
|
||||
class ConcurrentHashMapTest extends MapTest {
|
||||
Map<Integer,Integer> containerInitializer() {
|
||||
return new ConcurrentHashMap<Integer,Integer>(
|
||||
return new ConcurrentHashMap<>(
|
||||
MapData.map(
|
||||
new CountingGenerator.Integer(),
|
||||
new CountingGenerator.Integer(), containerSize));
|
||||
|
@ -18,6 +18,7 @@ public class MultiLock {
|
||||
public static void main(String[] args) throws Exception {
|
||||
final MultiLock multiLock = new MultiLock();
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
multiLock.f1(10);
|
||||
}
|
||||
|
@ -1,11 +1,12 @@
|
||||
//: concurrency/MutexEvenGenerator.java
|
||||
// Preventing thread collisions with mutexes.
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.util.concurrent.locks.*;
|
||||
|
||||
public class MutexEvenGenerator extends IntGenerator {
|
||||
private int currentEvenValue = 0;
|
||||
private Lock lock = new ReentrantLock();
|
||||
@Override
|
||||
public int next() {
|
||||
lock.lock();
|
||||
try {
|
||||
|
@ -10,6 +10,7 @@ import static net.mindview.util.Print.*;
|
||||
class NIOBlocked implements Runnable {
|
||||
private final SocketChannel sc;
|
||||
public NIOBlocked(SocketChannel sc) { this.sc = sc; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
print("Waiting for read() in " + this);
|
||||
|
@ -19,12 +19,14 @@ class Blocker {
|
||||
|
||||
class Task implements Runnable {
|
||||
static Blocker blocker = new Blocker();
|
||||
@Override
|
||||
public void run() { blocker.waitingCall(); }
|
||||
}
|
||||
|
||||
class Task2 implements Runnable {
|
||||
// A separate Blocker object:
|
||||
static Blocker blocker = new Blocker();
|
||||
@Override
|
||||
public void run() { blocker.waitingCall(); }
|
||||
}
|
||||
|
||||
@ -37,6 +39,7 @@ public class NotifyVsNotifyAll {
|
||||
Timer timer = new Timer();
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
boolean prod = true;
|
||||
@Override
|
||||
public void run() {
|
||||
if(prod) {
|
||||
System.out.print("\nnotify() ");
|
||||
|
@ -19,7 +19,7 @@ class Count {
|
||||
class Entrance implements Runnable {
|
||||
private static Count count = new Count();
|
||||
private static List<Entrance> entrances =
|
||||
new ArrayList<Entrance>();
|
||||
new ArrayList<>();
|
||||
private int number = 0;
|
||||
// Doesn't need synchronization to read:
|
||||
private final int id;
|
||||
@ -32,6 +32,7 @@ class Entrance implements Runnable {
|
||||
// garbage collection of dead tasks:
|
||||
entrances.add(this);
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(!canceled) {
|
||||
synchronized(this) {
|
||||
@ -47,6 +48,7 @@ class Entrance implements Runnable {
|
||||
print("Stopping " + this);
|
||||
}
|
||||
public synchronized int getValue() { return number; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Entrance " + id + ": " + getValue();
|
||||
}
|
||||
|
@ -22,6 +22,7 @@ public class Philosopher implements Runnable {
|
||||
id = ident;
|
||||
ponderFactor = ponder;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -41,5 +42,6 @@ public class Philosopher implements Runnable {
|
||||
print(this + " " + "exiting via interrupt");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() { return "Philosopher " + id; }
|
||||
} ///:~
|
||||
|
@ -9,6 +9,7 @@ class Sender implements Runnable {
|
||||
private Random rand = new Random(47);
|
||||
private PipedWriter out = new PipedWriter();
|
||||
public PipedWriter getPipedWriter() { return out; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true)
|
||||
@ -29,6 +30,7 @@ class Receiver implements Runnable {
|
||||
public Receiver(Sender sender) throws IOException {
|
||||
in = new PipedReader(sender.getPipedWriter());
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
|
@ -6,7 +6,7 @@ import java.util.*;
|
||||
|
||||
public class Pool<T> {
|
||||
private int size;
|
||||
private List<T> items = new ArrayList<T>();
|
||||
private List<T> items = new ArrayList<>();
|
||||
private volatile boolean[] checkedOut;
|
||||
private Semaphore available;
|
||||
public Pool(Class<T> classObject, int size) {
|
||||
|
@ -10,15 +10,17 @@ Runnable, Comparable<PrioritizedTask> {
|
||||
private final int id = counter++;
|
||||
private final int priority;
|
||||
protected static List<PrioritizedTask> sequence =
|
||||
new ArrayList<PrioritizedTask>();
|
||||
new ArrayList<>();
|
||||
public PrioritizedTask(int priority) {
|
||||
this.priority = priority;
|
||||
sequence.add(this);
|
||||
}
|
||||
@Override
|
||||
public int compareTo(PrioritizedTask arg) {
|
||||
return priority < arg.priority ? 1 :
|
||||
(priority > arg.priority ? -1 : 0);
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(rand.nextInt(250));
|
||||
@ -27,6 +29,7 @@ Runnable, Comparable<PrioritizedTask> {
|
||||
}
|
||||
print(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("[%1$-3d]", priority) +
|
||||
" Task " + id;
|
||||
@ -40,6 +43,7 @@ Runnable, Comparable<PrioritizedTask> {
|
||||
super(-1); // Lowest priority in this program
|
||||
exec = e;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
int count = 0;
|
||||
for(PrioritizedTask pt : sequence) {
|
||||
@ -63,6 +67,7 @@ class PrioritizedTaskProducer implements Runnable {
|
||||
queue = q;
|
||||
exec = e; // Used for EndSentinel
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
// Unbounded queue; never blocks.
|
||||
// Fill it up fast with random priorities:
|
||||
@ -94,6 +99,7 @@ class PrioritizedTaskConsumer implements Runnable {
|
||||
PriorityBlockingQueue<Runnable> q) {
|
||||
this.q = q;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted())
|
||||
@ -110,7 +116,7 @@ public class PriorityBlockingQueueDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ExecutorService exec = Executors.newCachedThreadPool();
|
||||
PriorityBlockingQueue<Runnable> queue =
|
||||
new PriorityBlockingQueue<Runnable>();
|
||||
new PriorityBlockingQueue<>();
|
||||
exec.execute(new PrioritizedTaskProducer(queue, exec));
|
||||
exec.execute(new PrioritizedTaskConsumer(queue));
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ public class ReaderWriterList<T> {
|
||||
private ReentrantReadWriteLock lock =
|
||||
new ReentrantReadWriteLock(true);
|
||||
public ReaderWriterList(int size, T initialValue) {
|
||||
lockedList = new ArrayList<T>(
|
||||
lockedList = new ArrayList<>(
|
||||
Collections.nCopies(size, initialValue));
|
||||
}
|
||||
public T set(int index, T element) {
|
||||
@ -45,8 +45,9 @@ class ReaderWriterListTest {
|
||||
private final static int SIZE = 100;
|
||||
private static Random rand = new Random(47);
|
||||
private ReaderWriterList<Integer> list =
|
||||
new ReaderWriterList<Integer>(SIZE, 0);
|
||||
new ReaderWriterList<>(SIZE, 0);
|
||||
private class Writer implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
for(int i = 0; i < 20; i++) { // 2 second test
|
||||
@ -61,6 +62,7 @@ class ReaderWriterListTest {
|
||||
}
|
||||
}
|
||||
private class Reader implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -1,6 +1,6 @@
|
||||
//: concurrency/ResponsiveUI.java
|
||||
// User interface responsiveness.
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
|
||||
class UnresponsiveUI {
|
||||
private volatile double d = 1;
|
||||
@ -17,6 +17,7 @@ public class ResponsiveUI extends Thread {
|
||||
setDaemon(true);
|
||||
start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
d = d + (Math.PI + Math.E) / d;
|
||||
|
@ -6,12 +6,14 @@ import static net.mindview.util.Print.*;
|
||||
class Meal {
|
||||
private final int orderNum;
|
||||
public Meal(int orderNum) { this.orderNum = orderNum; }
|
||||
@Override
|
||||
public String toString() { return "Meal " + orderNum; }
|
||||
}
|
||||
|
||||
class WaitPerson implements Runnable {
|
||||
private Restaurant restaurant;
|
||||
public WaitPerson(Restaurant r) { restaurant = r; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -35,6 +37,7 @@ class Chef implements Runnable {
|
||||
private Restaurant restaurant;
|
||||
private int count = 0;
|
||||
public Chef(Restaurant r) { restaurant = r; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -5,10 +5,12 @@ public class SelfManaged implements Runnable {
|
||||
private int countDown = 5;
|
||||
private Thread t = new Thread(this);
|
||||
public SelfManaged() { t.start(); }
|
||||
@Override
|
||||
public String toString() {
|
||||
return Thread.currentThread().getName() +
|
||||
"(" + countDown + "), ";
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
System.out.print(this);
|
||||
|
@ -12,6 +12,7 @@ class CheckoutTask<T> implements Runnable {
|
||||
public CheckoutTask(Pool<T> pool) {
|
||||
this.pool = pool;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
T item = pool.checkOut();
|
||||
@ -23,6 +24,7 @@ class CheckoutTask<T> implements Runnable {
|
||||
// Acceptable way to terminate
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CheckoutTask " + id + " ";
|
||||
}
|
||||
@ -31,13 +33,12 @@ class CheckoutTask<T> implements Runnable {
|
||||
public class SemaphoreDemo {
|
||||
final static int SIZE = 25;
|
||||
public static void main(String[] args) throws Exception {
|
||||
final Pool<Fat> pool =
|
||||
new Pool<Fat>(Fat.class, SIZE);
|
||||
final Pool<Fat> pool = new Pool<>(Fat.class, SIZE);
|
||||
ExecutorService exec = Executors.newCachedThreadPool();
|
||||
for(int i = 0; i < SIZE; i++)
|
||||
exec.execute(new CheckoutTask<Fat>(pool));
|
||||
exec.execute(new CheckoutTask<>(pool));
|
||||
print("All CheckoutTasks created");
|
||||
List<Fat> list = new ArrayList<Fat>();
|
||||
List<Fat> list = new ArrayList<>();
|
||||
for(int i = 0; i < SIZE; i++) {
|
||||
Fat f = pool.checkOut();
|
||||
printnb(i + ": main() thread checked out ");
|
||||
@ -45,6 +46,7 @@ public class SemaphoreDemo {
|
||||
list.add(f);
|
||||
}
|
||||
Future<?> blocked = exec.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
// Semaphore prevents additional checkout,
|
||||
|
@ -36,6 +36,7 @@ public class SerialNumberChecker {
|
||||
private static ExecutorService exec =
|
||||
Executors.newCachedThreadPool();
|
||||
static class SerialChecker implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
int serial =
|
||||
|
@ -1,5 +1,5 @@
|
||||
//: concurrency/SettingDefaultHandler.java
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class SettingDefaultHandler {
|
||||
|
@ -4,6 +4,7 @@ import java.util.concurrent.*;
|
||||
import static net.mindview.util.Print.*;
|
||||
|
||||
public class SimpleDaemons implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
|
@ -8,11 +8,13 @@ abstract class Incrementable {
|
||||
}
|
||||
|
||||
class SynchronizingTest extends Incrementable {
|
||||
@Override
|
||||
public synchronized void increment() { ++counter; }
|
||||
}
|
||||
|
||||
class LockingTest extends Incrementable {
|
||||
private Lock lock = new ReentrantLock();
|
||||
@Override
|
||||
public void increment() {
|
||||
lock.lock();
|
||||
try {
|
||||
|
@ -9,9 +9,11 @@ public class SimplePriorities implements Runnable {
|
||||
public SimplePriorities(int priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return Thread.currentThread() + ": " + countDown;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
Thread.currentThread().setPriority(priority);
|
||||
while(true) {
|
||||
|
@ -9,9 +9,11 @@ public class SimpleThread extends Thread {
|
||||
super(Integer.toString(++threadCount));
|
||||
start();
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "#" + getName() + "(" + countDown + "), ";
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
while(true) {
|
||||
System.out.print(this);
|
||||
|
@ -3,13 +3,14 @@
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class SleepingTask extends LiftOff {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(countDown-- > 0) {
|
||||
System.out.print(status());
|
||||
// Old-style:
|
||||
// Thread.sleep(100);
|
||||
// Java SE5/6-style:
|
||||
// Java 5/6-style:
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
|
@ -24,6 +24,7 @@ public class SyncObject {
|
||||
public static void main(String[] args) {
|
||||
final DualSynch ds = new DualSynch();
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
ds.f();
|
||||
}
|
||||
|
@ -29,6 +29,7 @@ abstract class Accumulator {
|
||||
public abstract void accumulate();
|
||||
public abstract long read();
|
||||
private class Modifier implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
for(long i = 0; i < cycles; i++)
|
||||
accumulate();
|
||||
@ -41,6 +42,7 @@ abstract class Accumulator {
|
||||
}
|
||||
private class Reader implements Runnable {
|
||||
private volatile long value;
|
||||
@Override
|
||||
public void run() {
|
||||
for(long i = 0; i < cycles; i++)
|
||||
value = read();
|
||||
@ -73,10 +75,12 @@ abstract class Accumulator {
|
||||
|
||||
class SynchronizedTest extends Accumulator {
|
||||
{ id = "synch"; }
|
||||
@Override
|
||||
public synchronized void accumulate() {
|
||||
value += preLoaded[index++];
|
||||
if(index >= SIZE) index = 0;
|
||||
}
|
||||
@Override
|
||||
public synchronized long read() {
|
||||
return value;
|
||||
}
|
||||
@ -85,6 +89,7 @@ class SynchronizedTest extends Accumulator {
|
||||
class LockTest extends Accumulator {
|
||||
{ id = "Lock"; }
|
||||
private Lock lock = new ReentrantLock();
|
||||
@Override
|
||||
public void accumulate() {
|
||||
lock.lock();
|
||||
try {
|
||||
@ -94,6 +99,7 @@ class LockTest extends Accumulator {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public long read() {
|
||||
lock.lock();
|
||||
try {
|
||||
@ -111,6 +117,7 @@ class AtomicTest extends Accumulator {
|
||||
// Relying on more than one Atomic at a time doesn't
|
||||
// work, so we still have to synchronize. But it gives
|
||||
// a performance indicator:
|
||||
@Override
|
||||
public synchronized void accumulate() {
|
||||
int i;
|
||||
i = index.getAndIncrement();
|
||||
@ -118,7 +125,9 @@ class AtomicTest extends Accumulator {
|
||||
if(++i >= SIZE)
|
||||
index.set(0);
|
||||
}
|
||||
@Override
|
||||
public synchronized long read() { return value.get(); }
|
||||
@Override
|
||||
public void report(Accumulator acc2) {
|
||||
printf("%-22s: %.2f\n", "synch/(Atomic-synch)",
|
||||
(double)acc2.duration/
|
||||
|
@ -1,10 +1,11 @@
|
||||
//: concurrency/SynchronizedEvenGenerator.java
|
||||
// Simplifying mutexes with the synchronized keyword.
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
|
||||
public class
|
||||
SynchronizedEvenGenerator extends IntGenerator {
|
||||
private int currentEvenValue = 0;
|
||||
@Override
|
||||
public synchronized int next() {
|
||||
++currentEvenValue;
|
||||
Thread.yield(); // Cause failure faster
|
||||
|
@ -1,5 +1,5 @@
|
||||
//: concurrency/TestBlockingQueues.java
|
||||
// {RunByHand}
|
||||
// {TimeOutDuringTesting}
|
||||
import java.util.concurrent.*;
|
||||
import java.io.*;
|
||||
import static net.mindview.util.Print.*;
|
||||
@ -16,6 +16,7 @@ class LiftOffRunner implements Runnable {
|
||||
print("Interrupted during put()");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -58,10 +59,10 @@ public class TestBlockingQueues {
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
test("LinkedBlockingQueue", // Unlimited size
|
||||
new LinkedBlockingQueue<LiftOff>());
|
||||
new LinkedBlockingQueue<>());
|
||||
test("ArrayBlockingQueue", // Fixed size
|
||||
new ArrayBlockingQueue<LiftOff>(3));
|
||||
new ArrayBlockingQueue<>(3));
|
||||
test("SynchronousQueue", // Size of 1
|
||||
new SynchronousQueue<LiftOff>());
|
||||
new SynchronousQueue<>());
|
||||
}
|
||||
} ///:~
|
||||
|
@ -6,6 +6,7 @@ import java.util.*;
|
||||
class Accessor implements Runnable {
|
||||
private final int id;
|
||||
public Accessor(int idn) { id = idn; }
|
||||
@Override
|
||||
public void run() {
|
||||
while(!Thread.currentThread().isInterrupted()) {
|
||||
ThreadLocalVariableHolder.increment();
|
||||
@ -13,6 +14,7 @@ class Accessor implements Runnable {
|
||||
Thread.yield();
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "#" + id + ": " +
|
||||
ThreadLocalVariableHolder.get();
|
||||
@ -23,6 +25,7 @@ public class ThreadLocalVariableHolder {
|
||||
private static ThreadLocal<Integer> value =
|
||||
new ThreadLocal<Integer>() {
|
||||
private Random rand = new Random(47);
|
||||
@Override
|
||||
protected synchronized Integer initialValue() {
|
||||
return rand.nextInt(10000);
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ class InnerThread1 {
|
||||
super(name);
|
||||
start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
@ -23,6 +24,7 @@ class InnerThread1 {
|
||||
print("interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName() + ": " + countDown;
|
||||
}
|
||||
@ -38,6 +40,7 @@ class InnerThread2 {
|
||||
private Thread t;
|
||||
public InnerThread2(String name) {
|
||||
t = new Thread(name) {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
@ -49,6 +52,7 @@ class InnerThread2 {
|
||||
print("sleep() interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName() + ": " + countDown;
|
||||
}
|
||||
@ -67,6 +71,7 @@ class InnerRunnable1 {
|
||||
t = new Thread(this, name);
|
||||
t.start();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
@ -78,6 +83,7 @@ class InnerRunnable1 {
|
||||
print("sleep() interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return t.getName() + ": " + countDown;
|
||||
}
|
||||
@ -93,6 +99,7 @@ class InnerRunnable2 {
|
||||
private Thread t;
|
||||
public InnerRunnable2(String name) {
|
||||
t = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
@ -104,6 +111,7 @@ class InnerRunnable2 {
|
||||
print("sleep() interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return Thread.currentThread().getName() +
|
||||
": " + countDown;
|
||||
@ -122,6 +130,7 @@ class ThreadMethod {
|
||||
public void runTask() {
|
||||
if(t == null) {
|
||||
t = new Thread(name) {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(true) {
|
||||
@ -133,6 +142,7 @@ class ThreadMethod {
|
||||
print("sleep() interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return getName() + ": " + countDown;
|
||||
}
|
||||
|
@ -13,6 +13,7 @@ class Toast {
|
||||
public void jam() { status = Status.JAMMED; }
|
||||
public Status getStatus() { return status; }
|
||||
public int getId() { return id; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Toast " + id + ": " + status;
|
||||
}
|
||||
@ -25,6 +26,7 @@ class Toaster implements Runnable {
|
||||
private int count = 0;
|
||||
private Random rand = new Random(47);
|
||||
public Toaster(ToastQueue tq) { toastQueue = tq; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -50,6 +52,7 @@ class Butterer implements Runnable {
|
||||
dryQueue = dry;
|
||||
butteredQueue = buttered;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -73,6 +76,7 @@ class Jammer implements Runnable {
|
||||
butteredQueue = buttered;
|
||||
finishedQueue = finished;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -96,6 +100,7 @@ class Eater implements Runnable {
|
||||
public Eater(ToastQueue finished) {
|
||||
finishedQueue = finished;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
80
concurrency/build.xml
Normal file
80
concurrency/build.xml
Normal file
@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="concurrency"/>
|
||||
<property name="excludedfiles" value=""/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<touch file="failures"/>
|
||||
<jrun cls="ActiveObjectDemo" />
|
||||
<jrun cls="AtomicEvenGenerator" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="AtomicIntegerTest" />
|
||||
<jrun cls="AtomicityTest" />
|
||||
<jrun cls="AttemptLocking" />
|
||||
<jrun cls="BankTellerSimulation" arguments='5' />
|
||||
<jrun cls="BasicThreads" />
|
||||
<jrun cls="CachedThreadPool" />
|
||||
<jrun cls="CallableDemo" />
|
||||
<jrun cls="CaptureUncaughtException" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="CarBuilder" />
|
||||
<jrun cls="CloseResource" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="CountDownLatchDemo" />
|
||||
<jrun cls="concurrency.CriticalSection" dirpath="../concurrency" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="DaemonFromFactory" />
|
||||
<jrun cls="Daemons" />
|
||||
<jrun cls="DaemonsDontRunFinally" />
|
||||
<jrun cls="DeadlockingDiningPhilosophers" arguments='0 5 timeout' />
|
||||
<jrun cls="DelayQueueDemo" />
|
||||
<jrun cls="EvenGenerator" />
|
||||
<jrun cls="ExceptionThread" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="ExchangerDemo" />
|
||||
<jrun cls="concurrency.ExplicitCriticalSection" dirpath="../concurrency" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="FastSimulation" />
|
||||
<jrun cls="FixedDiningPhilosophers" arguments='5 5 timeout' />
|
||||
<jrun cls="FixedThreadPool" />
|
||||
<jrun cls="GreenhouseScheduler" arguments='5000' />
|
||||
<jrun cls="HorseRace" />
|
||||
<jrun cls="Interrupting" />
|
||||
<jrun cls="Interrupting2" />
|
||||
<jrun cls="InterruptingIdiom" arguments='1100' />
|
||||
<jrun cls="Joining" />
|
||||
<jrun cls="ListComparisons" arguments='1 10 10' />
|
||||
<jrun cls="MainThread" />
|
||||
<jrun cls="MapComparisons" arguments='1 10 10' />
|
||||
<jrun cls="MoreBasicThreads" />
|
||||
<jrun cls="MultiLock" />
|
||||
<jrun cls="MutexEvenGenerator" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="NaiveExceptionHandling" failOnError='false' msg='* Exception was Expected *' />
|
||||
<jrun cls="NIOInterruption" />
|
||||
<jrun cls="NotifyVsNotifyAll" />
|
||||
<jrun cls="OrnamentalGarden" />
|
||||
<jrun cls="PipedIO" />
|
||||
<jrun cls="PriorityBlockingQueueDemo" />
|
||||
<jrun cls="ReaderWriterList" />
|
||||
<jrun cls="ResponsiveUI" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="Restaurant" />
|
||||
<jrun cls="SelfManaged" />
|
||||
<jrun cls="SemaphoreDemo" />
|
||||
<jrun cls="SerialNumberChecker" arguments='4' />
|
||||
<jrun cls="SettingDefaultHandler" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="SimpleDaemons" />
|
||||
<jrun cls="SimpleMicroBenchmark" />
|
||||
<jrun cls="SimplePriorities" />
|
||||
<jrun cls="SimpleThread" />
|
||||
<jrun cls="SingleThreadExecutor" />
|
||||
<jrun cls="SleepingTask" />
|
||||
<jrun cls="SynchronizationComparisons" />
|
||||
<jrun cls="SynchronizedEvenGenerator" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="SyncObject" />
|
||||
<jrun cls="TestBlockingQueues" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />
|
||||
<jrun cls="ThreadLocalVariableHolder" />
|
||||
<jrun cls="ThreadVariations" />
|
||||
<jrun cls="ToastOMatic" />
|
||||
<jrun cls="concurrency.restaurant2.RestaurantWithQueues" dirpath="../concurrency/restaurant2" arguments='5' />
|
||||
<jrun cls="concurrency.waxomatic.WaxOMatic" dirpath="../concurrency/waxomatic" />
|
||||
<jrun cls="concurrency.waxomatic2.WaxOMatic2" dirpath="../concurrency/waxomatic2" />
|
||||
<delete file="failures"/>
|
||||
</target>
|
||||
|
||||
</project>
|
@ -21,6 +21,7 @@ class Order { // (A data-transfer object)
|
||||
public Food item() { return food; }
|
||||
public Customer getCustomer() { return customer; }
|
||||
public WaitPerson getWaitPerson() { return waitPerson; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order: " + id + " item: " + food +
|
||||
" for: " + customer +
|
||||
@ -38,6 +39,7 @@ class Plate {
|
||||
}
|
||||
public Order getOrder() { return order; }
|
||||
public Food getFood() { return food; }
|
||||
@Override
|
||||
public String toString() { return food.toString(); }
|
||||
}
|
||||
|
||||
@ -47,7 +49,7 @@ class Customer implements Runnable {
|
||||
private final WaitPerson waitPerson;
|
||||
// Only one course at a time can be received:
|
||||
private SynchronousQueue<Plate> placeSetting =
|
||||
new SynchronousQueue<Plate>();
|
||||
new SynchronousQueue<>();
|
||||
public Customer(WaitPerson w) { waitPerson = w; }
|
||||
public void
|
||||
deliver(Plate p) throws InterruptedException {
|
||||
@ -55,6 +57,7 @@ class Customer implements Runnable {
|
||||
// eating the previous course:
|
||||
placeSetting.put(p);
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
for(Course course : Course.values()) {
|
||||
Food food = course.randomSelection();
|
||||
@ -70,6 +73,7 @@ class Customer implements Runnable {
|
||||
}
|
||||
print(this + "finished meal, leaving");
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer " + id + " ";
|
||||
}
|
||||
@ -80,7 +84,7 @@ class WaitPerson implements Runnable {
|
||||
private final int id = counter++;
|
||||
private final Restaurant restaurant;
|
||||
BlockingQueue<Plate> filledOrders =
|
||||
new LinkedBlockingQueue<Plate>();
|
||||
new LinkedBlockingQueue<>();
|
||||
public WaitPerson(Restaurant rest) { restaurant = rest; }
|
||||
public void placeOrder(Customer cust, Food food) {
|
||||
try {
|
||||
@ -91,6 +95,7 @@ class WaitPerson implements Runnable {
|
||||
print(this + " placeOrder interrupted");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -106,6 +111,7 @@ class WaitPerson implements Runnable {
|
||||
}
|
||||
print(this + " off duty");
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "WaitPerson " + id + " ";
|
||||
}
|
||||
@ -117,6 +123,7 @@ class Chef implements Runnable {
|
||||
private final Restaurant restaurant;
|
||||
private static Random rand = new Random(47);
|
||||
public Chef(Restaurant rest) { restaurant = rest; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -133,17 +140,18 @@ class Chef implements Runnable {
|
||||
}
|
||||
print(this + " off duty");
|
||||
}
|
||||
@Override
|
||||
public String toString() { return "Chef " + id + " "; }
|
||||
}
|
||||
|
||||
class Restaurant implements Runnable {
|
||||
private List<WaitPerson> waitPersons =
|
||||
new ArrayList<WaitPerson>();
|
||||
private List<Chef> chefs = new ArrayList<Chef>();
|
||||
new ArrayList<>();
|
||||
private List<Chef> chefs = new ArrayList<>();
|
||||
private ExecutorService exec;
|
||||
private static Random rand = new Random(47);
|
||||
BlockingQueue<Order>
|
||||
orders = new LinkedBlockingQueue<Order>();
|
||||
orders = new LinkedBlockingQueue<>();
|
||||
public Restaurant(ExecutorService e, int nWaitPersons,
|
||||
int nChefs) {
|
||||
exec = e;
|
||||
@ -158,6 +166,7 @@ class Restaurant implements Runnable {
|
||||
exec.execute(chef);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -29,6 +29,7 @@ class Car {
|
||||
class WaxOn implements Runnable {
|
||||
private Car car;
|
||||
public WaxOn(Car c) { car = c; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -47,6 +48,7 @@ class WaxOn implements Runnable {
|
||||
class WaxOff implements Runnable {
|
||||
private Car car;
|
||||
public WaxOff(Car c) { car = c; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -50,6 +50,7 @@ class Car {
|
||||
class WaxOn implements Runnable {
|
||||
private Car car;
|
||||
public WaxOn(Car c) { car = c; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
@ -68,6 +69,7 @@ class WaxOn implements Runnable {
|
||||
class WaxOff implements Runnable {
|
||||
private Car car;
|
||||
public WaxOff(Car c) { car = c; }
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while(!Thread.interrupted()) {
|
||||
|
@ -20,6 +20,7 @@ public class AssociativeArray<K,V> {
|
||||
return (V)pairs[i][1];
|
||||
return null; // Did not find key
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for(int i = 0; i < index; i++) {
|
||||
@ -33,7 +34,7 @@ public class AssociativeArray<K,V> {
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
AssociativeArray<String,String> map =
|
||||
new AssociativeArray<String,String>(6);
|
||||
new AssociativeArray<>(6);
|
||||
map.put("sky", "blue");
|
||||
map.put("grass", "green");
|
||||
map.put("ocean", "dancing");
|
||||
|
@ -5,12 +5,16 @@ import java.util.*;
|
||||
class Element {
|
||||
private String ident;
|
||||
public Element(String id) { ident = id; }
|
||||
@Override
|
||||
public String toString() { return ident; }
|
||||
@Override
|
||||
public int hashCode() { return ident.hashCode(); }
|
||||
@Override
|
||||
public boolean equals(Object r) {
|
||||
return r instanceof Element &&
|
||||
ident.equals(((Element)r).ident);
|
||||
}
|
||||
@Override
|
||||
protected void finalize() {
|
||||
System.out.println("Finalizing " +
|
||||
getClass().getSimpleName() + " " + ident);
|
||||
@ -32,8 +36,7 @@ public class CanonicalMapping {
|
||||
if(args.length > 0)
|
||||
size = new Integer(args[0]);
|
||||
Key[] keys = new Key[size];
|
||||
WeakHashMap<Key,Value> map =
|
||||
new WeakHashMap<Key,Value>();
|
||||
WeakHashMap<Key,Value> map = new WeakHashMap<>();
|
||||
for(int i = 0; i < size; i++) {
|
||||
Key k = new Key(Integer.toString(i));
|
||||
Value v = new Value(Integer.toString(i));
|
||||
|
@ -5,14 +5,14 @@ import net.mindview.util.*;
|
||||
|
||||
public class CollectionDataGeneration {
|
||||
public static void main(String[] args) {
|
||||
System.out.println(new ArrayList<String>(
|
||||
System.out.println(new ArrayList<>(
|
||||
CollectionData.list( // Convenience method
|
||||
new RandomGenerator.String(9), 10)));
|
||||
System.out.println(new HashSet<Integer>(
|
||||
new CollectionData<Integer>(
|
||||
System.out.println(new HashSet<>(
|
||||
new CollectionData<>(
|
||||
new RandomGenerator.Integer(), 10)));
|
||||
}
|
||||
} /* Output:
|
||||
[YNzbrnyGc, FOWZnTcQr, GseGZMmJM, RoEsuEcUO, neOEdLsmw, HLGEahKcx, rEqUCBbkI, naMesbtWH, kjUrUkZPg, wsqPzDyCy]
|
||||
[573, 4779, 871, 4367, 6090, 7882, 2017, 8037, 3455, 299]
|
||||
[2017, 3455, 4779, 871, 6090, 573, 7882, 299, 8037, 4367]
|
||||
*///:~
|
||||
|
@ -7,13 +7,14 @@ class Government implements Generator<String> {
|
||||
"distributing swords is no basis for a system of " +
|
||||
"government").split(" ");
|
||||
private int index;
|
||||
@Override
|
||||
public String next() { return foundation[index++]; }
|
||||
}
|
||||
|
||||
public class CollectionDataTest {
|
||||
public static void main(String[] args) {
|
||||
Set<String> set = new LinkedHashSet<String>(
|
||||
new CollectionData<String>(new Government(), 15));
|
||||
Set<String> set = new LinkedHashSet<>(
|
||||
new CollectionData<>(new Government(), 15));
|
||||
// Using the convenience method:
|
||||
set.addAll(CollectionData.list(new Government(), 15));
|
||||
System.out.println(set);
|
||||
|
@ -6,7 +6,7 @@ import static net.mindview.util.Print.*;
|
||||
|
||||
public class CollectionMethods {
|
||||
public static void main(String[] args) {
|
||||
Collection<String> c = new ArrayList<String>();
|
||||
Collection<String> c = new ArrayList<>();
|
||||
c.addAll(Countries.names(6));
|
||||
c.add("ten");
|
||||
c.add("eleven");
|
||||
@ -21,7 +21,7 @@ public class CollectionMethods {
|
||||
print("Collections.max(c) = " + Collections.max(c));
|
||||
print("Collections.min(c) = " + Collections.min(c));
|
||||
// Add a Collection to another Collection
|
||||
Collection<String> c2 = new ArrayList<String>();
|
||||
Collection<String> c2 = new ArrayList<>();
|
||||
c2.addAll(Countries.names(6));
|
||||
c.addAll(c2);
|
||||
print(c);
|
||||
@ -50,25 +50,25 @@ public class CollectionMethods {
|
||||
// in c2 that also appear in c3:
|
||||
c2.removeAll(c3);
|
||||
print("c2.isEmpty() = " + c2.isEmpty());
|
||||
c = new ArrayList<String>();
|
||||
c = new ArrayList<>();
|
||||
c.addAll(Countries.names(6));
|
||||
print(c);
|
||||
c.clear(); // Remove all elements
|
||||
print("after c.clear():" + c);
|
||||
}
|
||||
} /* Output:
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven]
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven]
|
||||
Collections.max(c) = ten
|
||||
Collections.min(c) = ALGERIA
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
||||
[ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
||||
[BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||
[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||
[BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||
[ten, eleven]
|
||||
[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
||||
[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||
c.contains(BOTSWANA) = true
|
||||
c.containsAll(c2) = true
|
||||
[ANGOLA, BENIN]
|
||||
c2.isEmpty() = true
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||
after c.clear():[]
|
||||
*///:~
|
||||
|
@ -5,7 +5,7 @@ import static net.mindview.util.Print.*;
|
||||
|
||||
public class CountedString {
|
||||
private static List<String> created =
|
||||
new ArrayList<String>();
|
||||
new ArrayList<>();
|
||||
private String s;
|
||||
private int id = 0;
|
||||
public CountedString(String str) {
|
||||
@ -17,10 +17,12 @@ public class CountedString {
|
||||
if(s2.equals(s))
|
||||
id++;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "String: " + s + " id: " + id +
|
||||
" hashCode(): " + hashCode();
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
// The very simple approach:
|
||||
// return s.hashCode() * id;
|
||||
@ -30,6 +32,7 @@ public class CountedString {
|
||||
result = 37 * result + id;
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o instanceof CountedString &&
|
||||
s.equals(((CountedString)o).s) &&
|
||||
@ -37,7 +40,7 @@ public class CountedString {
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Map<CountedString,Integer> map =
|
||||
new HashMap<CountedString,Integer>();
|
||||
new HashMap<>();
|
||||
CountedString[] cs = new CountedString[5];
|
||||
for(int i = 0; i < cs.length; i++) {
|
||||
cs[i] = new CountedString("hi");
|
||||
|
@ -10,7 +10,7 @@ public class DequeTest {
|
||||
deque.addLast(i);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Deque<Integer> di = new Deque<Integer>();
|
||||
Deque<Integer> di = new Deque<>();
|
||||
fillTest(di);
|
||||
print(di);
|
||||
while(di.size() != 0)
|
||||
|
@ -6,13 +6,13 @@ import net.mindview.util.*;
|
||||
public class Enumerations {
|
||||
public static void main(String[] args) {
|
||||
Vector<String> v =
|
||||
new Vector<String>(Countries.names(10));
|
||||
new Vector<>(Countries.names(10));
|
||||
Enumeration<String> e = v.elements();
|
||||
while(e.hasMoreElements())
|
||||
System.out.print(e.nextElement() + ", ");
|
||||
// Produce an Enumeration from a Collection:
|
||||
e = Collections.enumeration(new ArrayList<String>());
|
||||
e = Collections.enumeration(new ArrayList<>());
|
||||
}
|
||||
} /* Output:
|
||||
ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC,
|
||||
ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, CHAD,
|
||||
*///:~
|
||||
|
@ -4,7 +4,7 @@ import java.util.*;
|
||||
|
||||
public class FailFast {
|
||||
public static void main(String[] args) {
|
||||
Collection<String> c = new ArrayList<String>();
|
||||
Collection<String> c = new ArrayList<>();
|
||||
Iterator<String> it = c.iterator();
|
||||
c.add("An object");
|
||||
try {
|
||||
|
@ -5,6 +5,7 @@ import java.util.*;
|
||||
class StringAddress {
|
||||
private String s;
|
||||
public StringAddress(String s) { this.s = s; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " " + s;
|
||||
}
|
||||
@ -12,7 +13,7 @@ class StringAddress {
|
||||
|
||||
public class FillingLists {
|
||||
public static void main(String[] args) {
|
||||
List<StringAddress> list= new ArrayList<StringAddress>(
|
||||
List<StringAddress> list = new ArrayList<>(
|
||||
Collections.nCopies(4, new StringAddress("Hello")));
|
||||
System.out.println(list);
|
||||
Collections.fill(list, new StringAddress("World!"));
|
||||
|
@ -4,6 +4,7 @@
|
||||
public class Groundhog {
|
||||
protected int number;
|
||||
public Groundhog(int n) { number = n; }
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Groundhog #" + number;
|
||||
}
|
||||
|
@ -4,7 +4,9 @@
|
||||
|
||||
public class Groundhog2 extends Groundhog {
|
||||
public Groundhog2(int n) { super(n); }
|
||||
@Override
|
||||
public int hashCode() { return number; }
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o instanceof Groundhog2 &&
|
||||
(number == ((Groundhog2)o).number);
|
||||
|
@ -5,7 +5,7 @@ import java.util.*;
|
||||
|
||||
public class IndividualTest {
|
||||
public static void main(String[] args) {
|
||||
Set<Individual> pets = new TreeSet<Individual>();
|
||||
Set<Individual> pets = new TreeSet<>();
|
||||
for(List<? extends Pet> lp :
|
||||
MapOfList.petPeople.values())
|
||||
for(Pet p : lp)
|
||||
|
@ -7,12 +7,10 @@ import static net.mindview.util.Print.*;
|
||||
public class LinkedHashMapDemo {
|
||||
public static void main(String[] args) {
|
||||
LinkedHashMap<Integer,String> linkedMap =
|
||||
new LinkedHashMap<Integer,String>(
|
||||
new CountingMapData(9));
|
||||
new LinkedHashMap<>(new CountingMapData(9));
|
||||
print(linkedMap);
|
||||
// Least-recently-used order:
|
||||
linkedMap =
|
||||
new LinkedHashMap<Integer,String>(16, 0.75f, true);
|
||||
linkedMap = new LinkedHashMap<>(16, 0.75f, true);
|
||||
linkedMap.putAll(new CountingMapData(9));
|
||||
print(linkedMap);
|
||||
for(int i = 0; i < 6; i++) // Cause accesses:
|
||||
|
@ -8,11 +8,12 @@ public class ListPerformance {
|
||||
static Random rand = new Random();
|
||||
static int reps = 1000;
|
||||
static List<Test<List<Integer>>> tests =
|
||||
new ArrayList<Test<List<Integer>>>();
|
||||
new ArrayList<>();
|
||||
static List<Test<LinkedList<Integer>>> qTests =
|
||||
new ArrayList<Test<LinkedList<Integer>>>();
|
||||
new ArrayList<>();
|
||||
static {
|
||||
tests.add(new Test<List<Integer>>("add") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int listSize = tp.size;
|
||||
@ -25,6 +26,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
tests.add(new Test<List<Integer>>("get") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops * reps;
|
||||
int listSize = list.size();
|
||||
@ -34,6 +36,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
tests.add(new Test<List<Integer>>("set") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops * reps;
|
||||
int listSize = list.size();
|
||||
@ -43,6 +46,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
tests.add(new Test<List<Integer>>("iteradd") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
final int LOOPS = 1000000;
|
||||
int half = list.size() / 2;
|
||||
@ -53,6 +57,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
tests.add(new Test<List<Integer>>("insert") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
for(int i = 0; i < loops; i++)
|
||||
@ -61,6 +66,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
tests.add(new Test<List<Integer>>("remove") {
|
||||
@Override
|
||||
int test(List<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int size = tp.size;
|
||||
@ -75,6 +81,7 @@ public class ListPerformance {
|
||||
});
|
||||
// Tests for queue behavior:
|
||||
qTests.add(new Test<LinkedList<Integer>>("addFirst") {
|
||||
@Override
|
||||
int test(LinkedList<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int size = tp.size;
|
||||
@ -87,6 +94,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
qTests.add(new Test<LinkedList<Integer>>("addLast") {
|
||||
@Override
|
||||
int test(LinkedList<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int size = tp.size;
|
||||
@ -100,6 +108,7 @@ public class ListPerformance {
|
||||
});
|
||||
qTests.add(
|
||||
new Test<LinkedList<Integer>>("rmFirst") {
|
||||
@Override
|
||||
int test(LinkedList<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int size = tp.size;
|
||||
@ -113,6 +122,7 @@ public class ListPerformance {
|
||||
}
|
||||
});
|
||||
qTests.add(new Test<LinkedList<Integer>>("rmLast") {
|
||||
@Override
|
||||
int test(LinkedList<Integer> list, TestParam tp) {
|
||||
int loops = tp.loops;
|
||||
int size = tp.size;
|
||||
@ -164,13 +174,13 @@ public class ListPerformance {
|
||||
10, 5000, 100, 5000, 1000, 1000, 10000, 200);
|
||||
if(args.length > 0)
|
||||
Tester.defaultParams = TestParam.array(args);
|
||||
ListTester.run(new ArrayList<Integer>(), tests);
|
||||
ListTester.run(new LinkedList<Integer>(), tests);
|
||||
ListTester.run(new Vector<Integer>(), tests);
|
||||
ListTester.run(new ArrayList<>(), tests);
|
||||
ListTester.run(new LinkedList<>(), tests);
|
||||
ListTester.run(new Vector<>(), tests);
|
||||
Tester.fieldWidth = 12;
|
||||
Tester<LinkedList<Integer>> qTest =
|
||||
new Tester<LinkedList<Integer>>(
|
||||
new LinkedList<Integer>(), qTests);
|
||||
new LinkedList<>(), qTests);
|
||||
qTest.setHeadline("Queue tests");
|
||||
qTest.timedTest();
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user