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.
|
All Rights Reserved.
|
||||||
|
|
||||||
Permission to use, copy, modify, and distribute this
|
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
|
3. Permission to incorporate the Source Code into printed
|
||||||
media may be obtained by contacting:
|
media may be obtained by contacting:
|
||||||
|
|
||||||
MindView, Inc. 5343 Valle Vista La Mesa, California 91941
|
MindView LLC, PO Box 969, Crested Butte, CO 81224
|
||||||
Wayne@MindView.net
|
MindViewInc@gmail.com
|
||||||
|
|
||||||
4. The Source Code and documentation are copyrighted by
|
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
|
or implied warranty of any kind, including any implied
|
||||||
warranty of merchantability, fitness for a particular
|
warranty of merchantability, fitness for a particular
|
||||||
purpose or non-infringement. MindView, Inc. does not
|
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,
|
warrant that the operation of any program that includes the
|
||||||
Inc. makes no representation about the suitability of 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
|
Source Code or of any software that includes the Source
|
||||||
Code for any purpose. The entire risk as to the quality
|
Code for any purpose. The entire risk as to the quality
|
||||||
and performance of any program that includes the Source
|
and performance of any program that includes the Source
|
||||||
Code is with the user of the Source Code. The user
|
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
|
exclusively for any reason on the Source Code or any
|
||||||
program that includes the Source Code. Should the Source
|
program that includes the Source Code. Should the Source
|
||||||
Code or any resulting software prove defective, the user
|
Code or any resulting software prove defective, the user
|
||||||
assumes the cost of all necessary servicing, repair, or
|
assumes the cost of all necessary servicing, repair, or
|
||||||
correction.
|
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,
|
LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT,
|
||||||
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||||
INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF
|
INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF
|
||||||
BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR
|
BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR
|
||||||
PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE
|
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
|
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, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED
|
PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED
|
||||||
HEREUNDER IS ON AN "AS IS" BASIS, WITHOUT ANY ACCOMPANYING
|
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,
|
OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
|
||||||
ENHANCEMENTS, OR MODIFICATIONS.
|
ENHANCEMENTS, OR MODIFICATIONS.
|
||||||
|
|
||||||
Please note that MindView, Inc. maintains a Web site which
|
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
|
is the sole distribution point for electronic copies of the
|
||||||
sites), where it is freely available under the terms stated above.
|
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,
|
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.
|
||||||
|
///:~
|
||||||
|
@ -5,4 +5,4 @@ public class SingleImport {
|
|||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
ArrayList list = new ArrayList();
|
ArrayList list = new ArrayList();
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
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 AtUnitExample4(String word) { this.word = word; }
|
||||||
public String getWord() { return word; }
|
public String getWord() { return word; }
|
||||||
public String scrambleWord() {
|
public String scrambleWord() {
|
||||||
List<Character> chars = new ArrayList<Character>();
|
List<Character> chars = new ArrayList<>();
|
||||||
for(Character c : word.toCharArray())
|
for(Character c : word.toCharArray())
|
||||||
chars.add(c);
|
chars.add(c);
|
||||||
Collections.shuffle(chars, rand);
|
Collections.shuffle(chars, rand);
|
||||||
|
@ -7,6 +7,7 @@ import net.mindview.util.*;
|
|||||||
public class AtUnitExample5 {
|
public class AtUnitExample5 {
|
||||||
private String text;
|
private String text;
|
||||||
public AtUnitExample5(String text) { this.text = text; }
|
public AtUnitExample5(String text) { this.text = text; }
|
||||||
|
@Override
|
||||||
public String toString() { return text; }
|
public String toString() { return text; }
|
||||||
@TestProperty static PrintWriter output;
|
@TestProperty static PrintWriter output;
|
||||||
@TestProperty static int counter;
|
@TestProperty static int counter;
|
||||||
|
@ -5,7 +5,7 @@ import net.mindview.atunit.*;
|
|||||||
import net.mindview.util.*;
|
import net.mindview.util.*;
|
||||||
|
|
||||||
public class HashSetTest {
|
public class HashSetTest {
|
||||||
HashSet<String> testObject = new HashSet<String>();
|
HashSet<String> testObject = new HashSet<>();
|
||||||
@Test void initialization() {
|
@Test void initialization() {
|
||||||
assert testObject.isEmpty();
|
assert testObject.isEmpty();
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ public class InterfaceExtractorProcessor
|
|||||||
implements AnnotationProcessor {
|
implements AnnotationProcessor {
|
||||||
private final AnnotationProcessorEnvironment env;
|
private final AnnotationProcessorEnvironment env;
|
||||||
private ArrayList<MethodDeclaration> interfaceMethods =
|
private ArrayList<MethodDeclaration> interfaceMethods =
|
||||||
new ArrayList<MethodDeclaration>();
|
new ArrayList<>();
|
||||||
public InterfaceExtractorProcessor(
|
public InterfaceExtractorProcessor(
|
||||||
AnnotationProcessorEnvironment env) { this.env = env; }
|
AnnotationProcessorEnvironment env) { this.env = env; }
|
||||||
public void process() {
|
public void process() {
|
||||||
@ -58,4 +58,4 @@ public class InterfaceExtractorProcessor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -20,4 +20,4 @@ public class InterfaceExtractorProcessorFactory
|
|||||||
public Collection<String> supportedOptions() {
|
public Collection<String> supportedOptions() {
|
||||||
return Collections.emptySet();
|
return Collections.emptySet();
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -4,7 +4,7 @@ package annotations;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
public class StackL<T> {
|
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 void push(T v) { list.addFirst(v); }
|
||||||
public T top() { return list.getFirst(); }
|
public T top() { return list.getFirst(); }
|
||||||
public T pop() { return list.removeFirst(); }
|
public T pop() { return list.removeFirst(); }
|
||||||
|
@ -18,7 +18,7 @@ public class UseCaseTracker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
List<Integer> useCases = new ArrayList<Integer>();
|
List<Integer> useCases = new ArrayList<>();
|
||||||
Collections.addAll(useCases, 47, 48, 49, 50);
|
Collections.addAll(useCases, 47, 48, 49, 50);
|
||||||
trackUseCases(useCases, PasswordUtils.class);
|
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 getHandle() { return handle; }
|
||||||
public String getFirstName() { return firstName; }
|
public String getFirstName() { return firstName; }
|
||||||
public String getLastName() { return lastName; }
|
public String getLastName() { return lastName; }
|
||||||
|
@Override
|
||||||
public String toString() { return handle; }
|
public String toString() { return handle; }
|
||||||
public Integer getAge() { return age; }
|
public Integer getAge() { return age; }
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -98,4 +98,4 @@ public class TableCreationProcessorFactory
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -24,7 +24,7 @@ public class TableCreator {
|
|||||||
// If the name is empty, use the Class name:
|
// If the name is empty, use the Class name:
|
||||||
if(tableName.length() < 1)
|
if(tableName.length() < 1)
|
||||||
tableName = cl.getName().toUpperCase();
|
tableName = cl.getName().toUpperCase();
|
||||||
List<String> columnDefs = new ArrayList<String>();
|
List<String> columnDefs = new ArrayList<>();
|
||||||
for(Field field : cl.getDeclaredFields()) {
|
for(Field field : cl.getDeclaredFields()) {
|
||||||
String columnName = null;
|
String columnName = null;
|
||||||
Annotation[] anns = field.getDeclaredAnnotations();
|
Annotation[] anns = field.getDeclaredAnnotations();
|
||||||
|
@ -8,14 +8,14 @@ public class ArrayOfGenerics {
|
|||||||
List<String>[] ls;
|
List<String>[] ls;
|
||||||
List[] la = new List[10];
|
List[] la = new List[10];
|
||||||
ls = (List<String>[])la; // "Unchecked" warning
|
ls = (List<String>[])la; // "Unchecked" warning
|
||||||
ls[0] = new ArrayList<String>();
|
ls[0] = new ArrayList<>();
|
||||||
// Compile-time checking produces an error:
|
// Compile-time checking produces an error:
|
||||||
//! ls[1] = new ArrayList<Integer>();
|
//! ls[1] = new ArrayList<Integer>();
|
||||||
|
|
||||||
// The problem: List<String> is a subtype of Object
|
// The problem: List<String> is a subtype of Object
|
||||||
Object[] objects = ls; // So assignment is OK
|
Object[] objects = ls; // So assignment is OK
|
||||||
// Compiles and runs without complaint:
|
// Compiles and runs without complaint:
|
||||||
objects[1] = new ArrayList<Integer>();
|
objects[1] = new ArrayList<>();
|
||||||
|
|
||||||
// However, if your needs are straightforward it is
|
// However, if your needs are straightforward it is
|
||||||
// possible to create an array of generics, albeit
|
// possible to create an array of generics, albeit
|
||||||
@ -23,6 +23,6 @@ public class ArrayOfGenerics {
|
|||||||
List<BerylliumSphere>[] spheres =
|
List<BerylliumSphere>[] spheres =
|
||||||
(List<BerylliumSphere>[])new List[10];
|
(List<BerylliumSphere>[])new List[10];
|
||||||
for(int i = 0; i < spheres.length; i++)
|
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;
|
i = n1;
|
||||||
j = n2;
|
j = n2;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
String result = "[i = " + i + ", j = " + j + "]";
|
String result = "[i = " + i + ", j = " + j + "]";
|
||||||
if(count++ % 3 == 0)
|
if(count++ % 3 == 0)
|
||||||
result += "\n";
|
result += "\n";
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public int compareTo(CompType rv) {
|
public int compareTo(CompType rv) {
|
||||||
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
|
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
|
||||||
}
|
}
|
||||||
private static Random r = new Random(47);
|
private static Random r = new Random(47);
|
||||||
public static Generator<CompType> generator() {
|
public static Generator<CompType> generator() {
|
||||||
return new Generator<CompType>() {
|
return new Generator<CompType>() {
|
||||||
|
@Override
|
||||||
public CompType next() {
|
public CompType next() {
|
||||||
return new CompType(r.nextInt(100),r.nextInt(100));
|
return new CompType(r.nextInt(100),r.nextInt(100));
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,7 @@ import static net.mindview.util.Print.*;
|
|||||||
class BerylliumSphere {
|
class BerylliumSphere {
|
||||||
private static long counter;
|
private static long counter;
|
||||||
private final long id = counter++;
|
private final long id = counter++;
|
||||||
|
@Override
|
||||||
public String toString() { return "Sphere " + id; }
|
public String toString() { return "Sphere " + id; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -16,8 +17,7 @@ public class ContainerComparison {
|
|||||||
print(Arrays.toString(spheres));
|
print(Arrays.toString(spheres));
|
||||||
print(spheres[4]);
|
print(spheres[4]);
|
||||||
|
|
||||||
List<BerylliumSphere> sphereList =
|
List<BerylliumSphere> sphereList= new ArrayList<>();
|
||||||
new ArrayList<BerylliumSphere>();
|
|
||||||
for(int i = 0; i < 5; i++)
|
for(int i = 0; i < 5; i++)
|
||||||
sphereList.add(new BerylliumSphere());
|
sphereList.add(new BerylliumSphere());
|
||||||
print(sphereList);
|
print(sphereList);
|
||||||
@ -27,7 +27,7 @@ public class ContainerComparison {
|
|||||||
print(Arrays.toString(integers));
|
print(Arrays.toString(integers));
|
||||||
print(integers[4]);
|
print(integers[4]);
|
||||||
|
|
||||||
List<Integer> intList = new ArrayList<Integer>(
|
List<Integer> intList = new ArrayList<>(
|
||||||
Arrays.asList(0, 1, 2, 3, 4, 5));
|
Arrays.asList(0, 1, 2, 3, 4, 5));
|
||||||
intList.add(97);
|
intList.add(97);
|
||||||
print(intList);
|
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>
|
public Future<Integer>
|
||||||
calculateInt(final int x, final int y) {
|
calculateInt(final int x, final int y) {
|
||||||
return ex.submit(new Callable<Integer>() {
|
return ex.submit(new Callable<Integer>() {
|
||||||
|
@Override
|
||||||
public Integer call() {
|
public Integer call() {
|
||||||
print("starting " + x + " + " + y);
|
print("starting " + x + " + " + y);
|
||||||
pause(500);
|
pause(500);
|
||||||
@ -33,6 +34,7 @@ public class ActiveObjectDemo {
|
|||||||
public Future<Float>
|
public Future<Float>
|
||||||
calculateFloat(final float x, final float y) {
|
calculateFloat(final float x, final float y) {
|
||||||
return ex.submit(new Callable<Float>() {
|
return ex.submit(new Callable<Float>() {
|
||||||
|
@Override
|
||||||
public Float call() {
|
public Float call() {
|
||||||
print("starting " + x + " + " + y);
|
print("starting " + x + " + " + y);
|
||||||
pause(2000);
|
pause(2000);
|
||||||
@ -45,7 +47,7 @@ public class ActiveObjectDemo {
|
|||||||
ActiveObjectDemo d1 = new ActiveObjectDemo();
|
ActiveObjectDemo d1 = new ActiveObjectDemo();
|
||||||
// Prevents ConcurrentModificationException:
|
// Prevents ConcurrentModificationException:
|
||||||
List<Future<?>> results =
|
List<Future<?>> results =
|
||||||
new CopyOnWriteArrayList<Future<?>>();
|
new CopyOnWriteArrayList<>();
|
||||||
for(float f = 0.0f; f < 1.0f; f += 0.2f)
|
for(float f = 0.0f; f < 1.0f; f += 0.2f)
|
||||||
results.add(d1.calculateFloat(f, f));
|
results.add(d1.calculateFloat(f, f));
|
||||||
for(int i = 0; i < 5; i++)
|
for(int i = 0; i < 5; i++)
|
||||||
|
@ -1,11 +1,12 @@
|
|||||||
//: concurrency/AtomicEvenGenerator.java
|
//: concurrency/AtomicEvenGenerator.java
|
||||||
// Atomic classes are occasionally useful in regular code.
|
// Atomic classes are occasionally useful in regular code.
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.util.concurrent.atomic.*;
|
import java.util.concurrent.atomic.*;
|
||||||
|
|
||||||
public class AtomicEvenGenerator extends IntGenerator {
|
public class AtomicEvenGenerator extends IntGenerator {
|
||||||
private AtomicInteger currentEvenValue =
|
private AtomicInteger currentEvenValue =
|
||||||
new AtomicInteger(0);
|
new AtomicInteger(0);
|
||||||
|
@Override
|
||||||
public int next() {
|
public int next() {
|
||||||
return currentEvenValue.addAndGet(2);
|
return currentEvenValue.addAndGet(2);
|
||||||
}
|
}
|
||||||
|
@ -7,12 +7,14 @@ public class AtomicIntegerTest implements Runnable {
|
|||||||
private AtomicInteger i = new AtomicInteger(0);
|
private AtomicInteger i = new AtomicInteger(0);
|
||||||
public int getValue() { return i.get(); }
|
public int getValue() { return i.get(); }
|
||||||
private void evenIncrement() { i.addAndGet(2); }
|
private void evenIncrement() { i.addAndGet(2); }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true)
|
while(true)
|
||||||
evenIncrement();
|
evenIncrement();
|
||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
new Timer().schedule(new TimerTask() {
|
new Timer().schedule(new TimerTask() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
System.err.println("Aborting");
|
System.err.println("Aborting");
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
|
@ -5,6 +5,7 @@ public class AtomicityTest implements Runnable {
|
|||||||
private int i = 0;
|
private int i = 0;
|
||||||
public int getValue() { return i; }
|
public int getValue() { return i; }
|
||||||
private synchronized void evenIncrement() { i++; i++; }
|
private synchronized void evenIncrement() { i++; i++; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true)
|
while(true)
|
||||||
evenIncrement();
|
evenIncrement();
|
||||||
|
@ -37,6 +37,7 @@ public class AttemptLocking {
|
|||||||
// Now create a separate task to grab the lock:
|
// Now create a separate task to grab the lock:
|
||||||
new Thread() {
|
new Thread() {
|
||||||
{ setDaemon(true); }
|
{ setDaemon(true); }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
al.lock.lock();
|
al.lock.lock();
|
||||||
System.out.println("acquired");
|
System.out.println("acquired");
|
||||||
|
@ -19,6 +19,7 @@ class CustomerLine extends ArrayBlockingQueue<Customer> {
|
|||||||
public CustomerLine(int maxLineSize) {
|
public CustomerLine(int maxLineSize) {
|
||||||
super(maxLineSize);
|
super(maxLineSize);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
if(this.size() == 0)
|
if(this.size() == 0)
|
||||||
return "[Empty]";
|
return "[Empty]";
|
||||||
@ -36,6 +37,7 @@ class CustomerGenerator implements Runnable {
|
|||||||
public CustomerGenerator(CustomerLine cq) {
|
public CustomerGenerator(CustomerLine cq) {
|
||||||
customers = cq;
|
customers = cq;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -96,9 +98,9 @@ class TellerManager implements Runnable {
|
|||||||
private ExecutorService exec;
|
private ExecutorService exec;
|
||||||
private CustomerLine customers;
|
private CustomerLine customers;
|
||||||
private PriorityQueue<Teller> workingTellers =
|
private PriorityQueue<Teller> workingTellers =
|
||||||
new PriorityQueue<Teller>();
|
new PriorityQueue<>();
|
||||||
private Queue<Teller> tellersDoingOtherThings =
|
private Queue<Teller> tellersDoingOtherThings =
|
||||||
new LinkedList<Teller>();
|
new LinkedList<>();
|
||||||
private int adjustmentPeriod;
|
private int adjustmentPeriod;
|
||||||
|
|
||||||
public TellerManager(ExecutorService e,
|
public TellerManager(ExecutorService e,
|
||||||
@ -146,6 +148,7 @@ class TellerManager implements Runnable {
|
|||||||
teller.doSomethingElse();
|
teller.doSomethingElse();
|
||||||
tellersDoingOtherThings.offer(teller);
|
tellersDoingOtherThings.offer(teller);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -161,6 +164,7 @@ class TellerManager implements Runnable {
|
|||||||
}
|
}
|
||||||
System.out.println(this + "terminating");
|
System.out.println(this + "terminating");
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() { return "TellerManager "; }
|
public String toString() { return "TellerManager "; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -201,4 +205,4 @@ Teller 0 interrupted
|
|||||||
Teller 0 terminating
|
Teller 0 terminating
|
||||||
CustomerGenerator interrupted
|
CustomerGenerator interrupted
|
||||||
CustomerGenerator terminating
|
CustomerGenerator terminating
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -7,6 +7,7 @@ class TaskWithResult implements Callable<String> {
|
|||||||
public TaskWithResult(int id) {
|
public TaskWithResult(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String call() {
|
public String call() {
|
||||||
return "result of TaskWithResult " + id;
|
return "result of TaskWithResult " + id;
|
||||||
}
|
}
|
||||||
@ -15,8 +16,7 @@ class TaskWithResult implements Callable<String> {
|
|||||||
public class CallableDemo {
|
public class CallableDemo {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
ExecutorService exec = Executors.newCachedThreadPool();
|
ExecutorService exec = Executors.newCachedThreadPool();
|
||||||
ArrayList<Future<String>> results =
|
ArrayList<Future<String>> results = new ArrayList<>();
|
||||||
new ArrayList<Future<String>>();
|
|
||||||
for(int i = 0; i < 10; i++)
|
for(int i = 0; i < 10; i++)
|
||||||
results.add(exec.submit(new TaskWithResult(i)));
|
results.add(exec.submit(new TaskWithResult(i)));
|
||||||
for(Future<String> fs : results)
|
for(Future<String> fs : results)
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
//: concurrency/CaptureUncaughtException.java
|
//: concurrency/CaptureUncaughtException.java
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
class ExceptionThread2 implements Runnable {
|
class ExceptionThread2 implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
Thread t = Thread.currentThread();
|
Thread t = Thread.currentThread();
|
||||||
System.out.println("run() by " + t);
|
System.out.println("run() by " + t);
|
||||||
@ -14,12 +15,14 @@ class ExceptionThread2 implements Runnable {
|
|||||||
|
|
||||||
class MyUncaughtExceptionHandler implements
|
class MyUncaughtExceptionHandler implements
|
||||||
Thread.UncaughtExceptionHandler {
|
Thread.UncaughtExceptionHandler {
|
||||||
|
@Override
|
||||||
public void uncaughtException(Thread t, Throwable e) {
|
public void uncaughtException(Thread t, Throwable e) {
|
||||||
System.out.println("caught " + e);
|
System.out.println("caught " + e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class HandlerThreadFactory implements ThreadFactory {
|
class HandlerThreadFactory implements ThreadFactory {
|
||||||
|
@Override
|
||||||
public Thread newThread(Runnable r) {
|
public Thread newThread(Runnable r) {
|
||||||
System.out.println(this + " creating new Thread");
|
System.out.println(this + " creating new Thread");
|
||||||
Thread t = new Thread(r);
|
Thread t = new Thread(r);
|
||||||
@ -45,4 +48,4 @@ eh = MyUncaughtExceptionHandler@1fb8ee3
|
|||||||
run() by Thread[Thread-0,5,main]
|
run() by Thread[Thread-0,5,main]
|
||||||
eh = MyUncaughtExceptionHandler@1fb8ee3
|
eh = MyUncaughtExceptionHandler@1fb8ee3
|
||||||
caught java.lang.RuntimeException
|
caught java.lang.RuntimeException
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -30,6 +30,7 @@ class ChassisBuilder implements Runnable {
|
|||||||
private CarQueue carQueue;
|
private CarQueue carQueue;
|
||||||
private int counter = 0;
|
private int counter = 0;
|
||||||
public ChassisBuilder(CarQueue cq) { carQueue = cq; }
|
public ChassisBuilder(CarQueue cq) { carQueue = cq; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -59,6 +60,7 @@ class Assembler implements Runnable {
|
|||||||
}
|
}
|
||||||
public Car car() { return car; }
|
public Car car() { return car; }
|
||||||
public CyclicBarrier barrier() { return barrier; }
|
public CyclicBarrier barrier() { return barrier; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -85,6 +87,7 @@ class Assembler implements Runnable {
|
|||||||
class Reporter implements Runnable {
|
class Reporter implements Runnable {
|
||||||
private CarQueue carQueue;
|
private CarQueue carQueue;
|
||||||
public Reporter(CarQueue cq) { carQueue = cq; }
|
public Reporter(CarQueue cq) { carQueue = cq; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -167,7 +170,7 @@ class WheelRobot extends Robot {
|
|||||||
|
|
||||||
class RobotPool {
|
class RobotPool {
|
||||||
// Quietly prevents identical entries:
|
// Quietly prevents identical entries:
|
||||||
private Set<Robot> pool = new HashSet<Robot>();
|
private Set<Robot> pool = new HashSet<>();
|
||||||
public synchronized void add(Robot r) {
|
public synchronized void add(Robot r) {
|
||||||
pool.add(r);
|
pool.add(r);
|
||||||
notifyAll();
|
notifyAll();
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
//: concurrency/CloseResource.java
|
//: concurrency/CloseResource.java
|
||||||
// Interrupting a blocked task by
|
// Interrupting a blocked task by
|
||||||
// closing the underlying resource.
|
// closing the underlying resource.
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
@ -12,6 +12,7 @@ class TaskPortion implements Runnable {
|
|||||||
TaskPortion(CountDownLatch latch) {
|
TaskPortion(CountDownLatch latch) {
|
||||||
this.latch = latch;
|
this.latch = latch;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
doWork();
|
doWork();
|
||||||
@ -24,6 +25,7 @@ class TaskPortion implements Runnable {
|
|||||||
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
|
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
|
||||||
print(this + "completed");
|
print(this + "completed");
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("%1$-3d ", id);
|
return String.format("%1$-3d ", id);
|
||||||
}
|
}
|
||||||
@ -37,6 +39,7 @@ class WaitingTask implements Runnable {
|
|||||||
WaitingTask(CountDownLatch latch) {
|
WaitingTask(CountDownLatch latch) {
|
||||||
this.latch = latch;
|
this.latch = latch;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
latch.await();
|
latch.await();
|
||||||
@ -45,6 +48,7 @@ class WaitingTask implements Runnable {
|
|||||||
print(this + " interrupted");
|
print(this + " interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("WaitingTask %1$-3d ", id);
|
return String.format("WaitingTask %1$-3d ", id);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
//: concurrency/CriticalSection.java
|
//: 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
|
// Synchronizing blocks instead of entire methods. Also
|
||||||
// demonstrates protection of a non-thread-safe class
|
// demonstrates protection of a non-thread-safe class
|
||||||
// with a thread-safe one.
|
// with a thread-safe one.
|
||||||
@ -19,6 +20,7 @@ class Pair { // Not thread-safe
|
|||||||
public int getY() { return y; }
|
public int getY() { return y; }
|
||||||
public void incrementX() { x++; }
|
public void incrementX() { x++; }
|
||||||
public void incrementY() { y++; }
|
public void incrementY() { y++; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "x: " + x + ", y: " + y;
|
return "x: " + x + ", y: " + y;
|
||||||
}
|
}
|
||||||
@ -40,7 +42,7 @@ abstract class PairManager {
|
|||||||
AtomicInteger checkCounter = new AtomicInteger(0);
|
AtomicInteger checkCounter = new AtomicInteger(0);
|
||||||
protected Pair p = new Pair();
|
protected Pair p = new Pair();
|
||||||
private List<Pair> storage =
|
private List<Pair> storage =
|
||||||
Collections.synchronizedList(new ArrayList<Pair>());
|
Collections.synchronizedList(new ArrayList<>());
|
||||||
public synchronized Pair getPair() {
|
public synchronized Pair getPair() {
|
||||||
// Make a copy to keep the original safe:
|
// Make a copy to keep the original safe:
|
||||||
return new Pair(p.getX(), p.getY());
|
return new Pair(p.getX(), p.getY());
|
||||||
@ -57,6 +59,7 @@ abstract class PairManager {
|
|||||||
|
|
||||||
// Synchronize the entire method:
|
// Synchronize the entire method:
|
||||||
class PairManager1 extends PairManager {
|
class PairManager1 extends PairManager {
|
||||||
|
@Override
|
||||||
public synchronized void increment() {
|
public synchronized void increment() {
|
||||||
p.incrementX();
|
p.incrementX();
|
||||||
p.incrementY();
|
p.incrementY();
|
||||||
@ -66,6 +69,7 @@ class PairManager1 extends PairManager {
|
|||||||
|
|
||||||
// Use a critical section:
|
// Use a critical section:
|
||||||
class PairManager2 extends PairManager {
|
class PairManager2 extends PairManager {
|
||||||
|
@Override
|
||||||
public void increment() {
|
public void increment() {
|
||||||
Pair temp;
|
Pair temp;
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
@ -82,10 +86,12 @@ class PairManipulator implements Runnable {
|
|||||||
public PairManipulator(PairManager pm) {
|
public PairManipulator(PairManager pm) {
|
||||||
this.pm = pm;
|
this.pm = pm;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true)
|
while(true)
|
||||||
pm.increment();
|
pm.increment();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Pair: " + pm.getPair() +
|
return "Pair: " + pm.getPair() +
|
||||||
" checkCounter = " + pm.checkCounter.get();
|
" checkCounter = " + pm.checkCounter.get();
|
||||||
@ -97,6 +103,7 @@ class PairChecker implements Runnable {
|
|||||||
public PairChecker(PairManager pm) {
|
public PairChecker(PairManager pm) {
|
||||||
this.pm = pm;
|
this.pm = pm;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true) {
|
while(true) {
|
||||||
pm.checkCounter.incrementAndGet();
|
pm.checkCounter.incrementAndGet();
|
||||||
@ -137,4 +144,4 @@ public class CriticalSection {
|
|||||||
} /* Output: (Sample)
|
} /* Output: (Sample)
|
||||||
pm1: Pair: x: 15, y: 15 checkCounter = 272565
|
pm1: Pair: x: 15, y: 15 checkCounter = 272565
|
||||||
pm2: Pair: x: 16, y: 16 checkCounter = 3956974
|
pm2: Pair: x: 16, y: 16 checkCounter = 3956974
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -5,6 +5,7 @@ import net.mindview.util.*;
|
|||||||
import static net.mindview.util.Print.*;
|
import static net.mindview.util.Print.*;
|
||||||
|
|
||||||
public class DaemonFromFactory implements Runnable {
|
public class DaemonFromFactory implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
|
@ -5,6 +5,7 @@ import static net.mindview.util.Print.*;
|
|||||||
|
|
||||||
class Daemon implements Runnable {
|
class Daemon implements Runnable {
|
||||||
private Thread[] t = new Thread[10];
|
private Thread[] t = new Thread[10];
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(int i = 0; i < t.length; i++) {
|
for(int i = 0; i < t.length; i++) {
|
||||||
t[i] = new Thread(new DaemonSpawn());
|
t[i] = new Thread(new DaemonSpawn());
|
||||||
@ -20,6 +21,7 @@ class Daemon implements Runnable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class DaemonSpawn implements Runnable {
|
class DaemonSpawn implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true)
|
while(true)
|
||||||
Thread.yield();
|
Thread.yield();
|
||||||
|
@ -4,6 +4,7 @@ import java.util.concurrent.*;
|
|||||||
import static net.mindview.util.Print.*;
|
import static net.mindview.util.Print.*;
|
||||||
|
|
||||||
class ADaemon implements Runnable {
|
class ADaemon implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
print("Starting ADaemon");
|
print("Starting ADaemon");
|
||||||
|
@ -10,24 +10,28 @@ class DelayedTask implements Runnable, Delayed {
|
|||||||
private final int delta;
|
private final int delta;
|
||||||
private final long trigger;
|
private final long trigger;
|
||||||
protected static List<DelayedTask> sequence =
|
protected static List<DelayedTask> sequence =
|
||||||
new ArrayList<DelayedTask>();
|
new ArrayList<>();
|
||||||
public DelayedTask(int delayInMilliseconds) {
|
public DelayedTask(int delayInMilliseconds) {
|
||||||
delta = delayInMilliseconds;
|
delta = delayInMilliseconds;
|
||||||
trigger = System.nanoTime() +
|
trigger = System.nanoTime() +
|
||||||
NANOSECONDS.convert(delta, MILLISECONDS);
|
NANOSECONDS.convert(delta, MILLISECONDS);
|
||||||
sequence.add(this);
|
sequence.add(this);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public long getDelay(TimeUnit unit) {
|
public long getDelay(TimeUnit unit) {
|
||||||
return unit.convert(
|
return unit.convert(
|
||||||
trigger - System.nanoTime(), NANOSECONDS);
|
trigger - System.nanoTime(), NANOSECONDS);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public int compareTo(Delayed arg) {
|
public int compareTo(Delayed arg) {
|
||||||
DelayedTask that = (DelayedTask)arg;
|
DelayedTask that = (DelayedTask)arg;
|
||||||
if(trigger < that.trigger) return -1;
|
if(trigger < that.trigger) return -1;
|
||||||
if(trigger > that.trigger) return 1;
|
if(trigger > that.trigger) return 1;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() { printnb(this + " "); }
|
public void run() { printnb(this + " "); }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("[%1$-4d]", delta) +
|
return String.format("[%1$-4d]", delta) +
|
||||||
" Task " + id;
|
" Task " + id;
|
||||||
@ -41,6 +45,7 @@ class DelayedTask implements Runnable, Delayed {
|
|||||||
super(delay);
|
super(delay);
|
||||||
exec = e;
|
exec = e;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(DelayedTask pt : sequence) {
|
for(DelayedTask pt : sequence) {
|
||||||
printnb(pt.summary() + " ");
|
printnb(pt.summary() + " ");
|
||||||
@ -57,6 +62,7 @@ class DelayedTaskConsumer implements Runnable {
|
|||||||
public DelayedTaskConsumer(DelayQueue<DelayedTask> q) {
|
public DelayedTaskConsumer(DelayQueue<DelayedTask> q) {
|
||||||
this.q = q;
|
this.q = q;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted())
|
while(!Thread.interrupted())
|
||||||
@ -73,7 +79,7 @@ public class DelayQueueDemo {
|
|||||||
Random rand = new Random(47);
|
Random rand = new Random(47);
|
||||||
ExecutorService exec = Executors.newCachedThreadPool();
|
ExecutorService exec = Executors.newCachedThreadPool();
|
||||||
DelayQueue<DelayedTask> queue =
|
DelayQueue<DelayedTask> queue =
|
||||||
new DelayQueue<DelayedTask>();
|
new DelayQueue<>();
|
||||||
// Fill with tasks that have random delays:
|
// Fill with tasks that have random delays:
|
||||||
for(int i = 0; i < 20; i++)
|
for(int i = 0; i < 20; i++)
|
||||||
queue.put(new DelayedTask(rand.nextInt(5000)));
|
queue.put(new DelayedTask(rand.nextInt(5000)));
|
||||||
|
@ -8,6 +8,7 @@ public class EvenChecker implements Runnable {
|
|||||||
generator = g;
|
generator = g;
|
||||||
id = ident;
|
id = ident;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(!generator.isCanceled()) {
|
while(!generator.isCanceled()) {
|
||||||
int val = generator.next();
|
int val = generator.next();
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
public class EvenGenerator extends IntGenerator {
|
public class EvenGenerator extends IntGenerator {
|
||||||
private int currentEvenValue = 0;
|
private int currentEvenValue = 0;
|
||||||
|
@Override
|
||||||
public int next() {
|
public int next() {
|
||||||
++currentEvenValue; // Danger point here!
|
++currentEvenValue; // Danger point here!
|
||||||
++currentEvenValue;
|
++currentEvenValue;
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
public class ExceptionThread implements Runnable {
|
public class ExceptionThread implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
throw new RuntimeException();
|
throw new RuntimeException();
|
||||||
}
|
}
|
||||||
|
@ -13,6 +13,7 @@ class ExchangerProducer<T> implements Runnable {
|
|||||||
generator = gen;
|
generator = gen;
|
||||||
this.holder = holder;
|
this.holder = holder;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -35,6 +36,7 @@ class ExchangerConsumer<T> implements Runnable {
|
|||||||
exchanger = ex;
|
exchanger = ex;
|
||||||
this.holder = holder;
|
this.holder = holder;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -60,14 +62,14 @@ public class ExchangerDemo {
|
|||||||
if(args.length > 1)
|
if(args.length > 1)
|
||||||
delay = new Integer(args[1]);
|
delay = new Integer(args[1]);
|
||||||
ExecutorService exec = Executors.newCachedThreadPool();
|
ExecutorService exec = Executors.newCachedThreadPool();
|
||||||
Exchanger<List<Fat>> xc = new Exchanger<List<Fat>>();
|
Exchanger<List<Fat>> xc = new Exchanger<>();
|
||||||
List<Fat>
|
List<Fat>
|
||||||
producerList = new CopyOnWriteArrayList<Fat>(),
|
producerList = new CopyOnWriteArrayList<>(),
|
||||||
consumerList = new CopyOnWriteArrayList<Fat>();
|
consumerList = new CopyOnWriteArrayList<>();
|
||||||
exec.execute(new ExchangerProducer<Fat>(xc,
|
exec.execute(new ExchangerProducer<>(xc,
|
||||||
BasicGenerator.create(Fat.class), producerList));
|
BasicGenerator.create(Fat.class), producerList));
|
||||||
exec.execute(
|
exec.execute(
|
||||||
new ExchangerConsumer<Fat>(xc,consumerList));
|
new ExchangerConsumer<>(xc,consumerList));
|
||||||
TimeUnit.SECONDS.sleep(delay);
|
TimeUnit.SECONDS.sleep(delay);
|
||||||
exec.shutdownNow();
|
exec.shutdownNow();
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ import java.util.concurrent.locks.*;
|
|||||||
// Synchronize the entire method:
|
// Synchronize the entire method:
|
||||||
class ExplicitPairManager1 extends PairManager {
|
class ExplicitPairManager1 extends PairManager {
|
||||||
private Lock lock = new ReentrantLock();
|
private Lock lock = new ReentrantLock();
|
||||||
|
@Override
|
||||||
public void increment() {
|
public void increment() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
@ -22,6 +23,7 @@ class ExplicitPairManager1 extends PairManager {
|
|||||||
// Use a critical section:
|
// Use a critical section:
|
||||||
class ExplicitPairManager2 extends PairManager {
|
class ExplicitPairManager2 extends PairManager {
|
||||||
private Lock lock = new ReentrantLock();
|
private Lock lock = new ReentrantLock();
|
||||||
|
@Override
|
||||||
public void increment() {
|
public void increment() {
|
||||||
Pair temp;
|
Pair temp;
|
||||||
lock.lock();
|
lock.lock();
|
||||||
@ -43,4 +45,4 @@ public class ExplicitCriticalSection {
|
|||||||
pman2 = new ExplicitPairManager2();
|
pman2 = new ExplicitPairManager2();
|
||||||
CriticalSection.testApproaches(pman1, pman2);
|
CriticalSection.testApproaches(pman1, pman2);
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -12,6 +12,7 @@ public class FastSimulation {
|
|||||||
new AtomicInteger[N_ELEMENTS][N_GENES];
|
new AtomicInteger[N_ELEMENTS][N_GENES];
|
||||||
static Random rand = new Random(47);
|
static Random rand = new Random(47);
|
||||||
static class Evolver implements Runnable {
|
static class Evolver implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
// Randomly select an element to work on:
|
// Randomly select an element to work on:
|
||||||
|
@ -12,5 +12,6 @@ public class Fat {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
public void operation() { System.out.println(this); }
|
public void operation() { System.out.println(this); }
|
||||||
|
@Override
|
||||||
public String toString() { return "Fat id: " + id; }
|
public String toString() { return "Fat id: " + id; }
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -26,6 +26,7 @@ public class GreenhouseScheduler {
|
|||||||
event, initialDelay, period, TimeUnit.MILLISECONDS);
|
event, initialDelay, period, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
class LightOn implements Runnable {
|
class LightOn implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here to
|
// Put hardware control code here to
|
||||||
// physically turn on the light.
|
// physically turn on the light.
|
||||||
@ -34,6 +35,7 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class LightOff implements Runnable {
|
class LightOff implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here to
|
// Put hardware control code here to
|
||||||
// physically turn off the light.
|
// physically turn off the light.
|
||||||
@ -42,6 +44,7 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class WaterOn implements Runnable {
|
class WaterOn implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here.
|
// Put hardware control code here.
|
||||||
System.out.println("Turning greenhouse water on");
|
System.out.println("Turning greenhouse water on");
|
||||||
@ -49,6 +52,7 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class WaterOff implements Runnable {
|
class WaterOff implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here.
|
// Put hardware control code here.
|
||||||
System.out.println("Turning greenhouse water off");
|
System.out.println("Turning greenhouse water off");
|
||||||
@ -56,6 +60,7 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ThermostatNight implements Runnable {
|
class ThermostatNight implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here.
|
// Put hardware control code here.
|
||||||
System.out.println("Thermostat to night setting");
|
System.out.println("Thermostat to night setting");
|
||||||
@ -63,6 +68,7 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class ThermostatDay implements Runnable {
|
class ThermostatDay implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Put hardware control code here.
|
// Put hardware control code here.
|
||||||
System.out.println("Thermostat to day setting");
|
System.out.println("Thermostat to day setting");
|
||||||
@ -70,15 +76,18 @@ public class GreenhouseScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
class Bell implements Runnable {
|
class Bell implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() { System.out.println("Bing!"); }
|
public void run() { System.out.println("Bing!"); }
|
||||||
}
|
}
|
||||||
class Terminate implements Runnable {
|
class Terminate implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
System.out.println("Terminating");
|
System.out.println("Terminating");
|
||||||
scheduler.shutdownNow();
|
scheduler.shutdownNow();
|
||||||
// Must start a separate task to do this job,
|
// Must start a separate task to do this job,
|
||||||
// since the scheduler was shut down:
|
// since the scheduler was shut down:
|
||||||
new Thread() {
|
new Thread() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(DataPoint d : data)
|
for(DataPoint d : data)
|
||||||
System.out.println(d);
|
System.out.println(d);
|
||||||
@ -96,6 +105,7 @@ public class GreenhouseScheduler {
|
|||||||
temperature = temp;
|
temperature = temp;
|
||||||
humidity = hum;
|
humidity = hum;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return time.getTime() +
|
return time.getTime() +
|
||||||
String.format(
|
String.format(
|
||||||
@ -114,8 +124,9 @@ public class GreenhouseScheduler {
|
|||||||
private int humidityDirection = +1;
|
private int humidityDirection = +1;
|
||||||
private Random rand = new Random(47);
|
private Random rand = new Random(47);
|
||||||
List<DataPoint> data = Collections.synchronizedList(
|
List<DataPoint> data = Collections.synchronizedList(
|
||||||
new ArrayList<DataPoint>());
|
new ArrayList<>());
|
||||||
class CollectData implements Runnable {
|
class CollectData implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
System.out.println("Collecting data");
|
System.out.println("Collecting data");
|
||||||
synchronized(GreenhouseScheduler.this) {
|
synchronized(GreenhouseScheduler.this) {
|
||||||
@ -153,4 +164,4 @@ public class GreenhouseScheduler {
|
|||||||
gh.repeat(gh.new ThermostatDay(), 0, 1400);
|
gh.repeat(gh.new ThermostatDay(), 0, 1400);
|
||||||
gh.repeat(gh.new CollectData(), 500, 500);
|
gh.repeat(gh.new CollectData(), 500, 500);
|
||||||
}
|
}
|
||||||
} /* (Execute to see output) *///:~
|
} /* (Execute to see output) *///:~
|
||||||
|
@ -12,6 +12,7 @@ class Horse implements Runnable {
|
|||||||
private static CyclicBarrier barrier;
|
private static CyclicBarrier barrier;
|
||||||
public Horse(CyclicBarrier b) { barrier = b; }
|
public Horse(CyclicBarrier b) { barrier = b; }
|
||||||
public synchronized int getStrides() { return strides; }
|
public synchronized int getStrides() { return strides; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -27,6 +28,7 @@ class Horse implements Runnable {
|
|||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() { return "Horse " + id + " "; }
|
public String toString() { return "Horse " + id + " "; }
|
||||||
public String tracks() {
|
public String tracks() {
|
||||||
StringBuilder s = new StringBuilder();
|
StringBuilder s = new StringBuilder();
|
||||||
@ -39,12 +41,13 @@ class Horse implements Runnable {
|
|||||||
|
|
||||||
public class HorseRace {
|
public class HorseRace {
|
||||||
static final int FINISH_LINE = 75;
|
static final int FINISH_LINE = 75;
|
||||||
private List<Horse> horses = new ArrayList<Horse>();
|
private List<Horse> horses = new ArrayList<>();
|
||||||
private ExecutorService exec =
|
private ExecutorService exec =
|
||||||
Executors.newCachedThreadPool();
|
Executors.newCachedThreadPool();
|
||||||
private CyclicBarrier barrier;
|
private CyclicBarrier barrier;
|
||||||
public HorseRace(int nHorses, final int pause) {
|
public HorseRace(int nHorses, final int pause) {
|
||||||
barrier = new CyclicBarrier(nHorses, new Runnable() {
|
barrier = new CyclicBarrier(nHorses, new Runnable() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
StringBuilder s = new StringBuilder();
|
StringBuilder s = new StringBuilder();
|
||||||
for(int i = 0; i < FINISH_LINE; i++)
|
for(int i = 0; i < FINISH_LINE; i++)
|
||||||
|
@ -5,6 +5,7 @@ import java.io.*;
|
|||||||
import static net.mindview.util.Print.*;
|
import static net.mindview.util.Print.*;
|
||||||
|
|
||||||
class SleepBlocked implements Runnable {
|
class SleepBlocked implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
TimeUnit.SECONDS.sleep(100);
|
TimeUnit.SECONDS.sleep(100);
|
||||||
@ -18,6 +19,7 @@ class SleepBlocked implements Runnable {
|
|||||||
class IOBlocked implements Runnable {
|
class IOBlocked implements Runnable {
|
||||||
private InputStream in;
|
private InputStream in;
|
||||||
public IOBlocked(InputStream is) { in = is; }
|
public IOBlocked(InputStream is) { in = is; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
print("Waiting for read():");
|
print("Waiting for read():");
|
||||||
@ -40,11 +42,13 @@ class SynchronizedBlocked implements Runnable {
|
|||||||
}
|
}
|
||||||
public SynchronizedBlocked() {
|
public SynchronizedBlocked() {
|
||||||
new Thread() {
|
new Thread() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
f(); // Lock acquired by this thread
|
f(); // Lock acquired by this thread
|
||||||
}
|
}
|
||||||
}.start();
|
}.start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
print("Trying to call f()");
|
print("Trying to call f()");
|
||||||
f();
|
f();
|
||||||
|
@ -24,6 +24,7 @@ class BlockedMutex {
|
|||||||
|
|
||||||
class Blocked2 implements Runnable {
|
class Blocked2 implements Runnable {
|
||||||
BlockedMutex blocked = new BlockedMutex();
|
BlockedMutex blocked = new BlockedMutex();
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
print("Waiting for f() in BlockedMutex");
|
print("Waiting for f() in BlockedMutex");
|
||||||
blocked.f();
|
blocked.f();
|
||||||
|
@ -17,6 +17,7 @@ class NeedsCleanup {
|
|||||||
|
|
||||||
class Blocked3 implements Runnable {
|
class Blocked3 implements Runnable {
|
||||||
private volatile double d = 0.0;
|
private volatile double d = 0.0;
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
|
@ -9,6 +9,7 @@ class Sleeper extends Thread {
|
|||||||
duration = sleepTime;
|
duration = sleepTime;
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
sleep(duration);
|
sleep(duration);
|
||||||
@ -28,6 +29,7 @@ class Joiner extends Thread {
|
|||||||
this.sleeper = sleeper;
|
this.sleeper = sleeper;
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
sleeper.join();
|
sleeper.join();
|
||||||
|
@ -13,6 +13,7 @@ public class LiftOff implements Runnable {
|
|||||||
return "#" + id + "(" +
|
return "#" + id + "(" +
|
||||||
(countDown > 0 ? countDown : "Liftoff!") + "), ";
|
(countDown > 0 ? countDown : "Liftoff!") + "), ";
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(countDown-- > 0) {
|
while(countDown-- > 0) {
|
||||||
System.out.print(status());
|
System.out.print(status());
|
||||||
|
@ -42,7 +42,7 @@ abstract class ListTest extends Tester<List<Integer>> {
|
|||||||
class SynchronizedArrayListTest extends ListTest {
|
class SynchronizedArrayListTest extends ListTest {
|
||||||
List<Integer> containerInitializer() {
|
List<Integer> containerInitializer() {
|
||||||
return Collections.synchronizedList(
|
return Collections.synchronizedList(
|
||||||
new ArrayList<Integer>(
|
new ArrayList<>(
|
||||||
new CountingIntegerList(containerSize)));
|
new CountingIntegerList(containerSize)));
|
||||||
}
|
}
|
||||||
SynchronizedArrayListTest(int nReaders, int nWriters) {
|
SynchronizedArrayListTest(int nReaders, int nWriters) {
|
||||||
@ -52,7 +52,7 @@ class SynchronizedArrayListTest extends ListTest {
|
|||||||
|
|
||||||
class CopyOnWriteArrayListTest extends ListTest {
|
class CopyOnWriteArrayListTest extends ListTest {
|
||||||
List<Integer> containerInitializer() {
|
List<Integer> containerInitializer() {
|
||||||
return new CopyOnWriteArrayList<Integer>(
|
return new CopyOnWriteArrayList<>(
|
||||||
new CountingIntegerList(containerSize));
|
new CountingIntegerList(containerSize));
|
||||||
}
|
}
|
||||||
CopyOnWriteArrayListTest(int nReaders, int nWriters) {
|
CopyOnWriteArrayListTest(int nReaders, int nWriters) {
|
||||||
|
@ -43,7 +43,7 @@ extends Tester<Map<Integer,Integer>> {
|
|||||||
class SynchronizedHashMapTest extends MapTest {
|
class SynchronizedHashMapTest extends MapTest {
|
||||||
Map<Integer,Integer> containerInitializer() {
|
Map<Integer,Integer> containerInitializer() {
|
||||||
return Collections.synchronizedMap(
|
return Collections.synchronizedMap(
|
||||||
new HashMap<Integer,Integer>(
|
new HashMap<>(
|
||||||
MapData.map(
|
MapData.map(
|
||||||
new CountingGenerator.Integer(),
|
new CountingGenerator.Integer(),
|
||||||
new CountingGenerator.Integer(),
|
new CountingGenerator.Integer(),
|
||||||
@ -56,7 +56,7 @@ class SynchronizedHashMapTest extends MapTest {
|
|||||||
|
|
||||||
class ConcurrentHashMapTest extends MapTest {
|
class ConcurrentHashMapTest extends MapTest {
|
||||||
Map<Integer,Integer> containerInitializer() {
|
Map<Integer,Integer> containerInitializer() {
|
||||||
return new ConcurrentHashMap<Integer,Integer>(
|
return new ConcurrentHashMap<>(
|
||||||
MapData.map(
|
MapData.map(
|
||||||
new CountingGenerator.Integer(),
|
new CountingGenerator.Integer(),
|
||||||
new CountingGenerator.Integer(), containerSize));
|
new CountingGenerator.Integer(), containerSize));
|
||||||
|
@ -18,6 +18,7 @@ public class MultiLock {
|
|||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
final MultiLock multiLock = new MultiLock();
|
final MultiLock multiLock = new MultiLock();
|
||||||
new Thread() {
|
new Thread() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
multiLock.f1(10);
|
multiLock.f1(10);
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,12 @@
|
|||||||
//: concurrency/MutexEvenGenerator.java
|
//: concurrency/MutexEvenGenerator.java
|
||||||
// Preventing thread collisions with mutexes.
|
// Preventing thread collisions with mutexes.
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.util.concurrent.locks.*;
|
import java.util.concurrent.locks.*;
|
||||||
|
|
||||||
public class MutexEvenGenerator extends IntGenerator {
|
public class MutexEvenGenerator extends IntGenerator {
|
||||||
private int currentEvenValue = 0;
|
private int currentEvenValue = 0;
|
||||||
private Lock lock = new ReentrantLock();
|
private Lock lock = new ReentrantLock();
|
||||||
|
@Override
|
||||||
public int next() {
|
public int next() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
|
@ -10,6 +10,7 @@ import static net.mindview.util.Print.*;
|
|||||||
class NIOBlocked implements Runnable {
|
class NIOBlocked implements Runnable {
|
||||||
private final SocketChannel sc;
|
private final SocketChannel sc;
|
||||||
public NIOBlocked(SocketChannel sc) { this.sc = sc; }
|
public NIOBlocked(SocketChannel sc) { this.sc = sc; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
print("Waiting for read() in " + this);
|
print("Waiting for read() in " + this);
|
||||||
|
@ -13,4 +13,4 @@ public class NaiveExceptionHandling {
|
|||||||
System.out.println("Exception was handled!");
|
System.out.println("Exception was handled!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -19,12 +19,14 @@ class Blocker {
|
|||||||
|
|
||||||
class Task implements Runnable {
|
class Task implements Runnable {
|
||||||
static Blocker blocker = new Blocker();
|
static Blocker blocker = new Blocker();
|
||||||
|
@Override
|
||||||
public void run() { blocker.waitingCall(); }
|
public void run() { blocker.waitingCall(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
class Task2 implements Runnable {
|
class Task2 implements Runnable {
|
||||||
// A separate Blocker object:
|
// A separate Blocker object:
|
||||||
static Blocker blocker = new Blocker();
|
static Blocker blocker = new Blocker();
|
||||||
|
@Override
|
||||||
public void run() { blocker.waitingCall(); }
|
public void run() { blocker.waitingCall(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,6 +39,7 @@ public class NotifyVsNotifyAll {
|
|||||||
Timer timer = new Timer();
|
Timer timer = new Timer();
|
||||||
timer.scheduleAtFixedRate(new TimerTask() {
|
timer.scheduleAtFixedRate(new TimerTask() {
|
||||||
boolean prod = true;
|
boolean prod = true;
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
if(prod) {
|
if(prod) {
|
||||||
System.out.print("\nnotify() ");
|
System.out.print("\nnotify() ");
|
||||||
|
@ -19,7 +19,7 @@ class Count {
|
|||||||
class Entrance implements Runnable {
|
class Entrance implements Runnable {
|
||||||
private static Count count = new Count();
|
private static Count count = new Count();
|
||||||
private static List<Entrance> entrances =
|
private static List<Entrance> entrances =
|
||||||
new ArrayList<Entrance>();
|
new ArrayList<>();
|
||||||
private int number = 0;
|
private int number = 0;
|
||||||
// Doesn't need synchronization to read:
|
// Doesn't need synchronization to read:
|
||||||
private final int id;
|
private final int id;
|
||||||
@ -32,6 +32,7 @@ class Entrance implements Runnable {
|
|||||||
// garbage collection of dead tasks:
|
// garbage collection of dead tasks:
|
||||||
entrances.add(this);
|
entrances.add(this);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(!canceled) {
|
while(!canceled) {
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
@ -47,6 +48,7 @@ class Entrance implements Runnable {
|
|||||||
print("Stopping " + this);
|
print("Stopping " + this);
|
||||||
}
|
}
|
||||||
public synchronized int getValue() { return number; }
|
public synchronized int getValue() { return number; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Entrance " + id + ": " + getValue();
|
return "Entrance " + id + ": " + getValue();
|
||||||
}
|
}
|
||||||
|
@ -22,6 +22,7 @@ public class Philosopher implements Runnable {
|
|||||||
id = ident;
|
id = ident;
|
||||||
ponderFactor = ponder;
|
ponderFactor = ponder;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -41,5 +42,6 @@ public class Philosopher implements Runnable {
|
|||||||
print(this + " " + "exiting via interrupt");
|
print(this + " " + "exiting via interrupt");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() { return "Philosopher " + id; }
|
public String toString() { return "Philosopher " + id; }
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -9,6 +9,7 @@ class Sender implements Runnable {
|
|||||||
private Random rand = new Random(47);
|
private Random rand = new Random(47);
|
||||||
private PipedWriter out = new PipedWriter();
|
private PipedWriter out = new PipedWriter();
|
||||||
public PipedWriter getPipedWriter() { return out; }
|
public PipedWriter getPipedWriter() { return out; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true)
|
while(true)
|
||||||
@ -29,6 +30,7 @@ class Receiver implements Runnable {
|
|||||||
public Receiver(Sender sender) throws IOException {
|
public Receiver(Sender sender) throws IOException {
|
||||||
in = new PipedReader(sender.getPipedWriter());
|
in = new PipedReader(sender.getPipedWriter());
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
|
@ -6,7 +6,7 @@ import java.util.*;
|
|||||||
|
|
||||||
public class Pool<T> {
|
public class Pool<T> {
|
||||||
private int size;
|
private int size;
|
||||||
private List<T> items = new ArrayList<T>();
|
private List<T> items = new ArrayList<>();
|
||||||
private volatile boolean[] checkedOut;
|
private volatile boolean[] checkedOut;
|
||||||
private Semaphore available;
|
private Semaphore available;
|
||||||
public Pool(Class<T> classObject, int size) {
|
public Pool(Class<T> classObject, int size) {
|
||||||
|
@ -10,15 +10,17 @@ Runnable, Comparable<PrioritizedTask> {
|
|||||||
private final int id = counter++;
|
private final int id = counter++;
|
||||||
private final int priority;
|
private final int priority;
|
||||||
protected static List<PrioritizedTask> sequence =
|
protected static List<PrioritizedTask> sequence =
|
||||||
new ArrayList<PrioritizedTask>();
|
new ArrayList<>();
|
||||||
public PrioritizedTask(int priority) {
|
public PrioritizedTask(int priority) {
|
||||||
this.priority = priority;
|
this.priority = priority;
|
||||||
sequence.add(this);
|
sequence.add(this);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public int compareTo(PrioritizedTask arg) {
|
public int compareTo(PrioritizedTask arg) {
|
||||||
return priority < arg.priority ? 1 :
|
return priority < arg.priority ? 1 :
|
||||||
(priority > arg.priority ? -1 : 0);
|
(priority > arg.priority ? -1 : 0);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
TimeUnit.MILLISECONDS.sleep(rand.nextInt(250));
|
TimeUnit.MILLISECONDS.sleep(rand.nextInt(250));
|
||||||
@ -27,6 +29,7 @@ Runnable, Comparable<PrioritizedTask> {
|
|||||||
}
|
}
|
||||||
print(this);
|
print(this);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return String.format("[%1$-3d]", priority) +
|
return String.format("[%1$-3d]", priority) +
|
||||||
" Task " + id;
|
" Task " + id;
|
||||||
@ -40,6 +43,7 @@ Runnable, Comparable<PrioritizedTask> {
|
|||||||
super(-1); // Lowest priority in this program
|
super(-1); // Lowest priority in this program
|
||||||
exec = e;
|
exec = e;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for(PrioritizedTask pt : sequence) {
|
for(PrioritizedTask pt : sequence) {
|
||||||
@ -63,6 +67,7 @@ class PrioritizedTaskProducer implements Runnable {
|
|||||||
queue = q;
|
queue = q;
|
||||||
exec = e; // Used for EndSentinel
|
exec = e; // Used for EndSentinel
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Unbounded queue; never blocks.
|
// Unbounded queue; never blocks.
|
||||||
// Fill it up fast with random priorities:
|
// Fill it up fast with random priorities:
|
||||||
@ -94,6 +99,7 @@ class PrioritizedTaskConsumer implements Runnable {
|
|||||||
PriorityBlockingQueue<Runnable> q) {
|
PriorityBlockingQueue<Runnable> q) {
|
||||||
this.q = q;
|
this.q = q;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted())
|
while(!Thread.interrupted())
|
||||||
@ -110,8 +116,8 @@ public class PriorityBlockingQueueDemo {
|
|||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
ExecutorService exec = Executors.newCachedThreadPool();
|
ExecutorService exec = Executors.newCachedThreadPool();
|
||||||
PriorityBlockingQueue<Runnable> queue =
|
PriorityBlockingQueue<Runnable> queue =
|
||||||
new PriorityBlockingQueue<Runnable>();
|
new PriorityBlockingQueue<>();
|
||||||
exec.execute(new PrioritizedTaskProducer(queue, exec));
|
exec.execute(new PrioritizedTaskProducer(queue, exec));
|
||||||
exec.execute(new PrioritizedTaskConsumer(queue));
|
exec.execute(new PrioritizedTaskConsumer(queue));
|
||||||
}
|
}
|
||||||
} /* (Execute to see output) *///:~
|
} /* (Execute to see output) *///:~
|
||||||
|
@ -10,7 +10,7 @@ public class ReaderWriterList<T> {
|
|||||||
private ReentrantReadWriteLock lock =
|
private ReentrantReadWriteLock lock =
|
||||||
new ReentrantReadWriteLock(true);
|
new ReentrantReadWriteLock(true);
|
||||||
public ReaderWriterList(int size, T initialValue) {
|
public ReaderWriterList(int size, T initialValue) {
|
||||||
lockedList = new ArrayList<T>(
|
lockedList = new ArrayList<>(
|
||||||
Collections.nCopies(size, initialValue));
|
Collections.nCopies(size, initialValue));
|
||||||
}
|
}
|
||||||
public T set(int index, T element) {
|
public T set(int index, T element) {
|
||||||
@ -45,8 +45,9 @@ class ReaderWriterListTest {
|
|||||||
private final static int SIZE = 100;
|
private final static int SIZE = 100;
|
||||||
private static Random rand = new Random(47);
|
private static Random rand = new Random(47);
|
||||||
private ReaderWriterList<Integer> list =
|
private ReaderWriterList<Integer> list =
|
||||||
new ReaderWriterList<Integer>(SIZE, 0);
|
new ReaderWriterList<>(SIZE, 0);
|
||||||
private class Writer implements Runnable {
|
private class Writer implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
for(int i = 0; i < 20; i++) { // 2 second test
|
for(int i = 0; i < 20; i++) { // 2 second test
|
||||||
@ -61,6 +62,7 @@ class ReaderWriterListTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
private class Reader implements Runnable {
|
private class Reader implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -80,4 +82,4 @@ class ReaderWriterListTest {
|
|||||||
for(int i = 0; i < writers; i++)
|
for(int i = 0; i < writers; i++)
|
||||||
exec.execute(new Writer());
|
exec.execute(new Writer());
|
||||||
}
|
}
|
||||||
} /* (Execute to see output) *///:~
|
} /* (Execute to see output) *///:~
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
//: concurrency/ResponsiveUI.java
|
//: concurrency/ResponsiveUI.java
|
||||||
// User interface responsiveness.
|
// User interface responsiveness.
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
|
|
||||||
class UnresponsiveUI {
|
class UnresponsiveUI {
|
||||||
private volatile double d = 1;
|
private volatile double d = 1;
|
||||||
@ -17,6 +17,7 @@ public class ResponsiveUI extends Thread {
|
|||||||
setDaemon(true);
|
setDaemon(true);
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true) {
|
while(true) {
|
||||||
d = d + (Math.PI + Math.E) / d;
|
d = d + (Math.PI + Math.E) / d;
|
||||||
|
@ -6,12 +6,14 @@ import static net.mindview.util.Print.*;
|
|||||||
class Meal {
|
class Meal {
|
||||||
private final int orderNum;
|
private final int orderNum;
|
||||||
public Meal(int orderNum) { this.orderNum = orderNum; }
|
public Meal(int orderNum) { this.orderNum = orderNum; }
|
||||||
|
@Override
|
||||||
public String toString() { return "Meal " + orderNum; }
|
public String toString() { return "Meal " + orderNum; }
|
||||||
}
|
}
|
||||||
|
|
||||||
class WaitPerson implements Runnable {
|
class WaitPerson implements Runnable {
|
||||||
private Restaurant restaurant;
|
private Restaurant restaurant;
|
||||||
public WaitPerson(Restaurant r) { restaurant = r; }
|
public WaitPerson(Restaurant r) { restaurant = r; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -35,6 +37,7 @@ class Chef implements Runnable {
|
|||||||
private Restaurant restaurant;
|
private Restaurant restaurant;
|
||||||
private int count = 0;
|
private int count = 0;
|
||||||
public Chef(Restaurant r) { restaurant = r; }
|
public Chef(Restaurant r) { restaurant = r; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
|
@ -5,10 +5,12 @@ public class SelfManaged implements Runnable {
|
|||||||
private int countDown = 5;
|
private int countDown = 5;
|
||||||
private Thread t = new Thread(this);
|
private Thread t = new Thread(this);
|
||||||
public SelfManaged() { t.start(); }
|
public SelfManaged() { t.start(); }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return Thread.currentThread().getName() +
|
return Thread.currentThread().getName() +
|
||||||
"(" + countDown + "), ";
|
"(" + countDown + "), ";
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true) {
|
while(true) {
|
||||||
System.out.print(this);
|
System.out.print(this);
|
||||||
|
@ -12,6 +12,7 @@ class CheckoutTask<T> implements Runnable {
|
|||||||
public CheckoutTask(Pool<T> pool) {
|
public CheckoutTask(Pool<T> pool) {
|
||||||
this.pool = pool;
|
this.pool = pool;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
T item = pool.checkOut();
|
T item = pool.checkOut();
|
||||||
@ -23,6 +24,7 @@ class CheckoutTask<T> implements Runnable {
|
|||||||
// Acceptable way to terminate
|
// Acceptable way to terminate
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "CheckoutTask " + id + " ";
|
return "CheckoutTask " + id + " ";
|
||||||
}
|
}
|
||||||
@ -31,13 +33,12 @@ class CheckoutTask<T> implements Runnable {
|
|||||||
public class SemaphoreDemo {
|
public class SemaphoreDemo {
|
||||||
final static int SIZE = 25;
|
final static int SIZE = 25;
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
final Pool<Fat> pool =
|
final Pool<Fat> pool = new Pool<>(Fat.class, SIZE);
|
||||||
new Pool<Fat>(Fat.class, SIZE);
|
|
||||||
ExecutorService exec = Executors.newCachedThreadPool();
|
ExecutorService exec = Executors.newCachedThreadPool();
|
||||||
for(int i = 0; i < SIZE; i++)
|
for(int i = 0; i < SIZE; i++)
|
||||||
exec.execute(new CheckoutTask<Fat>(pool));
|
exec.execute(new CheckoutTask<>(pool));
|
||||||
print("All CheckoutTasks created");
|
print("All CheckoutTasks created");
|
||||||
List<Fat> list = new ArrayList<Fat>();
|
List<Fat> list = new ArrayList<>();
|
||||||
for(int i = 0; i < SIZE; i++) {
|
for(int i = 0; i < SIZE; i++) {
|
||||||
Fat f = pool.checkOut();
|
Fat f = pool.checkOut();
|
||||||
printnb(i + ": main() thread checked out ");
|
printnb(i + ": main() thread checked out ");
|
||||||
@ -45,6 +46,7 @@ public class SemaphoreDemo {
|
|||||||
list.add(f);
|
list.add(f);
|
||||||
}
|
}
|
||||||
Future<?> blocked = exec.submit(new Runnable() {
|
Future<?> blocked = exec.submit(new Runnable() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
// Semaphore prevents additional checkout,
|
// Semaphore prevents additional checkout,
|
||||||
|
@ -36,6 +36,7 @@ public class SerialNumberChecker {
|
|||||||
private static ExecutorService exec =
|
private static ExecutorService exec =
|
||||||
Executors.newCachedThreadPool();
|
Executors.newCachedThreadPool();
|
||||||
static class SerialChecker implements Runnable {
|
static class SerialChecker implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true) {
|
while(true) {
|
||||||
int serial =
|
int serial =
|
||||||
@ -60,4 +61,4 @@ public class SerialNumberChecker {
|
|||||||
}
|
}
|
||||||
} /* Output: (Sample)
|
} /* Output: (Sample)
|
||||||
Duplicate: 8468656
|
Duplicate: 8468656
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
//: concurrency/SettingDefaultHandler.java
|
//: concurrency/SettingDefaultHandler.java
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
public class SettingDefaultHandler {
|
public class SettingDefaultHandler {
|
||||||
@ -11,4 +11,4 @@ public class SettingDefaultHandler {
|
|||||||
}
|
}
|
||||||
} /* Output:
|
} /* Output:
|
||||||
caught java.lang.RuntimeException
|
caught java.lang.RuntimeException
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -4,6 +4,7 @@ import java.util.concurrent.*;
|
|||||||
import static net.mindview.util.Print.*;
|
import static net.mindview.util.Print.*;
|
||||||
|
|
||||||
public class SimpleDaemons implements Runnable {
|
public class SimpleDaemons implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
|
@ -8,11 +8,13 @@ abstract class Incrementable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class SynchronizingTest extends Incrementable {
|
class SynchronizingTest extends Incrementable {
|
||||||
|
@Override
|
||||||
public synchronized void increment() { ++counter; }
|
public synchronized void increment() { ++counter; }
|
||||||
}
|
}
|
||||||
|
|
||||||
class LockingTest extends Incrementable {
|
class LockingTest extends Incrementable {
|
||||||
private Lock lock = new ReentrantLock();
|
private Lock lock = new ReentrantLock();
|
||||||
|
@Override
|
||||||
public void increment() {
|
public void increment() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
|
@ -9,9 +9,11 @@ public class SimplePriorities implements Runnable {
|
|||||||
public SimplePriorities(int priority) {
|
public SimplePriorities(int priority) {
|
||||||
this.priority = priority;
|
this.priority = priority;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return Thread.currentThread() + ": " + countDown;
|
return Thread.currentThread() + ": " + countDown;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
Thread.currentThread().setPriority(priority);
|
Thread.currentThread().setPriority(priority);
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -46,4 +48,4 @@ Thread[pool-1-thread-1,1,main]: 5
|
|||||||
Thread[pool-1-thread-5,1,main]: 5
|
Thread[pool-1-thread-5,1,main]: 5
|
||||||
Thread[pool-1-thread-4,1,main]: 5
|
Thread[pool-1-thread-4,1,main]: 5
|
||||||
...
|
...
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -9,9 +9,11 @@ public class SimpleThread extends Thread {
|
|||||||
super(Integer.toString(++threadCount));
|
super(Integer.toString(++threadCount));
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "#" + getName() + "(" + countDown + "), ";
|
return "#" + getName() + "(" + countDown + "), ";
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(true) {
|
while(true) {
|
||||||
System.out.print(this);
|
System.out.print(this);
|
||||||
|
@ -3,13 +3,14 @@
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
public class SleepingTask extends LiftOff {
|
public class SleepingTask extends LiftOff {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(countDown-- > 0) {
|
while(countDown-- > 0) {
|
||||||
System.out.print(status());
|
System.out.print(status());
|
||||||
// Old-style:
|
// Old-style:
|
||||||
// Thread.sleep(100);
|
// Thread.sleep(100);
|
||||||
// Java SE5/6-style:
|
// Java 5/6-style:
|
||||||
TimeUnit.MILLISECONDS.sleep(100);
|
TimeUnit.MILLISECONDS.sleep(100);
|
||||||
}
|
}
|
||||||
} catch(InterruptedException e) {
|
} catch(InterruptedException e) {
|
||||||
|
@ -24,6 +24,7 @@ public class SyncObject {
|
|||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
final DualSynch ds = new DualSynch();
|
final DualSynch ds = new DualSynch();
|
||||||
new Thread() {
|
new Thread() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
ds.f();
|
ds.f();
|
||||||
}
|
}
|
||||||
|
@ -29,6 +29,7 @@ abstract class Accumulator {
|
|||||||
public abstract void accumulate();
|
public abstract void accumulate();
|
||||||
public abstract long read();
|
public abstract long read();
|
||||||
private class Modifier implements Runnable {
|
private class Modifier implements Runnable {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(long i = 0; i < cycles; i++)
|
for(long i = 0; i < cycles; i++)
|
||||||
accumulate();
|
accumulate();
|
||||||
@ -41,6 +42,7 @@ abstract class Accumulator {
|
|||||||
}
|
}
|
||||||
private class Reader implements Runnable {
|
private class Reader implements Runnable {
|
||||||
private volatile long value;
|
private volatile long value;
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(long i = 0; i < cycles; i++)
|
for(long i = 0; i < cycles; i++)
|
||||||
value = read();
|
value = read();
|
||||||
@ -73,10 +75,12 @@ abstract class Accumulator {
|
|||||||
|
|
||||||
class SynchronizedTest extends Accumulator {
|
class SynchronizedTest extends Accumulator {
|
||||||
{ id = "synch"; }
|
{ id = "synch"; }
|
||||||
|
@Override
|
||||||
public synchronized void accumulate() {
|
public synchronized void accumulate() {
|
||||||
value += preLoaded[index++];
|
value += preLoaded[index++];
|
||||||
if(index >= SIZE) index = 0;
|
if(index >= SIZE) index = 0;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public synchronized long read() {
|
public synchronized long read() {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
@ -85,6 +89,7 @@ class SynchronizedTest extends Accumulator {
|
|||||||
class LockTest extends Accumulator {
|
class LockTest extends Accumulator {
|
||||||
{ id = "Lock"; }
|
{ id = "Lock"; }
|
||||||
private Lock lock = new ReentrantLock();
|
private Lock lock = new ReentrantLock();
|
||||||
|
@Override
|
||||||
public void accumulate() {
|
public void accumulate() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
@ -94,6 +99,7 @@ class LockTest extends Accumulator {
|
|||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public long read() {
|
public long read() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
@ -111,6 +117,7 @@ class AtomicTest extends Accumulator {
|
|||||||
// Relying on more than one Atomic at a time doesn't
|
// Relying on more than one Atomic at a time doesn't
|
||||||
// work, so we still have to synchronize. But it gives
|
// work, so we still have to synchronize. But it gives
|
||||||
// a performance indicator:
|
// a performance indicator:
|
||||||
|
@Override
|
||||||
public synchronized void accumulate() {
|
public synchronized void accumulate() {
|
||||||
int i;
|
int i;
|
||||||
i = index.getAndIncrement();
|
i = index.getAndIncrement();
|
||||||
@ -118,7 +125,9 @@ class AtomicTest extends Accumulator {
|
|||||||
if(++i >= SIZE)
|
if(++i >= SIZE)
|
||||||
index.set(0);
|
index.set(0);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public synchronized long read() { return value.get(); }
|
public synchronized long read() { return value.get(); }
|
||||||
|
@Override
|
||||||
public void report(Accumulator acc2) {
|
public void report(Accumulator acc2) {
|
||||||
printf("%-22s: %.2f\n", "synch/(Atomic-synch)",
|
printf("%-22s: %.2f\n", "synch/(Atomic-synch)",
|
||||||
(double)acc2.duration/
|
(double)acc2.duration/
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
//: concurrency/SynchronizedEvenGenerator.java
|
//: concurrency/SynchronizedEvenGenerator.java
|
||||||
// Simplifying mutexes with the synchronized keyword.
|
// Simplifying mutexes with the synchronized keyword.
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
|
|
||||||
public class
|
public class
|
||||||
SynchronizedEvenGenerator extends IntGenerator {
|
SynchronizedEvenGenerator extends IntGenerator {
|
||||||
private int currentEvenValue = 0;
|
private int currentEvenValue = 0;
|
||||||
|
@Override
|
||||||
public synchronized int next() {
|
public synchronized int next() {
|
||||||
++currentEvenValue;
|
++currentEvenValue;
|
||||||
Thread.yield(); // Cause failure faster
|
Thread.yield(); // Cause failure faster
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
//: concurrency/TestBlockingQueues.java
|
//: concurrency/TestBlockingQueues.java
|
||||||
// {RunByHand}
|
// {TimeOutDuringTesting}
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import static net.mindview.util.Print.*;
|
import static net.mindview.util.Print.*;
|
||||||
@ -16,6 +16,7 @@ class LiftOffRunner implements Runnable {
|
|||||||
print("Interrupted during put()");
|
print("Interrupted during put()");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -58,10 +59,10 @@ public class TestBlockingQueues {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
test("LinkedBlockingQueue", // Unlimited size
|
test("LinkedBlockingQueue", // Unlimited size
|
||||||
new LinkedBlockingQueue<LiftOff>());
|
new LinkedBlockingQueue<>());
|
||||||
test("ArrayBlockingQueue", // Fixed size
|
test("ArrayBlockingQueue", // Fixed size
|
||||||
new ArrayBlockingQueue<LiftOff>(3));
|
new ArrayBlockingQueue<>(3));
|
||||||
test("SynchronousQueue", // Size of 1
|
test("SynchronousQueue", // Size of 1
|
||||||
new SynchronousQueue<LiftOff>());
|
new SynchronousQueue<>());
|
||||||
}
|
}
|
||||||
} ///:~
|
} ///:~
|
||||||
|
@ -6,6 +6,7 @@ import java.util.*;
|
|||||||
class Accessor implements Runnable {
|
class Accessor implements Runnable {
|
||||||
private final int id;
|
private final int id;
|
||||||
public Accessor(int idn) { id = idn; }
|
public Accessor(int idn) { id = idn; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while(!Thread.currentThread().isInterrupted()) {
|
while(!Thread.currentThread().isInterrupted()) {
|
||||||
ThreadLocalVariableHolder.increment();
|
ThreadLocalVariableHolder.increment();
|
||||||
@ -13,6 +14,7 @@ class Accessor implements Runnable {
|
|||||||
Thread.yield();
|
Thread.yield();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "#" + id + ": " +
|
return "#" + id + ": " +
|
||||||
ThreadLocalVariableHolder.get();
|
ThreadLocalVariableHolder.get();
|
||||||
@ -23,6 +25,7 @@ public class ThreadLocalVariableHolder {
|
|||||||
private static ThreadLocal<Integer> value =
|
private static ThreadLocal<Integer> value =
|
||||||
new ThreadLocal<Integer>() {
|
new ThreadLocal<Integer>() {
|
||||||
private Random rand = new Random(47);
|
private Random rand = new Random(47);
|
||||||
|
@Override
|
||||||
protected synchronized Integer initialValue() {
|
protected synchronized Integer initialValue() {
|
||||||
return rand.nextInt(10000);
|
return rand.nextInt(10000);
|
||||||
}
|
}
|
||||||
|
@ -12,6 +12,7 @@ class InnerThread1 {
|
|||||||
super(name);
|
super(name);
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -23,6 +24,7 @@ class InnerThread1 {
|
|||||||
print("interrupted");
|
print("interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return getName() + ": " + countDown;
|
return getName() + ": " + countDown;
|
||||||
}
|
}
|
||||||
@ -38,6 +40,7 @@ class InnerThread2 {
|
|||||||
private Thread t;
|
private Thread t;
|
||||||
public InnerThread2(String name) {
|
public InnerThread2(String name) {
|
||||||
t = new Thread(name) {
|
t = new Thread(name) {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -49,6 +52,7 @@ class InnerThread2 {
|
|||||||
print("sleep() interrupted");
|
print("sleep() interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return getName() + ": " + countDown;
|
return getName() + ": " + countDown;
|
||||||
}
|
}
|
||||||
@ -67,6 +71,7 @@ class InnerRunnable1 {
|
|||||||
t = new Thread(this, name);
|
t = new Thread(this, name);
|
||||||
t.start();
|
t.start();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -78,6 +83,7 @@ class InnerRunnable1 {
|
|||||||
print("sleep() interrupted");
|
print("sleep() interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return t.getName() + ": " + countDown;
|
return t.getName() + ": " + countDown;
|
||||||
}
|
}
|
||||||
@ -93,6 +99,7 @@ class InnerRunnable2 {
|
|||||||
private Thread t;
|
private Thread t;
|
||||||
public InnerRunnable2(String name) {
|
public InnerRunnable2(String name) {
|
||||||
t = new Thread(new Runnable() {
|
t = new Thread(new Runnable() {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -104,6 +111,7 @@ class InnerRunnable2 {
|
|||||||
print("sleep() interrupted");
|
print("sleep() interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return Thread.currentThread().getName() +
|
return Thread.currentThread().getName() +
|
||||||
": " + countDown;
|
": " + countDown;
|
||||||
@ -122,6 +130,7 @@ class ThreadMethod {
|
|||||||
public void runTask() {
|
public void runTask() {
|
||||||
if(t == null) {
|
if(t == null) {
|
||||||
t = new Thread(name) {
|
t = new Thread(name) {
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(true) {
|
while(true) {
|
||||||
@ -133,6 +142,7 @@ class ThreadMethod {
|
|||||||
print("sleep() interrupted");
|
print("sleep() interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return getName() + ": " + countDown;
|
return getName() + ": " + countDown;
|
||||||
}
|
}
|
||||||
|
@ -13,6 +13,7 @@ class Toast {
|
|||||||
public void jam() { status = Status.JAMMED; }
|
public void jam() { status = Status.JAMMED; }
|
||||||
public Status getStatus() { return status; }
|
public Status getStatus() { return status; }
|
||||||
public int getId() { return id; }
|
public int getId() { return id; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Toast " + id + ": " + status;
|
return "Toast " + id + ": " + status;
|
||||||
}
|
}
|
||||||
@ -25,6 +26,7 @@ class Toaster implements Runnable {
|
|||||||
private int count = 0;
|
private int count = 0;
|
||||||
private Random rand = new Random(47);
|
private Random rand = new Random(47);
|
||||||
public Toaster(ToastQueue tq) { toastQueue = tq; }
|
public Toaster(ToastQueue tq) { toastQueue = tq; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -50,6 +52,7 @@ class Butterer implements Runnable {
|
|||||||
dryQueue = dry;
|
dryQueue = dry;
|
||||||
butteredQueue = buttered;
|
butteredQueue = buttered;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -73,6 +76,7 @@ class Jammer implements Runnable {
|
|||||||
butteredQueue = buttered;
|
butteredQueue = buttered;
|
||||||
finishedQueue = finished;
|
finishedQueue = finished;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -96,6 +100,7 @@ class Eater implements Runnable {
|
|||||||
public Eater(ToastQueue finished) {
|
public Eater(ToastQueue finished) {
|
||||||
finishedQueue = finished;
|
finishedQueue = finished;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
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 Food item() { return food; }
|
||||||
public Customer getCustomer() { return customer; }
|
public Customer getCustomer() { return customer; }
|
||||||
public WaitPerson getWaitPerson() { return waitPerson; }
|
public WaitPerson getWaitPerson() { return waitPerson; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Order: " + id + " item: " + food +
|
return "Order: " + id + " item: " + food +
|
||||||
" for: " + customer +
|
" for: " + customer +
|
||||||
@ -38,6 +39,7 @@ class Plate {
|
|||||||
}
|
}
|
||||||
public Order getOrder() { return order; }
|
public Order getOrder() { return order; }
|
||||||
public Food getFood() { return food; }
|
public Food getFood() { return food; }
|
||||||
|
@Override
|
||||||
public String toString() { return food.toString(); }
|
public String toString() { return food.toString(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +49,7 @@ class Customer implements Runnable {
|
|||||||
private final WaitPerson waitPerson;
|
private final WaitPerson waitPerson;
|
||||||
// Only one course at a time can be received:
|
// Only one course at a time can be received:
|
||||||
private SynchronousQueue<Plate> placeSetting =
|
private SynchronousQueue<Plate> placeSetting =
|
||||||
new SynchronousQueue<Plate>();
|
new SynchronousQueue<>();
|
||||||
public Customer(WaitPerson w) { waitPerson = w; }
|
public Customer(WaitPerson w) { waitPerson = w; }
|
||||||
public void
|
public void
|
||||||
deliver(Plate p) throws InterruptedException {
|
deliver(Plate p) throws InterruptedException {
|
||||||
@ -55,6 +57,7 @@ class Customer implements Runnable {
|
|||||||
// eating the previous course:
|
// eating the previous course:
|
||||||
placeSetting.put(p);
|
placeSetting.put(p);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
for(Course course : Course.values()) {
|
for(Course course : Course.values()) {
|
||||||
Food food = course.randomSelection();
|
Food food = course.randomSelection();
|
||||||
@ -70,6 +73,7 @@ class Customer implements Runnable {
|
|||||||
}
|
}
|
||||||
print(this + "finished meal, leaving");
|
print(this + "finished meal, leaving");
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Customer " + id + " ";
|
return "Customer " + id + " ";
|
||||||
}
|
}
|
||||||
@ -80,7 +84,7 @@ class WaitPerson implements Runnable {
|
|||||||
private final int id = counter++;
|
private final int id = counter++;
|
||||||
private final Restaurant restaurant;
|
private final Restaurant restaurant;
|
||||||
BlockingQueue<Plate> filledOrders =
|
BlockingQueue<Plate> filledOrders =
|
||||||
new LinkedBlockingQueue<Plate>();
|
new LinkedBlockingQueue<>();
|
||||||
public WaitPerson(Restaurant rest) { restaurant = rest; }
|
public WaitPerson(Restaurant rest) { restaurant = rest; }
|
||||||
public void placeOrder(Customer cust, Food food) {
|
public void placeOrder(Customer cust, Food food) {
|
||||||
try {
|
try {
|
||||||
@ -91,6 +95,7 @@ class WaitPerson implements Runnable {
|
|||||||
print(this + " placeOrder interrupted");
|
print(this + " placeOrder interrupted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -106,6 +111,7 @@ class WaitPerson implements Runnable {
|
|||||||
}
|
}
|
||||||
print(this + " off duty");
|
print(this + " off duty");
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "WaitPerson " + id + " ";
|
return "WaitPerson " + id + " ";
|
||||||
}
|
}
|
||||||
@ -117,6 +123,7 @@ class Chef implements Runnable {
|
|||||||
private final Restaurant restaurant;
|
private final Restaurant restaurant;
|
||||||
private static Random rand = new Random(47);
|
private static Random rand = new Random(47);
|
||||||
public Chef(Restaurant rest) { restaurant = rest; }
|
public Chef(Restaurant rest) { restaurant = rest; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -133,17 +140,18 @@ class Chef implements Runnable {
|
|||||||
}
|
}
|
||||||
print(this + " off duty");
|
print(this + " off duty");
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() { return "Chef " + id + " "; }
|
public String toString() { return "Chef " + id + " "; }
|
||||||
}
|
}
|
||||||
|
|
||||||
class Restaurant implements Runnable {
|
class Restaurant implements Runnable {
|
||||||
private List<WaitPerson> waitPersons =
|
private List<WaitPerson> waitPersons =
|
||||||
new ArrayList<WaitPerson>();
|
new ArrayList<>();
|
||||||
private List<Chef> chefs = new ArrayList<Chef>();
|
private List<Chef> chefs = new ArrayList<>();
|
||||||
private ExecutorService exec;
|
private ExecutorService exec;
|
||||||
private static Random rand = new Random(47);
|
private static Random rand = new Random(47);
|
||||||
BlockingQueue<Order>
|
BlockingQueue<Order>
|
||||||
orders = new LinkedBlockingQueue<Order>();
|
orders = new LinkedBlockingQueue<>();
|
||||||
public Restaurant(ExecutorService e, int nWaitPersons,
|
public Restaurant(ExecutorService e, int nWaitPersons,
|
||||||
int nChefs) {
|
int nChefs) {
|
||||||
exec = e;
|
exec = e;
|
||||||
@ -158,6 +166,7 @@ class Restaurant implements Runnable {
|
|||||||
exec.execute(chef);
|
exec.execute(chef);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -203,4 +212,4 @@ WaitPerson 3 received VINDALOO delivering to Customer 0
|
|||||||
Customer 0 eating VINDALOO
|
Customer 0 eating VINDALOO
|
||||||
WaitPerson 0 received FRUIT delivering to Customer 1
|
WaitPerson 0 received FRUIT delivering to Customer 1
|
||||||
...
|
...
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -29,6 +29,7 @@ class Car {
|
|||||||
class WaxOn implements Runnable {
|
class WaxOn implements Runnable {
|
||||||
private Car car;
|
private Car car;
|
||||||
public WaxOn(Car c) { car = c; }
|
public WaxOn(Car c) { car = c; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -47,6 +48,7 @@ class WaxOn implements Runnable {
|
|||||||
class WaxOff implements Runnable {
|
class WaxOff implements Runnable {
|
||||||
private Car car;
|
private Car car;
|
||||||
public WaxOff(Car c) { car = c; }
|
public WaxOff(Car c) { car = c; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
|
@ -50,6 +50,7 @@ class Car {
|
|||||||
class WaxOn implements Runnable {
|
class WaxOn implements Runnable {
|
||||||
private Car car;
|
private Car car;
|
||||||
public WaxOn(Car c) { car = c; }
|
public WaxOn(Car c) { car = c; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
@ -68,6 +69,7 @@ class WaxOn implements Runnable {
|
|||||||
class WaxOff implements Runnable {
|
class WaxOff implements Runnable {
|
||||||
private Car car;
|
private Car car;
|
||||||
public WaxOff(Car c) { car = c; }
|
public WaxOff(Car c) { car = c; }
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while(!Thread.interrupted()) {
|
while(!Thread.interrupted()) {
|
||||||
|
@ -20,6 +20,7 @@ public class AssociativeArray<K,V> {
|
|||||||
return (V)pairs[i][1];
|
return (V)pairs[i][1];
|
||||||
return null; // Did not find key
|
return null; // Did not find key
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
StringBuilder result = new StringBuilder();
|
StringBuilder result = new StringBuilder();
|
||||||
for(int i = 0; i < index; i++) {
|
for(int i = 0; i < index; i++) {
|
||||||
@ -33,7 +34,7 @@ public class AssociativeArray<K,V> {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
AssociativeArray<String,String> map =
|
AssociativeArray<String,String> map =
|
||||||
new AssociativeArray<String,String>(6);
|
new AssociativeArray<>(6);
|
||||||
map.put("sky", "blue");
|
map.put("sky", "blue");
|
||||||
map.put("grass", "green");
|
map.put("grass", "green");
|
||||||
map.put("ocean", "dancing");
|
map.put("ocean", "dancing");
|
||||||
|
@ -5,12 +5,16 @@ import java.util.*;
|
|||||||
class Element {
|
class Element {
|
||||||
private String ident;
|
private String ident;
|
||||||
public Element(String id) { ident = id; }
|
public Element(String id) { ident = id; }
|
||||||
|
@Override
|
||||||
public String toString() { return ident; }
|
public String toString() { return ident; }
|
||||||
|
@Override
|
||||||
public int hashCode() { return ident.hashCode(); }
|
public int hashCode() { return ident.hashCode(); }
|
||||||
|
@Override
|
||||||
public boolean equals(Object r) {
|
public boolean equals(Object r) {
|
||||||
return r instanceof Element &&
|
return r instanceof Element &&
|
||||||
ident.equals(((Element)r).ident);
|
ident.equals(((Element)r).ident);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
protected void finalize() {
|
protected void finalize() {
|
||||||
System.out.println("Finalizing " +
|
System.out.println("Finalizing " +
|
||||||
getClass().getSimpleName() + " " + ident);
|
getClass().getSimpleName() + " " + ident);
|
||||||
@ -32,8 +36,7 @@ public class CanonicalMapping {
|
|||||||
if(args.length > 0)
|
if(args.length > 0)
|
||||||
size = new Integer(args[0]);
|
size = new Integer(args[0]);
|
||||||
Key[] keys = new Key[size];
|
Key[] keys = new Key[size];
|
||||||
WeakHashMap<Key,Value> map =
|
WeakHashMap<Key,Value> map = new WeakHashMap<>();
|
||||||
new WeakHashMap<Key,Value>();
|
|
||||||
for(int i = 0; i < size; i++) {
|
for(int i = 0; i < size; i++) {
|
||||||
Key k = new Key(Integer.toString(i));
|
Key k = new Key(Integer.toString(i));
|
||||||
Value v = new Value(Integer.toString(i));
|
Value v = new Value(Integer.toString(i));
|
||||||
|
@ -5,14 +5,14 @@ import net.mindview.util.*;
|
|||||||
|
|
||||||
public class CollectionDataGeneration {
|
public class CollectionDataGeneration {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println(new ArrayList<String>(
|
System.out.println(new ArrayList<>(
|
||||||
CollectionData.list( // Convenience method
|
CollectionData.list( // Convenience method
|
||||||
new RandomGenerator.String(9), 10)));
|
new RandomGenerator.String(9), 10)));
|
||||||
System.out.println(new HashSet<Integer>(
|
System.out.println(new HashSet<>(
|
||||||
new CollectionData<Integer>(
|
new CollectionData<>(
|
||||||
new RandomGenerator.Integer(), 10)));
|
new RandomGenerator.Integer(), 10)));
|
||||||
}
|
}
|
||||||
} /* Output:
|
} /* Output:
|
||||||
[YNzbrnyGc, FOWZnTcQr, GseGZMmJM, RoEsuEcUO, neOEdLsmw, HLGEahKcx, rEqUCBbkI, naMesbtWH, kjUrUkZPg, wsqPzDyCy]
|
[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 " +
|
"distributing swords is no basis for a system of " +
|
||||||
"government").split(" ");
|
"government").split(" ");
|
||||||
private int index;
|
private int index;
|
||||||
|
@Override
|
||||||
public String next() { return foundation[index++]; }
|
public String next() { return foundation[index++]; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class CollectionDataTest {
|
public class CollectionDataTest {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Set<String> set = new LinkedHashSet<String>(
|
Set<String> set = new LinkedHashSet<>(
|
||||||
new CollectionData<String>(new Government(), 15));
|
new CollectionData<>(new Government(), 15));
|
||||||
// Using the convenience method:
|
// Using the convenience method:
|
||||||
set.addAll(CollectionData.list(new Government(), 15));
|
set.addAll(CollectionData.list(new Government(), 15));
|
||||||
System.out.println(set);
|
System.out.println(set);
|
||||||
|
@ -6,7 +6,7 @@ import static net.mindview.util.Print.*;
|
|||||||
|
|
||||||
public class CollectionMethods {
|
public class CollectionMethods {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Collection<String> c = new ArrayList<String>();
|
Collection<String> c = new ArrayList<>();
|
||||||
c.addAll(Countries.names(6));
|
c.addAll(Countries.names(6));
|
||||||
c.add("ten");
|
c.add("ten");
|
||||||
c.add("eleven");
|
c.add("eleven");
|
||||||
@ -21,7 +21,7 @@ public class CollectionMethods {
|
|||||||
print("Collections.max(c) = " + Collections.max(c));
|
print("Collections.max(c) = " + Collections.max(c));
|
||||||
print("Collections.min(c) = " + Collections.min(c));
|
print("Collections.min(c) = " + Collections.min(c));
|
||||||
// Add a Collection to another Collection
|
// Add a Collection to another Collection
|
||||||
Collection<String> c2 = new ArrayList<String>();
|
Collection<String> c2 = new ArrayList<>();
|
||||||
c2.addAll(Countries.names(6));
|
c2.addAll(Countries.names(6));
|
||||||
c.addAll(c2);
|
c.addAll(c2);
|
||||||
print(c);
|
print(c);
|
||||||
@ -50,25 +50,25 @@ public class CollectionMethods {
|
|||||||
// in c2 that also appear in c3:
|
// in c2 that also appear in c3:
|
||||||
c2.removeAll(c3);
|
c2.removeAll(c3);
|
||||||
print("c2.isEmpty() = " + c2.isEmpty());
|
print("c2.isEmpty() = " + c2.isEmpty());
|
||||||
c = new ArrayList<String>();
|
c = new ArrayList<>();
|
||||||
c.addAll(Countries.names(6));
|
c.addAll(Countries.names(6));
|
||||||
print(c);
|
print(c);
|
||||||
c.clear(); // Remove all elements
|
c.clear(); // Remove all elements
|
||||||
print("after c.clear():" + c);
|
print("after c.clear():" + c);
|
||||||
}
|
}
|
||||||
} /* Output:
|
} /* Output:
|
||||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven]
|
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven]
|
||||||
Collections.max(c) = ten
|
Collections.max(c) = ten
|
||||||
Collections.min(c) = ALGERIA
|
Collections.min(c) = ALGERIA
|
||||||
[ALGERIA, ANGOLA, 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, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||||
[BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
[BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||||
[ten, eleven]
|
[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.contains(BOTSWANA) = true
|
||||||
c.containsAll(c2) = true
|
c.containsAll(c2) = true
|
||||||
[ANGOLA, BENIN]
|
[ANGOLA, BENIN]
|
||||||
c2.isEmpty() = true
|
c2.isEmpty() = true
|
||||||
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO]
|
[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
|
||||||
after c.clear():[]
|
after c.clear():[]
|
||||||
*///:~
|
*///:~
|
||||||
|
@ -5,7 +5,7 @@ import static net.mindview.util.Print.*;
|
|||||||
|
|
||||||
public class CountedString {
|
public class CountedString {
|
||||||
private static List<String> created =
|
private static List<String> created =
|
||||||
new ArrayList<String>();
|
new ArrayList<>();
|
||||||
private String s;
|
private String s;
|
||||||
private int id = 0;
|
private int id = 0;
|
||||||
public CountedString(String str) {
|
public CountedString(String str) {
|
||||||
@ -17,10 +17,12 @@ public class CountedString {
|
|||||||
if(s2.equals(s))
|
if(s2.equals(s))
|
||||||
id++;
|
id++;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "String: " + s + " id: " + id +
|
return "String: " + s + " id: " + id +
|
||||||
" hashCode(): " + hashCode();
|
" hashCode(): " + hashCode();
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
// The very simple approach:
|
// The very simple approach:
|
||||||
// return s.hashCode() * id;
|
// return s.hashCode() * id;
|
||||||
@ -30,6 +32,7 @@ public class CountedString {
|
|||||||
result = 37 * result + id;
|
result = 37 * result + id;
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
return o instanceof CountedString &&
|
return o instanceof CountedString &&
|
||||||
s.equals(((CountedString)o).s) &&
|
s.equals(((CountedString)o).s) &&
|
||||||
@ -37,7 +40,7 @@ public class CountedString {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Map<CountedString,Integer> map =
|
Map<CountedString,Integer> map =
|
||||||
new HashMap<CountedString,Integer>();
|
new HashMap<>();
|
||||||
CountedString[] cs = new CountedString[5];
|
CountedString[] cs = new CountedString[5];
|
||||||
for(int i = 0; i < cs.length; i++) {
|
for(int i = 0; i < cs.length; i++) {
|
||||||
cs[i] = new CountedString("hi");
|
cs[i] = new CountedString("hi");
|
||||||
|
@ -10,7 +10,7 @@ public class DequeTest {
|
|||||||
deque.addLast(i);
|
deque.addLast(i);
|
||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Deque<Integer> di = new Deque<Integer>();
|
Deque<Integer> di = new Deque<>();
|
||||||
fillTest(di);
|
fillTest(di);
|
||||||
print(di);
|
print(di);
|
||||||
while(di.size() != 0)
|
while(di.size() != 0)
|
||||||
|
@ -6,13 +6,13 @@ import net.mindview.util.*;
|
|||||||
public class Enumerations {
|
public class Enumerations {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Vector<String> v =
|
Vector<String> v =
|
||||||
new Vector<String>(Countries.names(10));
|
new Vector<>(Countries.names(10));
|
||||||
Enumeration<String> e = v.elements();
|
Enumeration<String> e = v.elements();
|
||||||
while(e.hasMoreElements())
|
while(e.hasMoreElements())
|
||||||
System.out.print(e.nextElement() + ", ");
|
System.out.print(e.nextElement() + ", ");
|
||||||
// Produce an Enumeration from a Collection:
|
// Produce an Enumeration from a Collection:
|
||||||
e = Collections.enumeration(new ArrayList<String>());
|
e = Collections.enumeration(new ArrayList<>());
|
||||||
}
|
}
|
||||||
} /* Output:
|
} /* 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 class FailFast {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Collection<String> c = new ArrayList<String>();
|
Collection<String> c = new ArrayList<>();
|
||||||
Iterator<String> it = c.iterator();
|
Iterator<String> it = c.iterator();
|
||||||
c.add("An object");
|
c.add("An object");
|
||||||
try {
|
try {
|
||||||
|
@ -5,6 +5,7 @@ import java.util.*;
|
|||||||
class StringAddress {
|
class StringAddress {
|
||||||
private String s;
|
private String s;
|
||||||
public StringAddress(String s) { this.s = s; }
|
public StringAddress(String s) { this.s = s; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return super.toString() + " " + s;
|
return super.toString() + " " + s;
|
||||||
}
|
}
|
||||||
@ -12,7 +13,7 @@ class StringAddress {
|
|||||||
|
|
||||||
public class FillingLists {
|
public class FillingLists {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
List<StringAddress> list= new ArrayList<StringAddress>(
|
List<StringAddress> list = new ArrayList<>(
|
||||||
Collections.nCopies(4, new StringAddress("Hello")));
|
Collections.nCopies(4, new StringAddress("Hello")));
|
||||||
System.out.println(list);
|
System.out.println(list);
|
||||||
Collections.fill(list, new StringAddress("World!"));
|
Collections.fill(list, new StringAddress("World!"));
|
||||||
|
@ -4,6 +4,7 @@
|
|||||||
public class Groundhog {
|
public class Groundhog {
|
||||||
protected int number;
|
protected int number;
|
||||||
public Groundhog(int n) { number = n; }
|
public Groundhog(int n) { number = n; }
|
||||||
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Groundhog #" + number;
|
return "Groundhog #" + number;
|
||||||
}
|
}
|
||||||
|
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