├── .vscode └── settings.json ├── src ├── test │ └── java │ │ ├── verify │ │ ├── verify.jar │ │ ├── Readme │ │ └── Trace.java.copy │ │ ├── linerChecker │ │ ├── checker.jar │ │ ├── check.sh │ │ ├── README │ │ └── Trace.java.copy │ │ └── ticketingsystem │ │ ├── .travis.yml │ │ ├── MultiTraceVerifyTest.java │ │ ├── TraceVerifyTest.java │ │ ├── RandomTest.java │ │ ├── MultiThreadTest.java │ │ └── UnitTest.java └── main │ └── java │ └── ticketingsystem │ ├── TicketingSystem.java │ ├── Backoffer.java │ ├── jmh │ └── benchmark │ │ └── PerformanceBenchmarkRunner.java │ ├── TicketingDS.java │ ├── RemainSeatsTable.java │ ├── Train.java │ ├── PerformanceBenchmark.java │ └── Trace.java ├── trace.sh ├── .travis.yml ├── .gitignore ├── .factorypath ├── .github └── workflows │ ├── maven.yml │ └── codeql-analysis.yml ├── pom.xml ├── README.md ├── result.json └── LICENSE /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic" 3 | } -------------------------------------------------------------------------------- /src/test/java/verify/verify.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/specialpointcentral/TrainTicketingSystem/HEAD/src/test/java/verify/verify.jar -------------------------------------------------------------------------------- /trace.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd src/main/java 3 | javac -encoding UTF-8 -cp . ticketingsystem/Trace.java 4 | java -cp . ticketingsystem/Trace -------------------------------------------------------------------------------- /src/test/java/linerChecker/checker.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/specialpointcentral/TrainTicketingSystem/HEAD/src/test/java/linerChecker/checker.jar -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - openjdk11 5 | 6 | install: 7 | - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V 8 | script: 9 | - mvn test -B -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | install: 4 | - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V 5 | 6 | script: 7 | - mvn test -B -------------------------------------------------------------------------------- /src/test/java/verify/Readme: -------------------------------------------------------------------------------- 1 | 1. copy Trace.java to your dir 2 | 2. generate trace 3 | 3. enter verify dir 4 | 4. execute "java -jar verify.jar trace" 5 | 6 | If the first error is found, the result is as follows: 7 | 8 | Error: RemainTicket 57982522 57982654 0 3 3 2 3 9 | Real RemainTicket is 3 , Expect RemainTicket is 4, 3 2 3 10 | Verification Finished 11 | 12 | Else only "Verification Finished" is printed. 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/TicketingSystem.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | class Ticket { 4 | long tid; 5 | String passenger; 6 | int route; 7 | int coach; 8 | int seat; 9 | int departure; 10 | int arrival; 11 | } 12 | 13 | public interface TicketingSystem { 14 | Ticket buyTicket(String passenger, int route, int departure, int arrival); 15 | 16 | int inquiry(int route, int departure, int arrival); 17 | 18 | boolean refundTicket(Ticket ticket); 19 | } 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | !verify.jar 16 | !checker.jar 17 | *.war 18 | *.nar 19 | *.ear 20 | *.zip 21 | *.tar.gz 22 | *.rar 23 | 24 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 25 | hs_err_pid* 26 | 27 | # maven ignore 28 | target/ 29 | 30 | # eclipse ignore 31 | .settings/ 32 | .project 33 | .classpath 34 | 35 | 36 | 37 | # idea ignore 38 | .idea/ 39 | *.ipr 40 | *.iml 41 | *.iws 42 | 43 | **/trace -------------------------------------------------------------------------------- /.factorypath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/test/java/linerChecker/check.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ## compile Trace.java and put .class into bin 4 | javac ../../../main/java/ticketingsystem/Trace.java -d ./bin 5 | 6 | result=1 7 | 8 | ## begin test 9 | for i in $(seq 1 50); do ## you can change the number of test, default is 50 10 | java -cp bin ticketingsystem/Trace > trace 11 | java -jar checker.jar --no-path-info --coach 10 --seat 100 --station 10 < trace 12 | if [ $? != 0 ]; then 13 | echo "Test failed!!! see trace file to debug" 14 | result=0 15 | break 16 | fi 17 | done 18 | 19 | if [ $result == 1 ]; then 20 | echo "Test passed!!!" 21 | fi 22 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 11 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 11 23 | - name: Build with Maven 24 | run: mvn -B package --file pom.xml 25 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/Backoffer.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.concurrent.ThreadLocalRandom; 4 | 5 | public class Backoffer { 6 | ThreadLocal retryTime = ThreadLocal.withInitial(()->1); 7 | private ThreadLocalRandom rand = ThreadLocalRandom.current(); 8 | 9 | public void setBackoffTime(int time) { 10 | if(time > 1) 11 | retryTime.set(time); 12 | else 13 | retryTime.set(1); 14 | } 15 | 16 | public void backoff() { 17 | int bound = retryTime.get(); 18 | int j = rand.nextInt(bound); 19 | for(int i = 0; i < j; ++i); 20 | if(bound < 0xfff) 21 | retryTime.set(bound << 1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/jmh/benchmark/PerformanceBenchmarkRunner.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem.jmh.benchmark; 2 | 3 | import org.openjdk.jmh.results.format.ResultFormatType; 4 | import org.openjdk.jmh.runner.Runner; 5 | import org.openjdk.jmh.runner.RunnerException; 6 | import org.openjdk.jmh.runner.options.Options; 7 | import org.openjdk.jmh.runner.options.OptionsBuilder; 8 | 9 | import ticketingsystem.*; 10 | 11 | public class PerformanceBenchmarkRunner { 12 | public static void main(String[] args) throws RunnerException { 13 | Options opt = new OptionsBuilder().include(PerformanceBenchmark.class.getSimpleName()) 14 | .result("result.json") 15 | .resultFormat(ResultFormatType.JSON) 16 | .build(); 17 | new Runner(opt).run(); 18 | } 19 | } -------------------------------------------------------------------------------- /src/test/java/linerChecker/README: -------------------------------------------------------------------------------- 1 | 1. 说明 2 | 本测试包含有一个测试工具checker.jar以及一个方便测试的脚本check.sh 3 | 测试工具的使用格式如下: 4 | java -jar checker.jar --coach xx --seat xx --station xx < trace 5 | 其他使用说明见参数--help 6 | 7 | 2. 使用步骤 8 | step 1: 将本包中的文件加压到ticketingsystem的同级目录 9 | step 2: 修改ticketingsystem/Trace.java中的参数,routenum请务必设置成1 10 | step 3: 得到一个trace 11 | step 4: 运行命令checker.jar 12 | 13 | 3. 结果说明 14 | 如果trace可线性化,会打印出线性化的执行路径。否则输出Not Linearizable. 15 | 16 | 4. 注意事项 17 | check.sh是一个便于测试的脚本,可以直接运行。使用前请修改脚本中的参数。 18 | Trace.java中route数请设置为1,火车间是独立的,所以checker我是按照一辆车检验的。 19 | 当前版本支持的trace记录数可以达到500条左右,运行时间随着交叠区间个数增加呈指数级上升。所以建议不要生成过大的trace文件。 20 | 21 | 推荐的设置值: 22 | final static int threadnum = 5; 23 | final static int routenum = 1; // route is designed from 1 to 3 24 | final static int coachnum = 3; // coach is arranged from 1 to 5 25 | final static int seatnum = 5; // seat is allocated from 1 to 20 26 | final static int stationnum = 5; // station is designed from 1 to 5 27 | final static int testnum = 20; 28 | 29 | 可以常识的设置值: (一般500条一下运行时间可以接受) 30 | final static int threadnum = 5; 31 | final static int routenum = 1; // route is designed from 1 to 3 32 | final static int coachnum = 10; // coach is arranged from 1 to 5 33 | final static int seatnum = 100; // seat is allocated from 1 to 20 34 | final static int stationnum = 10; // station is designed from 1 to 5 35 | final static int testnum = 100; 36 | 37 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '17 13 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | language: [ 'java' ] 32 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 33 | # Learn more: 34 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 35 | 36 | steps: 37 | - name: Checkout repository 38 | uses: actions/checkout@v2 39 | 40 | - name: Set up JDK 11 41 | uses: actions/setup-java@v1 42 | with: 43 | java-version: 11 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/TicketingDS.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | public class TicketingDS implements TicketingSystem { 6 | private int threadNum; 7 | private Train[] trains; 8 | private int coachNum; 9 | private int seatNum; 10 | private int routeNum; 11 | 12 | private AtomicLong buyTicketQueryID; 13 | private long hashMask; 14 | 15 | private ThreadLocal ticketBeginID = ThreadLocal.withInitial(()->0L); 16 | private ThreadLocal ticketEndID = ThreadLocal.withInitial(()->-1L); 17 | 18 | public TicketingDS(int routenum, int coachnum, int seatnum, int stationnum, int threadnum) { 19 | this.threadNum = threadnum; 20 | this.coachNum = coachnum; 21 | this.seatNum = seatnum; 22 | this.routeNum = routenum; 23 | trains = new Train[routenum]; 24 | buyTicketQueryID = new AtomicLong(0); 25 | for (int i = 0; i < routenum; i++) { 26 | trains[i] = new Train(coachnum, seatnum, stationnum); 27 | } 28 | 29 | int coachBitNum = 32 - Integer.numberOfLeadingZeros(Math.max(this.coachNum - 1, 1)); 30 | int threadNumBitNum = 32 - Integer.numberOfLeadingZeros(Math.max(this.threadNum - 1, 1)); 31 | // hash mask for query 32 | if (this.threadNum > this.coachNum) { 33 | // all coach need used as hash 34 | this.hashMask = (0x1 << coachBitNum) - 1; 35 | } else { 36 | // will send to some coach 37 | this.hashMask = ((0x1 << threadNumBitNum) - 1) << (coachBitNum - threadNumBitNum); 38 | } 39 | } 40 | 41 | @Override 42 | public Ticket buyTicket(String passenger, int route, int departure, int arrival) { 43 | Ticket ticket = new Ticket(); 44 | long threadID = Thread.currentThread().getId(); 45 | // deliver to every train and coach 46 | int queryCoachID = (int)(threadID & hashMask); 47 | Train currTrian = trains[route - 1]; 48 | int beginSeats = currTrian.getFindRefund(departure - 1, arrival - 1); 49 | if(beginSeats == -1) beginSeats = queryCoachID * seatNum; 50 | int seat = currTrian.getAndLockSeat(departure - 1, arrival - 1, beginSeats); 51 | if (seat < 0) 52 | return null; 53 | // find a tid 54 | long queryID = ticketBeginID.get(); 55 | if(queryID > ticketEndID.get()) { 56 | queryID = buyTicketQueryID.getAndAdd(512); 57 | ticketEndID.set(queryID + 511); 58 | } 59 | ticketBeginID.set(queryID + 1); 60 | // build a ticket 61 | ticket.tid = queryID; 62 | ticket.passenger = passenger; 63 | ticket.route = route; 64 | ticket.departure = departure; 65 | ticket.arrival = arrival; 66 | ticket.coach = (seat / seatNum) + 1; 67 | ticket.seat = (seat % seatNum) + 1; 68 | 69 | currTrian.addSoldTicket(ticket); 70 | return ticket; 71 | } 72 | 73 | @Override 74 | public int inquiry(int route, int departure, int arrival) { 75 | Train currTrian = trains[route - 1]; 76 | return currTrian.getRemainSeats(departure - 1, arrival - 1); 77 | } 78 | 79 | @Override 80 | public boolean refundTicket(Ticket ticket) { 81 | Train currTrian = trains[ticket.route - 1]; 82 | if(!currTrian.containAndRemove(ticket)) { 83 | return false; 84 | } 85 | int seat = (ticket.coach - 1) * seatNum + (ticket.seat - 1); 86 | currTrian.insertRefundList(seat, ticket.departure - 1, ticket.arrival - 1); 87 | return currTrian.unlockSeat(seat, ticket.departure - 1, ticket.arrival - 1); 88 | } 89 | 90 | public void clear() { 91 | ticketBeginID.remove(); 92 | ticketEndID.remove(); 93 | for (int i = 0; i < routeNum; i++) { 94 | trains[i].clear(); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | ucas.huqi 7 | trainTicketingSystem 8 | 1.0-SNAPSHOT 9 | jar 10 | 11 | trainTicketingSystem 12 | https://github.com/specialpointcentral/TrainTicketingSystem 13 | 14 | 15 | UTF-8 16 | 11 17 | ${java.version} 18 | ${java.version} 19 | 20 | 5.6.2 21 | 22 | 23 | 3.2.2 24 | 3.1.0 25 | 3.1.0 26 | 3.8.1 27 | 3.0.0-M5 28 | 3.2.0 29 | 3.0.0-M1 30 | 31 | 32 | 33 | 34 | 35 | org.openjdk.jmh 36 | jmh-core 37 | 1.23 38 | 39 | 40 | org.openjdk.jmh 41 | jmh-generator-annprocess 42 | 1.23 43 | 44 | 45 | 46 | 47 | org.junit.jupiter 48 | junit-jupiter-api 49 | ${junit} 50 | test 51 | 52 | 53 | org.junit.jupiter 54 | junit-jupiter-engine 55 | ${junit} 56 | test 57 | 58 | 59 | org.junit.jupiter 60 | junit-jupiter-params 61 | ${junit} 62 | test 63 | 64 | 65 | 66 | 67 | 68 | 69 | maven-clean-plugin 70 | 3.1.0 71 | 72 | 73 | maven-resources-plugin 74 | 3.1.0 75 | 76 | 77 | maven-compiler-plugin 78 | 3.8.1 79 | 80 | 81 | maven-surefire-plugin 82 | 3.0.0-M4 83 | 84 | 85 | maven-jar-plugin 86 | 3.2.0 87 | 88 | 89 | maven-install-plugin 90 | 3.0.0-M1 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-shade-plugin 95 | ${maven.shade} 96 | 97 | 98 | package 99 | 100 | shade 101 | 102 | 103 | 104 | 105 | ticketingsystem.App 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/MultiTraceVerifyTest.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.io.*; 6 | 7 | import org.junit.jupiter.api.BeforeAll; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.RepeatedTest; 11 | import org.junit.jupiter.api.RepetitionInfo; 12 | import org.junit.jupiter.api.TestInfo; 13 | 14 | @DisplayName("MultiTraceVerifyTest") 15 | public class MultiTraceVerifyTest { 16 | private static File workDir = new File("src/main/java/ticketingsystem/"); 17 | private static File verifyDir = new File("src/test/java/linerChecker/"); 18 | private static boolean isWindows; 19 | 20 | protected int currentRepetition, totalRepetitions; 21 | 22 | @BeforeAll 23 | static void prepareFile() throws IOException, InterruptedException { 24 | String oldfile = verifyDir.getAbsolutePath() + "/Trace.java.copy"; 25 | String newfile = workDir.getAbsolutePath() + "/Trace.java"; 26 | copyFile(oldfile, newfile); 27 | isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); 28 | // compiler 29 | ProcessBuilder builder = new ProcessBuilder(); 30 | if (isWindows) { 31 | builder.command("cmd.exe", "/c", "javac -encoding UTF-8 -cp . ticketingsystem/Trace.java"); 32 | } else { 33 | builder.command("sh", "-c", "javac -encoding UTF-8 -cp . ticketingsystem/Trace.java"); 34 | } 35 | builder.directory(workDir.getParentFile()); 36 | Process process = builder.start(); 37 | int exitCode = process.waitFor(); 38 | assertEquals(0, exitCode); 39 | } 40 | 41 | @BeforeEach 42 | void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) throws IOException, InterruptedException { 43 | currentRepetition = repetitionInfo.getCurrentRepetition(); 44 | totalRepetitions = repetitionInfo.getTotalRepetitions(); 45 | String methodName = testInfo.getTestMethod().get().getName(); 46 | System.out.println( 47 | String.format("Execute repetition %d of %d for %s", currentRepetition, totalRepetitions, methodName)); 48 | System.out.flush(); 49 | 50 | generateTraceFile(); 51 | System.out.println( 52 | String.format("[%d/%d] Trace has been generated", currentRepetition, totalRepetitions)); 53 | System.out.flush(); 54 | } 55 | 56 | void generateTraceFile() throws IOException, InterruptedException { 57 | File f = new File(verifyDir.getPath() + "/trace"); 58 | if (f.exists()) { 59 | f.delete(); 60 | } 61 | ProcessBuilder builder = new ProcessBuilder(); 62 | if (isWindows) { 63 | builder.command("cmd.exe", "/c", "java -cp . ticketingsystem/Trace > " + f.getAbsolutePath()); 64 | } else { 65 | builder.command("sh", "-c", "java -cp . ticketingsystem/Trace > " + f.getAbsolutePath()); 66 | } 67 | builder.directory(workDir.getParentFile()); 68 | Process process = builder.start(); 69 | int exitCode = process.waitFor(); 70 | assertEquals(0, exitCode); 71 | } 72 | 73 | @RepeatedTest(value = 10, name = "{displayName} {currentRepetition}/{totalRepetitions}") 74 | void verifyMultiTrace() throws IOException, InterruptedException { 75 | ProcessBuilder builder = new ProcessBuilder(); 76 | if (isWindows) { 77 | builder.command("cmd.exe", "/c", "java -jar checker.jar --coach 10 --seat 10 --station 7 --no-path-info < trace"); 78 | } else { 79 | builder.command("sh", "-c", "java -jar checker.jar --coach 10 --seat 10 --station 7 --no-path-info < trace"); 80 | } 81 | builder.directory(verifyDir); 82 | Process process = builder.start(); 83 | 84 | int exitCode = process.waitFor(); 85 | assertEquals(0, exitCode); 86 | } 87 | 88 | private static void copyFile(String oldPath, String newPath) { 89 | try { 90 | int bytesum = 0; 91 | int byteread = 0; 92 | File oldfile = new File(oldPath); 93 | if (oldfile.exists()) { 94 | InputStream inStream = new FileInputStream(oldPath); 95 | FileOutputStream fs = new FileOutputStream(newPath); 96 | byte[] buffer = new byte[1024]; 97 | while ((byteread = inStream.read(buffer)) != -1) { 98 | bytesum += byteread; 99 | fs.write(buffer, 0, byteread); 100 | } 101 | inStream.close(); 102 | } 103 | } catch (Exception e) { 104 | System.out.println("copy error!"); 105 | e.printStackTrace(); 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/TraceVerifyTest.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.io.*; 6 | 7 | import org.junit.jupiter.api.BeforeAll; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.DisplayName; 10 | import org.junit.jupiter.api.RepeatedTest; 11 | import org.junit.jupiter.api.RepetitionInfo; 12 | import org.junit.jupiter.api.Test; 13 | import org.junit.jupiter.api.TestInfo; 14 | 15 | @DisplayName("TraceVerifyTest") 16 | public class TraceVerifyTest { 17 | private static File workDir = new File("src/main/java/ticketingsystem/"); 18 | private static File verifyDir = new File("src/test/java/verify/"); 19 | private static boolean isWindows; 20 | 21 | protected int currentRepetition, totalRepetitions; 22 | 23 | @BeforeAll 24 | static void prepareFile() throws IOException, InterruptedException { 25 | String oldfile = verifyDir.getAbsolutePath() + "/Trace.java.copy"; 26 | String newfile = workDir.getAbsolutePath() + "/Trace.java"; 27 | copyFile(oldfile, newfile); 28 | isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); 29 | // compiler 30 | ProcessBuilder builder = new ProcessBuilder(); 31 | if (isWindows) { 32 | builder.command("cmd.exe", "/c", "javac -encoding UTF-8 -cp . ticketingsystem/Trace.java"); 33 | } else { 34 | builder.command("sh", "-c", "javac -encoding UTF-8 -cp . ticketingsystem/Trace.java"); 35 | } 36 | builder.directory(workDir.getParentFile()); 37 | Process process = builder.start(); 38 | int exitCode = process.waitFor(); 39 | assertEquals(0, exitCode); 40 | } 41 | 42 | @BeforeEach 43 | void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) throws IOException, InterruptedException { 44 | currentRepetition = repetitionInfo.getCurrentRepetition(); 45 | totalRepetitions = repetitionInfo.getTotalRepetitions(); 46 | String methodName = testInfo.getTestMethod().get().getName(); 47 | System.out.println( 48 | String.format("Execute repetition %d of %d for %s", currentRepetition, totalRepetitions, methodName)); 49 | System.out.flush(); 50 | 51 | generateTraceFile(); 52 | System.out.println( 53 | String.format("[%d/%d] Trace has been generated", currentRepetition, totalRepetitions)); 54 | System.out.flush(); 55 | } 56 | 57 | void generateTraceFile() throws IOException, InterruptedException { 58 | File f = new File(verifyDir.getPath() + "/trace"); 59 | if (f.exists()) { 60 | f.delete(); 61 | } 62 | ProcessBuilder builder = new ProcessBuilder(); 63 | if (isWindows) { 64 | builder.command("cmd.exe", "/c", "java -cp . ticketingsystem/Trace > " + f.getAbsolutePath()); 65 | } else { 66 | builder.command("sh", "-c", "java -cp . ticketingsystem/Trace > " + f.getAbsolutePath()); 67 | } 68 | builder.directory(workDir.getParentFile()); 69 | Process process = builder.start(); 70 | int exitCode = process.waitFor(); 71 | assertEquals(0, exitCode); 72 | } 73 | 74 | @RepeatedTest(value = 10, name = "{displayName} {currentRepetition}/{totalRepetitions}") 75 | void verifyTrace() throws IOException, InterruptedException { 76 | ProcessBuilder builder = new ProcessBuilder(); 77 | if (isWindows) { 78 | builder.command("cmd.exe", "/c", "java -jar verify.jar trace"); 79 | } else { 80 | builder.command("sh", "-c", "java -jar verify.jar trace"); 81 | } 82 | builder.directory(verifyDir); 83 | Process process = builder.start(); 84 | InputStream in = process.getInputStream(); 85 | BufferedReader read = new BufferedReader(new InputStreamReader(in)); 86 | assertEquals("Verification Finished", read.readLine()); 87 | int exitCode = process.waitFor(); 88 | assertEquals(0, exitCode); 89 | } 90 | 91 | private static void copyFile(String oldPath, String newPath) { 92 | try { 93 | int bytesum = 0; 94 | int byteread = 0; 95 | File oldfile = new File(oldPath); 96 | if (oldfile.exists()) { 97 | InputStream inStream = new FileInputStream(oldPath); 98 | FileOutputStream fs = new FileOutputStream(newPath); 99 | byte[] buffer = new byte[1024]; 100 | while ((byteread = inStream.read(buffer)) != -1) { 101 | bytesum += byteread; 102 | fs.write(buffer, 0, byteread); 103 | } 104 | inStream.close(); 105 | } 106 | } catch (Exception e) { 107 | System.out.println("copy error!"); 108 | e.printStackTrace(); 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/RemainSeatsTable.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.Arrays; 4 | import java.util.concurrent.atomic.AtomicStampedReference; 5 | 6 | public class RemainSeatsTable { 7 | private int stationNum; 8 | private int seatNum; 9 | private AtomicStampedReference remainSeats; 10 | 11 | private ThreadLocal localTable; 12 | private ThreadLocal localTableSwither; 13 | 14 | Backoffer backoff = new Backoffer(); 15 | 16 | public RemainSeatsTable(final int seatnum, final int stationnum) { 17 | this.stationNum = stationnum; 18 | this.seatNum = seatnum; 19 | 20 | this.localTable = ThreadLocal.withInitial(() -> { 21 | int[][] remainSeat = new int[stationNum][]; 22 | for (int i = 0; i < stationNum; ++i) { 23 | // remainSeat[from][to] 24 | // NOTE: 'from' is real, but 'to' is (to+from) 25 | // if 'to' is 0, result is always 0 26 | // Example: remainSeat[1][2] = (1)->(3) 27 | remainSeat[i] = new int[stationNum - i]; 28 | remainSeat[i][0] = 0; 29 | for (int j = 1; j < stationNum - i; ++j) { 30 | remainSeat[i][j] = seatNum; 31 | } 32 | } 33 | return remainSeat; 34 | }); 35 | 36 | this.localTableSwither = ThreadLocal.withInitial(() -> { 37 | int[][] remainSeat = new int[stationNum][]; 38 | for (int i = 0; i < stationNum; ++i) { 39 | // remainSeat[from][to] 40 | // NOTE: 'from' is real, but 'to' is (to+from) 41 | // if 'to' is 0, result is always 0 42 | // Example: remainSeat[1][2] = (1)->(3) 43 | remainSeat[i] = new int[stationNum - i]; 44 | remainSeat[i][0] = 0; 45 | for (int j = 1; j < stationNum - i; ++j) { 46 | remainSeat[i][j] = seatNum; 47 | } 48 | } 49 | return remainSeat; 50 | }); 51 | 52 | this.remainSeats = new AtomicStampedReference<>(localTable.get(), 0); 53 | } 54 | 55 | public final int getRemainSeats(final int departure, final int arrival) { 56 | int currTimestap = remainSeats.getStamp(); 57 | int[][] currTable = remainSeats.getReference(); 58 | int remain = currTable[departure][arrival - departure]; 59 | int twiceTimestap = remainSeats.getStamp(); 60 | while (currTimestap != twiceTimestap) { 61 | currTimestap = remainSeats.getStamp(); 62 | currTable = remainSeats.getReference(); 63 | remain = currTable[departure][arrival - departure]; 64 | twiceTimestap = remainSeats.getStamp(); 65 | } 66 | return remain; 67 | } 68 | 69 | public final void setRemainSeats(final int departure, final int arrival, final long origin, final int num) { 70 | while (true) { 71 | int[][] oldTable = remainSeats.getReference(); 72 | int[][] newTable = localTable.get(); 73 | if (Arrays.equals(oldTable, newTable)) { 74 | // using my local table as global table, 75 | // so we need create a new one to modify 76 | newTable = localTableSwither.get(); 77 | } 78 | int stamp = remainSeats.getStamp(); 79 | // decrease/increase the table 80 | 81 | // if origin is 0, mark we need do all task 82 | boolean currIsNotClean = (origin != 0); 83 | // 0 1 2 3 4 5 84 | // Example: 2->4 85 | // 0-3 -> 3-5 86 | // departure station 87 | for (int i = 0; i < arrival; ++i) { 88 | // copy 89 | for (int j = i + 1; j < stationNum; ++j) { 90 | newTable[i][j - i] = oldTable[i][j - i]; 91 | } 92 | // arrival station 93 | for (int j = Math.max(departure, i) + 1; j < stationNum; ++j) { 94 | if (currIsNotClean && isOverlapping(i, j, origin)) { 95 | newTable[i][j - i] = oldTable[i][j - i]; 96 | } else { 97 | newTable[i][j - i] = oldTable[i][j - i] + num; 98 | } 99 | } 100 | } 101 | // copy 102 | for (int i = arrival; i < stationNum; ++i) { 103 | for (int j = i + 1; j < stationNum; ++j) { 104 | newTable[i][j - i] = oldTable[i][j - i]; 105 | } 106 | } 107 | 108 | if (remainSeats.compareAndSet(oldTable, newTable, stamp, stamp + 1)) { 109 | return; 110 | } 111 | backoff.backoff(); 112 | } 113 | } 114 | 115 | public void decrementRemainSeats(final int departure, final int arrival, final long origin) { 116 | setRemainSeats(departure, arrival, origin, -1); 117 | } 118 | 119 | public void incrementRemainSeats(final int departure, final int arrival, final long origin) { 120 | setRemainSeats(departure, arrival, origin, 1); 121 | } 122 | 123 | private final boolean isOverlapping(final int departure, final int arrival, final long origin) { 124 | // departure and arrival not overlapping the origin data 125 | int mask = ((0x01 << (arrival - departure)) - 1) << departure; 126 | return ((mask & origin) > 0); 127 | } 128 | 129 | public void clear() { 130 | localTable.remove(); 131 | localTableSwither.remove(); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TrainTicketingSystem 2 | 3 | 多核与并发数据结构-用于列车售票的可线性化并发数据结构 4 | 5 | ![Travis (.com)](https://img.shields.io/travis/com/specialpointcentral/TrainTicketingSystem?logo=travis-ci&logoColor=white&style=flat-square&link=https://travis-ci.com/specialpointcentral/TrainTicketingSystem) 6 | ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/specialpointcentral/TrainTicketingSystem/Java%20CI%20with%20Maven?logo=github&logoColor=whhite&style=flat-square) 7 | ![GitHub](https://img.shields.io/github/license/specialpointcentral/TrainTicketingSystem?style=flat-square) 8 | ![GitHub last commit](https://img.shields.io/github/last-commit/specialpointcentral/TrainTicketingSystem?style=flat-square) 9 | ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/specialpointcentral/TrainTicketingSystem?style=flat-square) 10 | 11 | ## 数据结构说明 12 | 13 | 给定`Ticket`类: 14 | 15 | ```java 16 | class Ticket{ 17 | long tid; 18 | String passenger; 19 | int route; 20 | int coach; 21 | int seat; 22 | int departure; 23 | int arrival; 24 | } 25 | ``` 26 | 27 | 其中,`tid`是车票编号,`passenger`是乘客名字,`route`是列车车次,`coach`是车厢号,`seat`是座位号,`departure`是出发站编号,`arrival`是到达站编号。 28 | 29 | 给定`TicketingSystem`接口: 30 | 31 | ```java 32 | public interface TicketingSystem { 33 | Ticket buyTicket(String passenger, int route, int departure, int arrival); 34 | int inquiry(int route, int departure, int arrival); 35 | boolean refundTicket(Ticket ticket); 36 | } 37 | ``` 38 | 39 | 其中: 40 | 41 | - `buyTicket`是购票方法,即乘客`passenger`购买`route`车次从`departure`站到`arrival`站的车票1张。若购票成功,返回有效的`Ticket`对象;若失败(即无余票),返回无效的`Ticket`对象(即`return null`)。 42 | - `refundTicket`是退票方法,对有效的`Ticket`对象返回`true`,对错误或无效的`Ticket`对象返回`false`。 43 | - `inquriy`是查询余票方法,即查询`route`车次从`departure`站到`arrival`站的余票数。 44 | 45 | ## 完成`TicketingDS`类 46 | 47 | 完成一个用于列车售票的可线性化并发数据结构:`TicketingDS`类: 48 | 49 | 1. 实现`TicketingSystem`接口, 50 | 2. 提供`TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum);`构造函数。 51 | 52 | 其中: 53 | 54 | - `routenum`是车次总数(缺省为5个), 55 | - `coachnum`是列车的车厢数目(缺省为8个), 56 | - `seatnum`是每节车厢的座位数(缺省为100个), 57 | - `stationnum`是每个车次经停站的数量(缺省为10个,含始发站和终点站), 58 | - `threadnum`是并发购票的线程数(缺省为16个)。 59 | 60 | 为简单起见,假设每个车次的`coachnum`、`seatnum`和`stationnum`都相同。 61 | 车票涉及的各项参数均从1开始计数,例如车厢从1到8号,车站从1到10编号等。 62 | 63 | ## 完成多线程测试程序 64 | 65 | 需编写多线程测试程序,在`main`方法中用下述语句创建`TicketingDS`类的一个实例。 66 | 67 | ```java 68 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum); 69 | ``` 70 | 71 | 系统中同时存在`threadnum`个线程(缺省为16个),每个线程是一个票务代理,需要: 72 | 73 | 1. 按照60%查询余票,30%购票和10%退票的比率反复调用`TicketingDS`类的三种方法若干次(缺省为总共10000次); 74 | 2. 按照线程数为4,8,16,32,64个的情况分别调用。 75 | 76 | 需要最后给出: 77 | 78 | 1. 给出每种方法调用的平均执行时间; 79 | 2. 同时计算系统的总吞吐率(单位时间内完成的方法调用总数)。 80 | 81 | ## 正确性要求 82 | 83 | 需要保证以下正确性: 84 | 85 | - 每张车票都有一个唯一的编号`tid`,不能重复。 86 | - 每一个`tid`的车票只能出售一次。退票后,原车票的`tid`作废。 87 | - 每个区段有余票时,系统必须满足该区段的购票请求。 88 | - 车票不能超卖,系统不能卖无座车票。 89 | - 买票、退票和查询余票方法均需满足可线性化要求。 90 | 91 | ## 文件清单 92 | 93 | 所有Java程序放在`ticketingsystem`目录中,`trace.sh`文件放在`ticketingsystem`目录的上层目录中。 94 | 如果程序有多重目录,那么将主Java程序放在`ticketingsystem`目录中。 95 | 96 | 文件清单如下: 97 | 98 | - `trace.sh`是trace生成脚本,用于正确性验证,不能更改。 99 | - `pom.xml`是依赖配置文件,使用`mvn`。 100 | - `.travis.yml`是CI配置文件,用于自动化测试。 101 | - 文件夹`.github`是github自动化测试配置文件。 102 | - 文件夹`src/main/java`为代码文件夹。 103 | 1. `TicketingSystem.java`是规范文件,不能更改。 104 | 2. `Trace.java`是trace生成程序,用于正确性验证,不能更改。 105 | 3. `TicketingDS.java`是并发数据结构的实现。 106 | 4. ... 其他的自建类。 107 | 5. `PerformanceBenchmark.java`是JMH基准测试程序。 108 | 6. `jmh.benchmark.PerformanceBenchmarkRunner.java`是JMH基准测试启动文件。 109 | 110 | - 文件夹`src/test/java`为测试文件夹。 111 | 1. `ticketingsystem`存放基本测试单元。 112 | - `UnitTest.java`为系统的单元测试,为单线程运行。 113 | - `RandomTest.java`为系统的随机测试,通过多线程,随机购、退、查票。 114 | - `MultiThreadTest.java`为多线程买、退票测试程序,通过多线程随机购、退票。 115 | - `TraceVerifyTest.java`为trace单线程可线性化比对测试。 116 | 2. `verify`文件夹存放trace单线程可线性化比对测试资源文件 117 | - `Trace.java.copy`为Trace调用文件,会自动替换原先的Trace.java。 118 | - `verify.jar`为单线程线性化测试包。 119 | 3. `linerChecker`文件夹存放trace多线程可线性化比对测试。 120 | - `check.sh`为启动脚本。 121 | - `checker.jar`为多线程线性化测试包。 122 | 123 | ## 使用说明 124 | 125 | ### 文件目录 126 | 127 | 项目文件主体在`src/main/java`下,你需要将你的文件放在`src/main/java/ticketingsystem`文件夹内,`PerformanceBenchmark.java`以及`jmh`文件夹用于基准测试不能删除。 128 | 129 | 1. 保证整个项目的结构。 130 | 2. 在`src/main/java/ticketingsystem`替换自己的实现。 131 | 3. 如果使用非`java-11`版本,请调整`pom.xml`。更改`your java version`为自己版本。 132 | 133 | ```xml 134 | 135 | UTF-8 136 | your java version 137 | ${java.version} 138 | ${java.version} 139 | ... 140 | 141 | ``` 142 | 143 | ### 使用`maven` 144 | 145 | 项目使用`maven`构建,运行前请安装`maven`。没有改变基本操作,常用的命令如下: 146 | 147 | - 通过`mvn clean`清理生成文件 148 | - 通过`mvn package`打成jar包 149 | - 通过`mvn test`执行测试 150 | - ... 151 | 152 | ### 使用`Junit`进行正确性测试 153 | 154 | > 注意:你需要安装`maven`才能执行,并且在执行过程中会自动安装相应依赖。 155 | 156 | 项目使用`Junit`进行正确性测试,你可以使用: 157 | 158 | - `mvn test`命令完成测试 159 | - 查看运行结果,会报告测试数量以及通过测试点数量。 160 | 161 | ### 使用`JMH`进行性能测试 162 | 163 | > 注意:你需要安装`maven`才能执行,并且在执行过程中会自动安装相应依赖。 164 | 165 | 项目使用`JMH`进行性能测试,你可以使用: 166 | 167 | - `mvn package`将项目打包 168 | - 在项目根目录下,运行: 169 | - `java -cp .\target\trainTicketingSystem-1.0-SNAPSHOT.jar ticketingsystem.jmh.benchmark.PerformanceBenchmarkRunner`。 170 | - 查看运行结果,结果单位为`ops/s`,即每秒操作数。这里的操作数与真实数量有差距,需要对数据乘上每次操作执行的买、退、查票动作数,即需要乘上64000。 171 | 172 | ### 使用CI自动化测试 173 | 174 | 项目支持`github workflow`以及`travis-ci`自动化测试,开箱即用。 175 | 每次`push`都会自动触发测试。 176 | 177 | ## 联系方式 178 | 179 | ![GitHub issues](https://img.shields.io/github/issues/specialpointcentral/TrainTicketingSystem?style=flat-square&link=https://github.com/specialpointcentral/TrainTicketingSystem/issues) 180 | ![GitHub followers](https://img.shields.io/github/followers/specialpointcentral?label=specialpointcentral&style=social&link=https://github.com/specialpointcentral) 181 | 182 | 任何问题欢迎提交issue。 183 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/Train.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | class RefundTicket { 7 | int seat; 8 | int departure; 9 | int arrival; 10 | public RefundTicket(final int seat, final int departure, final int arrival) { 11 | this.seat = seat; 12 | this.departure = departure; 13 | this.arrival = arrival; 14 | } 15 | } 16 | 17 | public class Train { 18 | private AtomicInteger[] seats; 19 | private final int seatNum; 20 | private final int coachNum; 21 | private final int stationNum; 22 | private final int allSeatNum; 23 | private ConcurrentHashMap soldTickets; 24 | 25 | private static final int BUFSIZE = 20; 26 | private ThreadLocal refundList = ThreadLocal.withInitial(()-> new RefundTicket[BUFSIZE]); 27 | private ThreadLocal pointer = ThreadLocal.withInitial(()-> 0); 28 | // map for remain seats 29 | RemainSeatsTable remainSeats; 30 | 31 | public Train(final int coachnum, final int seatnum, final int stationnum) { 32 | this.seatNum = seatnum; 33 | this.allSeatNum = coachnum * seatnum; 34 | this.coachNum = coachnum; 35 | this.stationNum = stationnum; 36 | this.seats = new AtomicInteger[this.allSeatNum]; 37 | for (int i = 0; i < this.allSeatNum; ++i) { 38 | this.seats[i] = new AtomicInteger(0); 39 | } 40 | remainSeats = new RemainSeatsTable(this.allSeatNum, this.stationNum); 41 | int initialCapacity = 128; 42 | float loadFactor = 0.5f; 43 | int concurrencyLevel = 2; 44 | soldTickets = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel); 45 | } 46 | 47 | public final int getAndLockSeat(final int departure, final int arrival) { 48 | return getAndLockSeat(departure, arrival, 0); 49 | } 50 | 51 | public int getAndLockSeat(final int departure, final int arrival, final int beginSeats) { 52 | // check if has seats 53 | if (haveRemainSeats(departure, arrival)) { 54 | int beginSeat = beginSeats % allSeatNum; 55 | // find the seat 56 | for (int i = 0; i < allSeatNum; ++i) { 57 | int pos = (beginSeat + i) % allSeatNum; 58 | int tmp = seats[pos].get(); 59 | // if seat is not occupied 60 | while (!isSeatOccupied(tmp, departure, arrival)) { 61 | // CAS! 62 | if (seats[pos].compareAndSet(tmp, setOccupied(tmp, departure, arrival))) { 63 | remainSeats.decrementRemainSeats(departure, arrival, tmp); 64 | return pos; 65 | } 66 | tmp = seats[pos].get(); 67 | } 68 | } 69 | } 70 | return -1; 71 | } 72 | 73 | public final int getRemainSeats(final int departure, final int arrival) { 74 | return remainSeats.getRemainSeats(departure, arrival); 75 | } 76 | 77 | public boolean unlockSeat(final int seat, final int departure, final int arrival) { 78 | while (true) { 79 | int tmp = seats[seat].get(); 80 | int cleanTmp = cleanOccupied(tmp, departure, arrival); 81 | if (seats[seat].compareAndSet(tmp, cleanTmp)) { 82 | remainSeats.incrementRemainSeats(departure, arrival, cleanTmp); 83 | return true; 84 | } 85 | } 86 | } 87 | 88 | private final boolean isSeatOccupied(final int block, final int departure, final int arrival) { 89 | int occupied = ((0x01 << (arrival - departure)) - 1) << departure; 90 | // 00000|0000|000000 block 91 | // 00000|1111|000000 occupied 92 | return (occupied & block) != 0; 93 | } 94 | 95 | private final int setOccupied(final int block, final int departure, final int arrival) { 96 | int occupied = ((0x01 << (arrival - departure)) - 1) << departure; 97 | return block | occupied; 98 | } 99 | 100 | private final int cleanOccupied(final int block, final int departure, final int arrival) { 101 | int occupied = ((0x01 << (arrival - departure)) - 1) << departure; 102 | return block & ~occupied; 103 | } 104 | 105 | private final boolean haveRemainSeats(final int departure, final int arrival) { 106 | return remainSeats.getRemainSeats(departure, arrival) > 0; 107 | } 108 | 109 | public final void insertRefundList(final int seat, final int departure, final int arrival) { 110 | int p = pointer.get(); 111 | refundList.get()[p] = new RefundTicket(seat, departure, arrival); 112 | pointer.set((p + 1) % BUFSIZE); 113 | } 114 | 115 | public final int getFindRefund(final int departure, final int arrival) { 116 | int usefulSeat = -1; 117 | for(int i = 0; i < BUFSIZE; ++i) { 118 | RefundTicket tick = refundList.get()[i]; 119 | if(tick != null && tick.departure <= departure && tick.arrival >= arrival) { 120 | usefulSeat = tick.seat; 121 | refundList.get()[i] = null; 122 | break; 123 | } 124 | } 125 | return usefulSeat; 126 | } 127 | 128 | public void clear() { 129 | refundList.remove(); 130 | pointer.remove(); 131 | remainSeats.clear(); 132 | } 133 | 134 | public final boolean containAndRemove(Ticket ticket) { 135 | Ticket containTicket = soldTickets.get(ticket.tid); 136 | if (containTicket == null || !ticketEquals(ticket, containTicket)) { 137 | return false; 138 | } 139 | return soldTickets.remove(ticket.tid, containTicket); 140 | } 141 | 142 | public final void addSoldTicket(Ticket ticket) { 143 | soldTickets.put(ticket.tid, ticket); 144 | } 145 | 146 | private final boolean ticketEquals(Ticket x, Ticket y) { 147 | if(x == y) return true; 148 | if(x == null || y == null) return false; 149 | 150 | return( 151 | (x.tid == y.tid) && 152 | (x.passenger.equals(y.passenger)) && 153 | (x.route == y.route) && 154 | (x.coach == y.coach) && 155 | (x.seat == y.seat) && 156 | (x.departure == y.departure) && 157 | (x.arrival == y.arrival) 158 | ); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/test/java/verify/Trace.java.copy: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | class ThreadId { 8 | // Atomic integer containing the next thread ID to be assigned 9 | private static final AtomicInteger nextId = new AtomicInteger(0); 10 | 11 | // Thread local variable containing each thread's ID 12 | private static final ThreadLocal threadId = 13 | new ThreadLocal() { 14 | @Override protected Integer initialValue() { 15 | return nextId.getAndIncrement(); 16 | } 17 | }; 18 | 19 | // Returns the current thread's unique ID, assigning it if necessary 20 | public static int get() { 21 | return threadId.get(); 22 | } 23 | } 24 | 25 | public class Trace { 26 | final static int threadnum = 1; 27 | final static int routenum = 3; // route is designed from 1 to 3 28 | final static int coachnum = 3; // coach is arranged from 1 to 5 29 | final static int seatnum = 3; // seat is allocated from 1 to 20 30 | final static int stationnum = 3; // station is designed from 1 to 5 31 | 32 | final static int testnum = 3000; 33 | final static int retpc = 30; // return ticket operation is 10% percent 34 | final static int buypc = 60; // buy ticket operation is 30% percent 35 | final static int inqpc = 100; //inquiry ticket operation is 60% percent 36 | 37 | static String passengerName() { 38 | Random rand = new Random(); 39 | long uid = rand.nextInt(testnum); 40 | return "passenger" + uid; 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | 45 | 46 | Thread[] threads = new Thread[threadnum]; 47 | 48 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum); 49 | 50 | final long startTime = System.nanoTime(); 51 | //long preTime = startTime; 52 | 53 | for (int i = 0; i< threadnum; i++) { 54 | threads[i] = new Thread(new Runnable() { 55 | public void run() { 56 | Random rand = new Random(); 57 | Ticket ticket = new Ticket(); 58 | ArrayList soldTicket = new ArrayList(); 59 | 60 | //System.out.println(ThreadId.get()); 61 | for (int i = 0; i < testnum; i++) { 62 | int sel = rand.nextInt(inqpc); 63 | if (0 <= sel && sel < retpc && soldTicket.size() > 0) { // return ticket 64 | int select = rand.nextInt(soldTicket.size()); 65 | long preTime = System.nanoTime() - startTime; 66 | if ((ticket = soldTicket.remove(select)) != null) { 67 | preTime = System.nanoTime() - startTime; 68 | if (tds.refundTicket(ticket)) { 69 | long postTime = System.nanoTime() - startTime; 70 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 71 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 72 | //System.out.flush(); 73 | } else { 74 | long postTime = System.nanoTime() - startTime; 75 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 76 | //System.out.flush(); 77 | } 78 | } else { 79 | long postTime = System.nanoTime() - startTime; 80 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 81 | //System.out.flush(); 82 | } 83 | } else if (retpc <= sel && sel < buypc) { // buy ticket 84 | String passenger = passengerName(); 85 | int route = rand.nextInt(routenum) + 1; 86 | int departure = rand.nextInt(stationnum - 1) + 1; 87 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 88 | long preTime = System.nanoTime() - startTime; 89 | if ((ticket = tds.buyTicket(passenger, route, departure, arrival)) != null) { 90 | long postTime = System.nanoTime() - startTime; 91 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 92 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 93 | soldTicket.add(ticket); 94 | //System.out.flush(); 95 | } else { 96 | long postTime = System.nanoTime() - startTime; 97 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 98 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 99 | //System.out.flush(); 100 | } 101 | } else if (buypc <= sel && sel < inqpc) { // inquiry ticket 102 | 103 | int route = rand.nextInt(routenum) + 1; 104 | int departure = rand.nextInt(stationnum - 1) + 1; 105 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 106 | long preTime = System.nanoTime() - startTime; 107 | int leftTicket = tds.inquiry(route, departure, arrival); 108 | long postTime = System.nanoTime() - startTime; 109 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 110 | //System.out.println(preTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 111 | //System.out.flush(); 112 | 113 | } 114 | } 115 | 116 | } 117 | }); 118 | threads[i].start(); 119 | } 120 | 121 | for (int i = 0; i< threadnum; i++) { 122 | threads[i].join(); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/RandomTest.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.DisplayName; 8 | 9 | @DisplayName("RandomTest") 10 | public class RandomTest { 11 | int threadnum = 8; 12 | int routenum = 20; // route is designed from 1 to 3 13 | int coachnum = 10; // coach is arranged from 1 to 5 14 | int seatnum = 100; // seat is allocated from 1 to 20 15 | int stationnum = 16; // station is designed from 1 to 5 16 | 17 | int testnum = 640000; 18 | final static int RETPC = 10; // return ticket operation is 10% percent 19 | final static int BUYPC = 30; // buy ticket operation is 30% percent 20 | final static int INQPC = 100; // inquiry ticket operation is 60% percent 21 | 22 | private String passengerName() { 23 | Random rand = new Random(System.currentTimeMillis()); 24 | long uid = rand.nextInt(testnum); 25 | return "passenger" + uid; 26 | } 27 | 28 | @Test 29 | @DisplayName("RandomTest - beginTest") 30 | void beginTest() throws InterruptedException { 31 | 32 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum); 33 | 34 | Thread[] threads = new Thread[threadnum]; 35 | final long startTime = System.nanoTime(); 36 | 37 | for (int i = 0; i < threadnum; i++) { 38 | threads[i] = new Thread(new Runnable() { 39 | public void run() { 40 | Random rand = new Random(System.currentTimeMillis()); 41 | Ticket ticket = new Ticket(); 42 | ArrayList soldTicket = new ArrayList(); 43 | 44 | for (int i = 0; i < testnum; i++) { 45 | int sel = rand.nextInt(INQPC); 46 | // refund ticket 47 | if (0 <= sel && sel < RETPC && !soldTicket.isEmpty()) { 48 | int select = rand.nextInt(soldTicket.size()); 49 | if ((ticket = soldTicket.remove(select)) != null) { 50 | long preTime = System.nanoTime() - startTime; 51 | if (tds.refundTicket(ticket)) { 52 | // long postTime = System.nanoTime() - startTime; 53 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " 54 | // + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " 55 | // + ticket.route + " " + ticket.coach + " " + ticket.departure + " " 56 | // + ticket.arrival + " " + ticket.seat); 57 | // System.out.flush(); 58 | } else { 59 | System.err.println(preTime + " " + String.valueOf(System.nanoTime() - startTime) 60 | + " " + ThreadId.get() + " " + "ErrOfRefund"); 61 | fail("Err: cannot refund ticket"); 62 | assert false : "Err: cannot refund ticket"; 63 | } 64 | } else { 65 | long preTime = System.nanoTime() - startTime; 66 | System.err.println(preTime + " " + String.valueOf(System.nanoTime() - startTime) + " " 67 | + ThreadId.get() + " " + "ErrOfRefund"); 68 | assertNotNull(ticket, "Err: soldTicket out of bounds"); 69 | assert false : "Err: soldTicket out of bounds"; 70 | } 71 | } else 72 | // buy ticket 73 | if (RETPC <= sel && sel < BUYPC) { 74 | String passenger = passengerName(); 75 | int route = rand.nextInt(routenum) + 1; 76 | int departure = rand.nextInt(stationnum - 1) + 1; 77 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always 78 | // greater than 79 | // departure 80 | // long preTime = System.nanoTime() - startTime; 81 | if ((ticket = tds.buyTicket(passenger, route, departure, arrival)) != null) { 82 | // long postTime = System.nanoTime() - startTime; 83 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " 84 | // + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " 85 | // + ticket.route + " " + ticket.coach + " " + ticket.departure + " " 86 | // + ticket.arrival + " " + ticket.seat); 87 | soldTicket.add(ticket); 88 | // System.out.flush(); 89 | } else { 90 | // System.out.println(preTime + " " + String.valueOf(System.nanoTime() - startTime) + " " 91 | // + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure + " " 92 | // + arrival); 93 | // System.out.flush(); 94 | } 95 | } else 96 | // inquiry ticket 97 | if (BUYPC <= sel && sel < INQPC) { 98 | 99 | int route = rand.nextInt(routenum) + 1; 100 | int departure = rand.nextInt(stationnum - 1) + 1; 101 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always 102 | // greater than 103 | // departure 104 | // long preTime = System.nanoTime() - startTime; 105 | int leftTicket = tds.inquiry(route, departure, arrival); 106 | // long postTime = System.nanoTime() - startTime; 107 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "RemainTicket" 108 | // + " " + leftTicket + " " + route + " " + departure + " " + arrival); 109 | // System.out.flush(); 110 | } 111 | } 112 | } 113 | }); 114 | threads[i].start(); 115 | } 116 | 117 | for (int i = 0; i < threadnum; i++) { 118 | threads[i].join(); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/PerformanceBenchmark.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import org.openjdk.jmh.annotations.*; 4 | 5 | import java.text.DecimalFormat; 6 | import java.util.*; 7 | 8 | import java.util.concurrent.Callable; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.ThreadLocalRandom; 12 | import java.util.concurrent.TimeUnit; 13 | import java.util.logging.Logger; 14 | 15 | @BenchmarkMode(Mode.Throughput) 16 | @Warmup(iterations = 5, time = 1) 17 | @Measurement(iterations = 5, time = 5) 18 | @Fork(2) 19 | @State(value = Scope.Benchmark) 20 | @OutputTimeUnit(TimeUnit.SECONDS) 21 | public class PerformanceBenchmark { 22 | @Param({ "1", "2", "4", "8", "16", "32", "64", "128" }) 23 | static int nThreads; 24 | 25 | private ExecutorService pool; 26 | 27 | final static int routenum = 20; // route is designed from 1 to 3 28 | final static int coachnum = 10; // coach is arranged from 1 to 5 29 | final static int seatnum = 100; // seat is allocated from 1 to 20 30 | final static int stationnum = 16; // station is designed from 1 to 5 31 | 32 | final static int testnum = 64000; 33 | final static int retpc = 10; // return ticket operation is 10% percent 34 | final static int buypc = 30; // buy ticket operation is 30% percent 35 | final static int inqpc = 100; // inquiry ticket operation is 60% percent 36 | 37 | TicketingDS tds; 38 | ArrayList> list; 39 | 40 | static ThreadLocalRandom rand = ThreadLocalRandom.current(); 41 | 42 | // perform record 43 | class PerformRecord { 44 | int buySuccessTimes; 45 | int buyFailTimes; 46 | int refundTimes; 47 | int inqueryTimes; 48 | } 49 | 50 | ThreadLocal perform = ThreadLocal.withInitial(() -> new PerformRecord()); 51 | List singlePerform = Collections.synchronizedList(new ArrayList()); 52 | ArrayList performList = new ArrayList<>(); 53 | 54 | Logger logger = Logger.getLogger("PerformLog"); 55 | 56 | static String passengerName() { 57 | long uid = rand.nextLong(); 58 | return "passenger" + uid; 59 | } 60 | 61 | @Setup(Level.Trial) 62 | public void initPerform() { 63 | performList.clear(); 64 | } 65 | 66 | @Setup(Level.Iteration) 67 | public void init() { 68 | this.pool = Executors.newFixedThreadPool(nThreads); 69 | tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, nThreads); 70 | list = new ArrayList<>(); 71 | singlePerform.clear(); 72 | for (int i = 0; i < nThreads; i++) { 73 | list.add(new Callable() { 74 | @Override 75 | public Object call() throws Exception { 76 | perform.get().buySuccessTimes = 0; 77 | perform.get().buyFailTimes = 0; 78 | perform.get().refundTimes = 0; 79 | perform.get().inqueryTimes = 0; 80 | 81 | singleTrace(); 82 | 83 | singlePerform.add(perform.get()); 84 | return null; 85 | } 86 | }); 87 | } 88 | } 89 | 90 | @Benchmark 91 | public int performTrace() throws InterruptedException { 92 | pool.invokeAll(list); 93 | return nThreads; 94 | } 95 | 96 | @TearDown(Level.Iteration) 97 | public void finish() { 98 | performCalc(); 99 | pool.shutdown(); 100 | } 101 | 102 | public void performCalc() { 103 | PerformRecord p = new PerformRecord(); 104 | for (int i = 0; i < singlePerform.size(); ++i) { 105 | p.buySuccessTimes += singlePerform.get(i).buySuccessTimes; 106 | p.buyFailTimes += singlePerform.get(i).buyFailTimes; 107 | p.refundTimes += singlePerform.get(i).refundTimes; 108 | p.inqueryTimes += singlePerform.get(i).inqueryTimes; 109 | } 110 | performList.add(p); 111 | } 112 | 113 | @TearDown(Level.Trial) 114 | public void performRes() { 115 | for (int i = 0; i < performList.size(); ++i) { 116 | PerformRecord p = performList.get(i); 117 | int all = p.inqueryTimes + p.refundTimes + p.buySuccessTimes + p.buyFailTimes; 118 | logger.info(String.format( 119 | "[Turn: %02d] Inquery: %08d(%s%%), Refund: %08d(%s%%), BuySuccess: %08d(%s%%), BuyFailed: %08d(%s%%) %n", 120 | i + 1, p.inqueryTimes, new DecimalFormat("0.00").format(p.inqueryTimes * 100.0 / all), 121 | p.refundTimes, new DecimalFormat("0.00").format(p.refundTimes * 100.0 / all), p.buySuccessTimes, 122 | new DecimalFormat("0.00").format(p.buySuccessTimes * 100.0 / all), p.buyFailTimes, 123 | new DecimalFormat("0.00").format(p.buyFailTimes * 100.0 / all))); 124 | } 125 | } 126 | 127 | private final void singleTrace() { 128 | Ticket ticket = null; 129 | ArrayList soldTicket = new ArrayList(); 130 | 131 | for (int i = 0; i < testnum / nThreads; i++) { 132 | int sel = rand.nextInt(inqpc); 133 | // return ticket 134 | if (0 <= sel && sel < retpc && !soldTicket.isEmpty()) { 135 | int select = rand.nextInt(soldTicket.size()); 136 | if ((ticket = soldTicket.remove(select)) != null) { 137 | if (!tds.refundTicket(ticket)) { 138 | System.out.println("ErrOfRefund"); 139 | System.out.flush(); 140 | } 141 | } else { 142 | System.out.println("ErrOfRefund"); 143 | System.out.flush(); 144 | } 145 | perform.get().refundTimes++; 146 | } else 147 | // buy ticket 148 | if (retpc <= sel && sel < buypc) { 149 | String passenger = passengerName(); 150 | int route = rand.nextInt(routenum) + 1; 151 | int departure = rand.nextInt(stationnum - 1) + 1; 152 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always 153 | // greater than 154 | // departure 155 | if ((ticket = tds.buyTicket(passenger, route, departure, arrival)) != null) { 156 | soldTicket.add(ticket); 157 | perform.get().buySuccessTimes++; 158 | } else { 159 | perform.get().buyFailTimes++; 160 | } 161 | } else 162 | // inquiry ticket 163 | if (buypc <= sel && sel < inqpc) { 164 | 165 | int route = rand.nextInt(routenum) + 1; 166 | int departure = rand.nextInt(stationnum - 1) + 1; 167 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always 168 | // greater than 169 | // departure 170 | int leftTicket = tds.inquiry(route, departure, arrival); 171 | 172 | perform.get().inqueryTimes++; 173 | } 174 | } 175 | } 176 | } -------------------------------------------------------------------------------- /src/test/java/linerChecker/Trace.java.copy: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | class ThreadId { 8 | // Atomic integer containing the next thread ID to be assigned 9 | private static final AtomicInteger nextId = new AtomicInteger(0); 10 | 11 | // Thread local variable containing each thread's ID 12 | private static final ThreadLocal threadId = 13 | new ThreadLocal() { 14 | @Override protected Integer initialValue() { 15 | return nextId.getAndIncrement(); 16 | } 17 | }; 18 | 19 | // Returns the current thread's unique ID, assigning it if necessary 20 | public static int get() { 21 | return threadId.get(); 22 | } 23 | } 24 | 25 | public class Trace { 26 | final static int threadnum = 3; 27 | final static int routenum = 1; // route is designed from 1 to 3 28 | final static int coachnum = 10; // coach is arranged from 1 to 5 29 | final static int seatnum = 10; // seat is allocated from 1 to 20 30 | final static int stationnum = 7; // station is designed from 1 to 5 31 | 32 | final static int testnum = 50; 33 | final static int retpc = 10; // return ticket operation is 10% percent 34 | final static int buypc = 30; // buy ticket operation is 30% percent 35 | final static int inqpc = 100; //inquiry ticket operation is 60% percent 36 | 37 | static String passengerName() { 38 | Random rand = new Random(); 39 | long uid = rand.nextInt(testnum); 40 | return "passenger" + uid; 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | 45 | 46 | Thread[] threads = new Thread[threadnum]; 47 | 48 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum); 49 | 50 | final long startTime = System.nanoTime(); 51 | //long preTime = startTime; 52 | 53 | for (int i = 0; i< threadnum; i++) { 54 | threads[i] = new Thread(new Runnable() { 55 | public void run() { 56 | Random rand = new Random(); 57 | Ticket ticket = new Ticket(); 58 | ArrayList soldTicket = new ArrayList(); 59 | 60 | //System.out.println(ThreadId.get()); 61 | for (int i = 0; i < testnum; i++) { 62 | int sel = rand.nextInt(inqpc); 63 | if (0 <= sel && sel < retpc && soldTicket.size() > 0) { // return ticket 64 | int select = rand.nextInt(soldTicket.size()); 65 | long preTime = System.nanoTime() - startTime; 66 | if ((ticket = soldTicket.remove(select)) != null) { 67 | preTime = System.nanoTime() - startTime; 68 | if (tds.refundTicket(ticket)) { 69 | long postTime = System.nanoTime() - startTime; 70 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 71 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 72 | //System.out.flush(); 73 | } else { 74 | long postTime = System.nanoTime() - startTime; 75 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 76 | //System.out.flush(); 77 | } 78 | } else { 79 | long postTime = System.nanoTime() - startTime; 80 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 81 | //System.out.flush(); 82 | } 83 | } else if (retpc <= sel && sel < buypc) { // buy ticket 84 | String passenger = passengerName(); 85 | int route = rand.nextInt(routenum) + 1; 86 | int departure = rand.nextInt(stationnum - 1) + 1; 87 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 88 | long preTime = System.nanoTime() - startTime; 89 | if ((ticket = tds.buyTicket(passenger, route, departure, arrival)) != null) { 90 | long postTime = System.nanoTime() - startTime; 91 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 92 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 93 | soldTicket.add(ticket); 94 | //System.out.flush(); 95 | } else { 96 | long postTime = System.nanoTime() - startTime; 97 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 98 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 99 | //System.out.flush(); 100 | } 101 | } else if (buypc <= sel && sel < inqpc) { // inquiry ticket 102 | 103 | int route = rand.nextInt(routenum) + 1; 104 | int departure = rand.nextInt(stationnum - 1) + 1; 105 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 106 | long preTime = System.nanoTime() - startTime; 107 | int leftTicket = tds.inquiry(route, departure, arrival); 108 | long postTime = System.nanoTime() - startTime; 109 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 110 | //System.out.println(preTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 111 | //System.out.flush(); 112 | 113 | } 114 | } 115 | 116 | } 117 | }); 118 | threads[i].start(); 119 | } 120 | 121 | for (int i = 0; i< threadnum; i++) { 122 | threads[i].join(); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/ticketingsystem/Trace.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | class ThreadId { 8 | // Atomic integer containing the next thread ID to be assigned 9 | private static final AtomicInteger nextId = new AtomicInteger(0); 10 | 11 | // Thread local variable containing each thread's ID 12 | private static final ThreadLocal threadId = 13 | new ThreadLocal() { 14 | @Override protected Integer initialValue() { 15 | return nextId.getAndIncrement(); 16 | } 17 | }; 18 | 19 | // Returns the current thread's unique ID, assigning it if necessary 20 | public static int get() { 21 | return threadId.get(); 22 | } 23 | } 24 | 25 | public class Trace { 26 | final static int threadnum = 8; 27 | final static int routenum = 4; // route is designed from 1 to 3 28 | final static int coachnum = 10; // coach is arranged from 1 to 5 29 | final static int seatnum = 100; // seat is allocated from 1 to 20 30 | final static int stationnum = 16; // station is designed from 1 to 5 31 | 32 | final static int testnum = 64000000; 33 | final static int retpc = 10; // return ticket operation is 10% percent 34 | final static int buypc = 30; // buy ticket operation is 30% percent 35 | final static int inqpc = 100; //inquiry ticket operation is 60% percent 36 | 37 | static String passengerName() { 38 | Random rand = new Random(); 39 | long uid = rand.nextInt(testnum); 40 | return "passenger" + uid; 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | 45 | 46 | Thread[] threads = new Thread[threadnum]; 47 | 48 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum); 49 | 50 | final long startTime = System.nanoTime(); 51 | //long preTime = startTime; 52 | 53 | for (int i = 0; i< threadnum; i++) { 54 | threads[i] = new Thread(new Runnable() { 55 | public void run() { 56 | Random rand = new Random(); 57 | Ticket ticket = new Ticket(); 58 | ArrayList soldTicket = new ArrayList(); 59 | 60 | //System.out.println(ThreadId.get()); 61 | for (int i = 0; i < testnum; i++) { 62 | int sel = rand.nextInt(inqpc); 63 | if (0 <= sel && sel < retpc && soldTicket.size() > 0) { // return ticket 64 | int select = rand.nextInt(soldTicket.size()); 65 | long preTime = System.nanoTime() - startTime; 66 | if ((ticket = soldTicket.remove(select)) != null) { 67 | preTime = System.nanoTime() - startTime; 68 | if (tds.refundTicket(ticket)) { 69 | long postTime = System.nanoTime() - startTime; 70 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 71 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketRefund" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 72 | //System.out.flush(); 73 | } else { 74 | long postTime = System.nanoTime() - startTime; 75 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 76 | //System.out.flush(); 77 | } 78 | } else { 79 | long postTime = System.nanoTime() - startTime; 80 | System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "ErrOfRefund"); 81 | //System.out.flush(); 82 | } 83 | } else if (retpc <= sel && sel < buypc) { // buy ticket 84 | String passenger = passengerName(); 85 | int route = rand.nextInt(routenum) + 1; 86 | int departure = rand.nextInt(stationnum - 1) + 1; 87 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 88 | long preTime = System.nanoTime() - startTime; 89 | if ((ticket = tds.buyTicket(passenger, route, departure, arrival)) != null) { 90 | long postTime = System.nanoTime() - startTime; 91 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 92 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketBought" + " " + ticket.tid + " " + ticket.passenger + " " + ticket.route + " " + ticket.coach + " " + ticket.departure + " " + ticket.arrival + " " + ticket.seat); 93 | soldTicket.add(ticket); 94 | //System.out.flush(); 95 | } else { 96 | long postTime = System.nanoTime() - startTime; 97 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 98 | //System.out.println(preTime + " " + ThreadId.get() + " " + "TicketSoldOut" + " " + route + " " + departure+ " " + arrival); 99 | //System.out.flush(); 100 | } 101 | } else if (buypc <= sel && sel < inqpc) { // inquiry ticket 102 | 103 | int route = rand.nextInt(routenum) + 1; 104 | int departure = rand.nextInt(stationnum - 1) + 1; 105 | int arrival = departure + rand.nextInt(stationnum - departure) + 1; // arrival is always greater than departure 106 | long preTime = System.nanoTime() - startTime; 107 | int leftTicket = tds.inquiry(route, departure, arrival); 108 | long postTime = System.nanoTime() - startTime; 109 | // System.out.println(preTime + " " + postTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 110 | //System.out.println(preTime + " " + ThreadId.get() + " " + "RemainTicket" + " " + leftTicket + " " + route+ " " + departure+ " " + arrival); 111 | //System.out.flush(); 112 | 113 | } 114 | } 115 | 116 | } 117 | }); 118 | threads[i].start(); 119 | } 120 | 121 | for (int i = 0; i< threadnum; i++) { 122 | threads[i].join(); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/MultiThreadTest.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.*; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import static org.junit.jupiter.api.Assertions.*; 8 | import org.junit.jupiter.api.TestInfo; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.DisplayName; 11 | import org.junit.jupiter.api.RepeatedTest; 12 | import org.junit.jupiter.api.RepetitionInfo; 13 | 14 | /** 15 | * unit test This test is only run in single thread. 16 | */ 17 | @DisplayName("MultiThreadTest") 18 | public class MultiThreadTest { 19 | protected static final ExecutorService pool = Executors.newCachedThreadPool(); 20 | // barrier for making all threads begin at same time 21 | protected CyclicBarrier barrier; 22 | // buy tickest 23 | List soldTicket = Collections.synchronizedList(new ArrayList()); 24 | List cannotSoldTicket = Collections.synchronizedList(new ArrayList()); 25 | AtomicInteger soldTicketNum = new AtomicInteger(0); 26 | AtomicInteger refundTicketNum = new AtomicInteger(0); 27 | AtomicInteger realRefundTicketNum = new AtomicInteger(0); 28 | 29 | int opForRoute; 30 | // ticketing date struct 31 | int threadnum = 8; 32 | int routenum = 20; // route is designed from 1 to 20 33 | int coachnum = 10; // coach is arranged from 1 to 10 34 | int seatnum = 100; // seat is allocated from 1 to 100 35 | int stationnum = 16; // station is designed from 1 to 16 36 | final static int TESTNUM = 50; 37 | private byte[] lock = new byte[0]; 38 | protected TicketingDS tds; 39 | 40 | // system start time 41 | protected long startTime; 42 | protected int currentRepetition, totalRepetitions; 43 | 44 | private String passengerName() { 45 | Random rand = new Random(System.currentTimeMillis()); 46 | long uid = rand.nextLong(); 47 | return "passenger" + uid; 48 | } 49 | 50 | @BeforeEach 51 | void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) { 52 | currentRepetition = repetitionInfo.getCurrentRepetition(); 53 | totalRepetitions = repetitionInfo.getTotalRepetitions(); 54 | String methodName = testInfo.getTestMethod().get().getName(); 55 | System.out.println( 56 | String.format("Execute repetition %d of %d for %s", currentRepetition, totalRepetitions, methodName)); 57 | System.out.flush(); 58 | 59 | initData(); 60 | } 61 | 62 | private void initData() { 63 | Random rand = new Random(System.currentTimeMillis()); 64 | opForRoute = rand.nextInt(routenum) + 1; 65 | tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, threadnum * 2); 66 | soldTicket.clear(); 67 | cannotSoldTicket.clear(); 68 | soldTicketNum.set(0); 69 | refundTicketNum.set(0); 70 | realRefundTicketNum.set(0); 71 | startTime = System.nanoTime(); 72 | } 73 | 74 | @RepeatedTest(value = TESTNUM, name = "{displayName} {currentRepetition}/{totalRepetitions}") 75 | void buyAndRefundTickets() { 76 | barrier = new CyclicBarrier(threadnum * 2 + 1); 77 | try { 78 | for (int i = 0; i < threadnum; i++) { 79 | pool.execute(new BuyTickets()); 80 | pool.execute(new RefundTickets()); 81 | } 82 | barrier.await(); // waiting for ready 83 | barrier.await(); // waiting for finish 84 | // sold tickets number must bigger than all seats number 85 | assertTrue(soldTicketNum.get() >= coachnum * seatnum, 86 | "Sold tickets number must bigger than all seats number"); 87 | // refundTicketNum must equal to realRefundTicketNum 88 | assertEquals(refundTicketNum.get(), realRefundTicketNum.get(), 89 | "Value refundTicketNum must equal to realRefundTicketNum"); 90 | // remainTicketNum need equal to sold - refund 91 | int remainTicketNum = tds.inquiry(opForRoute, stationnum / 2, stationnum / 2 + 1); 92 | int cannotSoldTicketNum = cannotSoldTicket.size(); 93 | assertEquals(remainTicketNum, coachnum * seatnum - soldTicketNum.get() + refundTicketNum.get(), 94 | "Value remainTicketNum need equal to all - soldTicketNum + refundTicketNum"); 95 | 96 | } catch (Exception e) { 97 | fail("RuntimeException: " + e.getMessage()); 98 | } 99 | } 100 | 101 | class BuyTickets implements Runnable { 102 | 103 | @Override 104 | public void run() { 105 | Random rand = new Random(System.currentTimeMillis()); 106 | try { 107 | barrier.await(); 108 | int buyTicketNum = rand.nextInt(coachnum * seatnum / threadnum) + (coachnum * seatnum / threadnum) + 1; 109 | for (int i = 0; i < buyTicketNum; ++i) { 110 | // we make all of them pass station stationnum / 2 111 | int departure = rand.nextInt(stationnum / 2) + 1; 112 | int arrival = stationnum / 2 + rand.nextInt(stationnum - stationnum / 2) + 1; 113 | String passenger = passengerName(); 114 | Ticket ticket = tds.buyTicket(passenger, opForRoute, departure, arrival); 115 | if (ticket != null) { 116 | // System.out.printf("[%02d/%02d](%-13d) B: %03d-%03d => (%02d)->(%02d)\n", currentRepetition, 117 | // totalRepetitions, System.nanoTime() - startTime, ticket.coach, ticket.seat, 118 | // ticket.departure, ticket.arrival); 119 | soldTicketNum.getAndIncrement(); 120 | soldTicket.add(ticket); 121 | // System.out.flush(); 122 | } else { 123 | int[] t = new int[2]; 124 | t[0] = departure; 125 | t[1] = arrival; 126 | cannotSoldTicket.add(t); 127 | } 128 | Thread.sleep(rand.nextInt(10)); 129 | } 130 | barrier.await(); 131 | } catch (Exception e) { 132 | throw new RuntimeException(e); 133 | } 134 | } 135 | } 136 | 137 | class RefundTickets implements Runnable { 138 | 139 | @Override 140 | public void run() { 141 | try { 142 | barrier.await(); 143 | Ticket tic = null; 144 | boolean refundOK = false; 145 | Random rand = new Random(System.currentTimeMillis()); 146 | Thread.sleep(rand.nextInt(10)); 147 | while (!soldTicket.isEmpty()) { 148 | synchronized (lock) { 149 | tic = null; 150 | if (!soldTicket.isEmpty()) { 151 | tic = soldTicket.get(rand.nextInt(soldTicket.size())); 152 | soldTicket.remove(tic); 153 | } 154 | } 155 | if (tic != null) { 156 | refundTicketNum.getAndIncrement(); 157 | refundOK = tds.refundTicket(tic); 158 | // System.out.printf("[%02d/%02d](%-13d) R: %03d-%03d <= (%02d)->(%02d)\n", currentRepetition, 159 | // totalRepetitions, System.nanoTime() - startTime, tic.coach, tic.seat, tic.departure, 160 | // tic.arrival); 161 | // System.out.flush(); 162 | if (refundOK) { 163 | realRefundTicketNum.getAndIncrement(); 164 | if(tds.refundTicket(tic)) { 165 | // cannot success 166 | realRefundTicketNum.getAndDecrement(); 167 | } 168 | } else { 169 | System.err.printf("[%02d/%02d](%-13d) R: %03d-%03d != (%02d)->(%02d)\n", currentRepetition, 170 | totalRepetitions, System.nanoTime() - startTime, tic.coach, tic.seat, tic.departure, 171 | tic.arrival); 172 | } 173 | } 174 | Thread.sleep(rand.nextInt(20)); 175 | } 176 | barrier.await(); 177 | } catch (Exception e) { 178 | throw new RuntimeException(e); 179 | 180 | } 181 | } 182 | 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/test/java/ticketingsystem/UnitTest.java: -------------------------------------------------------------------------------- 1 | package ticketingsystem; 2 | 3 | import java.util.*; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.DisplayName; 8 | 9 | /** 10 | * unit test This test is only run in single thread. 11 | */ 12 | @DisplayName("UnitTest") 13 | public class UnitTest { 14 | int routenum = 3; // route is designed from 1 to 3 15 | int coachnum = 5; // coach is arranged from 1 to 5 16 | int seatnum = 10; // seat is allocated from 1 to 20 17 | int stationnum = 8; // station is designed from 1 to 5 18 | long startTime; 19 | 20 | private String passengerName() { 21 | Random rand = new Random(System.currentTimeMillis()); 22 | long uid = rand.nextLong(); 23 | return "passenger" + uid; 24 | } 25 | 26 | @Test 27 | @DisplayName("UnitTest - Test BuyTicket") 28 | void testBuyTicket() throws InterruptedException { 29 | startTime = System.nanoTime(); 30 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, 1); 31 | int route = routenum; 32 | int departure = 1; 33 | int arrival = stationnum; 34 | int beginTickets = tds.inquiry(route, departure, arrival); 35 | long preTime = System.nanoTime() - startTime; 36 | if (beginTickets != seatnum * coachnum) { 37 | long postTime = System.nanoTime() - startTime; 38 | System.err.println( 39 | preTime + " " + postTime + " " + "testBuyTicket Test0: beginTickets=" + beginTickets + "."); 40 | fail("Err: Inquiry wrong seats!"); 41 | assert false : "Err: Inquiry wrong seats!"; 42 | } 43 | 44 | /** 45 | * 1. Test only buy a ticket 46 | */ 47 | preTime = System.nanoTime() - startTime; 48 | String passenger = passengerName(); 49 | // rand a ticket 50 | Random rand = new Random(System.currentTimeMillis()); 51 | departure = rand.nextInt(stationnum - 2) + 2; // 1 to 2 is reverse 52 | arrival = departure + rand.nextInt(stationnum - departure) + 1; 53 | Ticket ticket = tds.buyTicket(passenger, route, departure, arrival); 54 | if (ticket == null) { 55 | long postTime = System.nanoTime() - startTime; 56 | System.err.println(preTime + " " + postTime + " " + "testBuyTicket Test1: Cannot buy a ticket!"); 57 | fail("Err: Cannot buy a ticket!"); 58 | assert false : "Err: Cannot buy a ticket!"; 59 | } 60 | int remainTickets = tds.inquiry(route, departure, arrival); 61 | if (remainTickets != (beginTickets - 1)) { 62 | long postTime = System.nanoTime() - startTime; 63 | System.err.println(preTime + " " + postTime + " " + "testBuyTicket Test1: Return error ticket number " 64 | + remainTickets + "."); 65 | fail("Err: Return error ticket number!"); 66 | assert false : "Err: Return error ticket number!"; 67 | } 68 | /** 69 | * 2. Test buy all tickets 70 | */ 71 | preTime = System.nanoTime() - startTime; 72 | // first we need buy all tickets - 1 73 | for (int i = 0; i < remainTickets; ++i) { 74 | if ((ticket = tds.buyTicket(passenger, route, 1, stationnum)) == null) { 75 | long postTime = System.nanoTime() - startTime; 76 | System.err.println(preTime + " " + postTime + " " 77 | + "testBuyTicket Test2.1: Cannot buy a ticket in turn " + i + "."); 78 | fail("Err: Cannot buy a ticket!"); 79 | assert false : "Err: Cannot buy a ticket!"; 80 | } 81 | } 82 | // second we find what we can buy 83 | remainTickets = tds.inquiry(route, 1, stationnum); 84 | if (remainTickets != 0) { 85 | long postTime = System.nanoTime() - startTime; 86 | System.err.println(preTime + " " + postTime + " " + "testBuyTicket Test2.2: Return error ticket number " 87 | + remainTickets + "."); 88 | fail("Err: Return error ticket number!"); 89 | assert false : "Err: Return error ticket number!"; 90 | } 91 | // third, we try to buy 1 to 2, 1 tickets remain 92 | if ((ticket = tds.buyTicket(passenger, route, 1, 2)) == null) { 93 | long postTime = System.nanoTime() - startTime; 94 | System.err.println(preTime + " " + postTime + " " + "testBuyTicket Test2.3: Cannot buy a ticket!"); 95 | fail("Err: Cannot buy a ticket!"); 96 | assert false : "Err: Cannot buy a ticket!"; 97 | } 98 | remainTickets = tds.inquiry(route, 1, 2); 99 | if (remainTickets != 0) { 100 | long postTime = System.nanoTime() - startTime; 101 | System.err.println(preTime + " " + postTime + " " + "testBuyTicket Test2.3: Return error ticket number " 102 | + remainTickets + "."); 103 | fail("Err: Return error ticket number!"); 104 | assert false : "Err: Return error ticket number!"; 105 | } 106 | /** 107 | * 3. Test overbound situation 108 | */ 109 | if ((ticket = tds.buyTicket(passenger, route, 1, 2)) != null) { 110 | long postTime = System.nanoTime() - startTime; 111 | System.err.println( 112 | preTime + " " + postTime + " " + "testBuyTicket Test3: Can buy a ticket when 0 ticket remain???"); 113 | fail("Err: Can buy a ticket when 0 ticket remain!"); 114 | assert false : "Err: Can buy a ticket when 0 ticket remain!"; 115 | } 116 | } 117 | 118 | @Test 119 | @DisplayName("UnitTest - Test RefundTicket") 120 | void testRefundTicket() throws InterruptedException { 121 | startTime = System.nanoTime(); 122 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, 1); 123 | int route = routenum - 1; 124 | int departure = 1; 125 | int arrival = stationnum; 126 | int beginTickets = tds.inquiry(route, departure, arrival); 127 | long preTime = System.nanoTime() - startTime; 128 | if (beginTickets != seatnum * coachnum) { 129 | long postTime = System.nanoTime() - startTime; 130 | System.err.println( 131 | preTime + " " + postTime + " " + "testRefundTicket Test0: beginTickets=" + beginTickets + "."); 132 | fail("Err: Inquiry wrong seats!"); 133 | assert false : "Err: Inquiry wrong seats!"; 134 | } 135 | // rand a ticket 136 | Random rand = new Random(System.currentTimeMillis()); 137 | departure = rand.nextInt(stationnum - 1) + 1; 138 | arrival = departure + rand.nextInt(stationnum - departure) + 1; 139 | /** 140 | * 1. Test only buy a ticket then refund a ticket 141 | */ 142 | preTime = System.nanoTime() - startTime; 143 | String passenger = passengerName(); 144 | 145 | Ticket ticket = tds.buyTicket(passenger, route, departure, arrival); 146 | if (ticket == null || !tds.refundTicket(ticket)) { 147 | long postTime = System.nanoTime() - startTime; 148 | System.err.println(preTime + " " + postTime + " " + "testRefundTicket Test1: Cannot buy/refund a ticket!"); 149 | fail("Err: Cannot buy a ticket!"); 150 | assert false : "Err: Cannot buy a ticket!"; 151 | } 152 | int remainTickets = tds.inquiry(route, departure, arrival); 153 | if (remainTickets != beginTickets) { 154 | long postTime = System.nanoTime() - startTime; 155 | System.err.println(preTime + " " + postTime + " " + "testRefundTicket Test1: Return error ticket number " 156 | + remainTickets + "."); 157 | fail("Err: Return error ticket number!"); 158 | assert false : "Err: Return error ticket number!"; 159 | } 160 | /** 161 | * 2. Test refund a ticket with wrong ticket info 162 | */ 163 | if (tds.refundTicket(ticket)) { 164 | long postTime = System.nanoTime() - startTime; 165 | System.err.println(preTime + " " + postTime + " " + "testRefundTicket Test2: Cannot refund a ticket!"); 166 | fail("Err: Cannot refund a ticket!"); 167 | assert false : "Err: Cannot refund a ticket!"; 168 | } 169 | remainTickets = tds.inquiry(route, departure, arrival); 170 | if (remainTickets != beginTickets) { 171 | long postTime = System.nanoTime() - startTime; 172 | System.err.println(preTime + " " + postTime + " " + "testRefundTicket Test2: Return error ticket number " 173 | + remainTickets + "."); 174 | fail("Err: Return error ticket number!"); 175 | assert false : "Err: Return error ticket number!"; 176 | } 177 | } 178 | 179 | @Test 180 | @DisplayName("UnitTest - Test InquiryTicket") 181 | void testInquiryTicket() throws InterruptedException { 182 | startTime = System.nanoTime(); 183 | final TicketingDS tds = new TicketingDS(routenum, coachnum, seatnum, stationnum, 1); 184 | int route = routenum - 2; 185 | int departure = 1; 186 | int arrival = stationnum; 187 | int beginTickets = tds.inquiry(route, departure, arrival); 188 | long preTime = System.nanoTime() - startTime; 189 | String passenger = passengerName(); 190 | Random rand = new Random(System.currentTimeMillis()); 191 | 192 | if (beginTickets != seatnum * coachnum) { 193 | long postTime = System.nanoTime() - startTime; 194 | System.err.println( 195 | preTime + " " + postTime + " " + "testInquiryTicket Test0: beginTickets=" + beginTickets + "."); 196 | fail("Err: Inquiry wrong seats!"); 197 | assert false : "Err: Inquiry wrong seats!"; 198 | } 199 | /** 200 | * 1. Test inquiry by sold some tickets 201 | */ 202 | preTime = System.nanoTime() - startTime; 203 | for (int i = 1; i < beginTickets / 2; ++i) { 204 | if (tds.buyTicket(passenger, route, departure, arrival) == null 205 | || tds.inquiry(route, departure, arrival) != beginTickets - i) { 206 | long postTime = System.nanoTime() - startTime; 207 | System.err.println( 208 | preTime + " " + postTime + " " + "testInquiryTicket Test1: beginTickets=" + beginTickets + "."); 209 | fail("Err: Inquiry wrong seats!"); 210 | assert false : "Err: Inquiry wrong seats!"; 211 | } 212 | } 213 | /** 214 | * 2. Test inquiry by sold/refunded some tickets 215 | */ 216 | beginTickets = tds.inquiry(route, departure, arrival); 217 | int refund = rand.nextInt(beginTickets / 2 - 3) + 2; 218 | int buy = rand.nextInt(beginTickets / 2 - 3) + 2; 219 | refund = Math.min(refund, buy); 220 | preTime = System.nanoTime() - startTime; 221 | ArrayList tks = new ArrayList(); 222 | Ticket tic = null; 223 | for (int i = 1; i < buy; ++i) { 224 | if ((tic = tds.buyTicket(passenger, route, departure, arrival)) == null 225 | || tds.inquiry(route, departure, arrival) != beginTickets - i) { 226 | long postTime = System.nanoTime() - startTime; 227 | System.err.println( 228 | preTime + " " + postTime + " " + "testInquiryTicket Test2: beginTickets=" + beginTickets + "."); 229 | fail("Err: Inquiry wrong seats!"); 230 | assert false : "Err: Inquiry wrong seats!"; 231 | } 232 | tks.add(tic); 233 | } 234 | 235 | beginTickets = tds.inquiry(route, departure, arrival); 236 | for (int i = 1; i < refund && tks.size() > 0; ++i) { 237 | tic = tks.get(rand.nextInt(tks.size())); 238 | if (!tds.refundTicket(tic) || 239 | (tds.inquiry(route, departure, arrival) != beginTickets + i)) { 240 | long postTime = System.nanoTime() - startTime; 241 | System.err.println( 242 | preTime + " " + postTime + " " + "testInquiryTicket Test2: remain=" + tds.inquiry(route, departure, arrival) 243 | + ",but we need have " + (beginTickets + i + 1) + "."); 244 | fail("Err: Inquiry wrong seats!"); 245 | assert false : "Err: Inquiry wrong seats!"; 246 | } 247 | tks.remove(tic); 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /result.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "jmhVersion" : "1.23", 4 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 5 | "mode" : "thrpt", 6 | "threads" : 1, 7 | "forks" : 2, 8 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 9 | "jvmArgs" : [ 10 | ], 11 | "jdkVersion" : "14.0.2", 12 | "vmName" : "OpenJDK 64-Bit Server VM", 13 | "vmVersion" : "14.0.2+12", 14 | "warmupIterations" : 5, 15 | "warmupTime" : "1 s", 16 | "warmupBatchSize" : 1, 17 | "measurementIterations" : 5, 18 | "measurementTime" : "5 s", 19 | "measurementBatchSize" : 1, 20 | "params" : { 21 | "nThreads" : "1" 22 | }, 23 | "primaryMetric" : { 24 | "score" : 60.753836489564875, 25 | "scoreError" : 1.3352924192921942, 26 | "scoreConfidence" : [ 27 | 59.41854407027268, 28 | 62.08912890885707 29 | ], 30 | "scorePercentiles" : { 31 | "0.0" : 59.60269362712451, 32 | "50.0" : 60.504859864152024, 33 | "90.0" : 62.31187760753813, 34 | "95.0" : 62.344476176831165, 35 | "99.0" : 62.344476176831165, 36 | "99.9" : 62.344476176831165, 37 | "99.99" : 62.344476176831165, 38 | "99.999" : 62.344476176831165, 39 | "99.9999" : 62.344476176831165, 40 | "100.0" : 62.344476176831165 41 | }, 42 | "scoreUnit" : "ops/s", 43 | "rawData" : [ 44 | [ 45 | 59.60269362712451, 46 | 60.872165647246874, 47 | 60.511604115250876, 48 | 60.49811561305318, 49 | 60.27391059546891 50 | ], 51 | [ 52 | 61.184891054820746, 53 | 62.344476176831165, 54 | 59.8012708088987, 55 | 60.43074677305297, 56 | 62.01849048390077 57 | ] 58 | ] 59 | }, 60 | "secondaryMetrics" : { 61 | } 62 | }, 63 | { 64 | "jmhVersion" : "1.23", 65 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 66 | "mode" : "thrpt", 67 | "threads" : 1, 68 | "forks" : 2, 69 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 70 | "jvmArgs" : [ 71 | ], 72 | "jdkVersion" : "14.0.2", 73 | "vmName" : "OpenJDK 64-Bit Server VM", 74 | "vmVersion" : "14.0.2+12", 75 | "warmupIterations" : 5, 76 | "warmupTime" : "1 s", 77 | "warmupBatchSize" : 1, 78 | "measurementIterations" : 5, 79 | "measurementTime" : "5 s", 80 | "measurementBatchSize" : 1, 81 | "params" : { 82 | "nThreads" : "2" 83 | }, 84 | "primaryMetric" : { 85 | "score" : 110.05064364284583, 86 | "scoreError" : 4.603530934794296, 87 | "scoreConfidence" : [ 88 | 105.44711270805153, 89 | 114.65417457764012 90 | ], 91 | "scorePercentiles" : { 92 | "0.0" : 105.68695535765093, 93 | "50.0" : 110.00935490164889, 94 | "90.0" : 114.76937187468467, 95 | "95.0" : 114.89350090550441, 96 | "99.0" : 114.89350090550441, 97 | "99.9" : 114.89350090550441, 98 | "99.99" : 114.89350090550441, 99 | "99.999" : 114.89350090550441, 100 | "99.9999" : 114.89350090550441, 101 | "100.0" : 114.89350090550441 102 | }, 103 | "scoreUnit" : "ops/s", 104 | "rawData" : [ 105 | [ 106 | 114.89350090550441, 107 | 107.25635492906149, 108 | 110.04625630909442, 109 | 105.68695535765093, 110 | 109.97245349420338 111 | ], 112 | [ 113 | 112.70897848315657, 114 | 107.51617078051743, 115 | 113.65221059730698, 116 | 107.68482589786561, 117 | 111.08872967409712 118 | ] 119 | ] 120 | }, 121 | "secondaryMetrics" : { 122 | } 123 | }, 124 | { 125 | "jmhVersion" : "1.23", 126 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 127 | "mode" : "thrpt", 128 | "threads" : 1, 129 | "forks" : 2, 130 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 131 | "jvmArgs" : [ 132 | ], 133 | "jdkVersion" : "14.0.2", 134 | "vmName" : "OpenJDK 64-Bit Server VM", 135 | "vmVersion" : "14.0.2+12", 136 | "warmupIterations" : 5, 137 | "warmupTime" : "1 s", 138 | "warmupBatchSize" : 1, 139 | "measurementIterations" : 5, 140 | "measurementTime" : "5 s", 141 | "measurementBatchSize" : 1, 142 | "params" : { 143 | "nThreads" : "4" 144 | }, 145 | "primaryMetric" : { 146 | "score" : 305.30853891695716, 147 | "scoreError" : 7.55735055129728, 148 | "scoreConfidence" : [ 149 | 297.75118836565986, 150 | 312.86588946825447 151 | ], 152 | "scorePercentiles" : { 153 | "0.0" : 297.2273472842002, 154 | "50.0" : 305.5998533706106, 155 | "90.0" : 312.8398531397886, 156 | "95.0" : 312.92634094870533, 157 | "99.0" : 312.92634094870533, 158 | "99.9" : 312.92634094870533, 159 | "99.99" : 312.92634094870533, 160 | "99.999" : 312.92634094870533, 161 | "99.9999" : 312.92634094870533, 162 | "100.0" : 312.92634094870533 163 | }, 164 | "scoreUnit" : "ops/s", 165 | "rawData" : [ 166 | [ 167 | 297.2273472842002, 168 | 312.92634094870533, 169 | 304.74578106943187, 170 | 306.5773868519458, 171 | 301.6173947968421 172 | ], 173 | [ 174 | 300.55138115325855, 175 | 308.3262136071227, 176 | 312.0614628595381, 177 | 302.59815492673766, 178 | 306.4539256717893 179 | ] 180 | ] 181 | }, 182 | "secondaryMetrics" : { 183 | } 184 | }, 185 | { 186 | "jmhVersion" : "1.23", 187 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 188 | "mode" : "thrpt", 189 | "threads" : 1, 190 | "forks" : 2, 191 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 192 | "jvmArgs" : [ 193 | ], 194 | "jdkVersion" : "14.0.2", 195 | "vmName" : "OpenJDK 64-Bit Server VM", 196 | "vmVersion" : "14.0.2+12", 197 | "warmupIterations" : 5, 198 | "warmupTime" : "1 s", 199 | "warmupBatchSize" : 1, 200 | "measurementIterations" : 5, 201 | "measurementTime" : "5 s", 202 | "measurementBatchSize" : 1, 203 | "params" : { 204 | "nThreads" : "8" 205 | }, 206 | "primaryMetric" : { 207 | "score" : 532.3139751136114, 208 | "scoreError" : 17.25833665762647, 209 | "scoreConfidence" : [ 210 | 515.0556384559849, 211 | 549.5723117712379 212 | ], 213 | "scorePercentiles" : { 214 | "0.0" : 511.8276231690101, 215 | "50.0" : 532.9889710967914, 216 | "90.0" : 549.0034861605105, 217 | "95.0" : 549.5271436912894, 218 | "99.0" : 549.5271436912894, 219 | "99.9" : 549.5271436912894, 220 | "99.99" : 549.5271436912894, 221 | "99.999" : 549.5271436912894, 222 | "99.9999" : 549.5271436912894, 223 | "100.0" : 549.5271436912894 224 | }, 225 | "scoreUnit" : "ops/s", 226 | "rawData" : [ 227 | [ 228 | 526.9886353981145, 229 | 533.1891183717928, 230 | 511.8276231690101, 231 | 544.2905683835007, 232 | 520.655861631266 233 | ], 234 | [ 235 | 541.8511020753737, 236 | 536.1943552792293, 237 | 532.78882382179, 238 | 525.8265193147477, 239 | 549.5271436912894 240 | ] 241 | ] 242 | }, 243 | "secondaryMetrics" : { 244 | } 245 | }, 246 | { 247 | "jmhVersion" : "1.23", 248 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 249 | "mode" : "thrpt", 250 | "threads" : 1, 251 | "forks" : 2, 252 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 253 | "jvmArgs" : [ 254 | ], 255 | "jdkVersion" : "14.0.2", 256 | "vmName" : "OpenJDK 64-Bit Server VM", 257 | "vmVersion" : "14.0.2+12", 258 | "warmupIterations" : 5, 259 | "warmupTime" : "1 s", 260 | "warmupBatchSize" : 1, 261 | "measurementIterations" : 5, 262 | "measurementTime" : "5 s", 263 | "measurementBatchSize" : 1, 264 | "params" : { 265 | "nThreads" : "16" 266 | }, 267 | "primaryMetric" : { 268 | "score" : 1032.392253459889, 269 | "scoreError" : 60.18258646588565, 270 | "scoreConfidence" : [ 271 | 972.2096669940033, 272 | 1092.5748399257745 273 | ], 274 | "scorePercentiles" : { 275 | "0.0" : 933.6282833843867, 276 | "50.0" : 1040.928074544579, 277 | "90.0" : 1081.7149497594016, 278 | "95.0" : 1084.6062011804754, 279 | "99.0" : 1084.6062011804754, 280 | "99.9" : 1084.6062011804754, 281 | "99.99" : 1084.6062011804754, 282 | "99.999" : 1084.6062011804754, 283 | "99.9999" : 1084.6062011804754, 284 | "100.0" : 1084.6062011804754 285 | }, 286 | "scoreUnit" : "ops/s", 287 | "rawData" : [ 288 | [ 289 | 1006.3468621349178, 290 | 1041.5673706770194, 291 | 933.6282833843867, 292 | 1038.521466204794, 293 | 1040.2887784121383 294 | ], 295 | [ 296 | 1042.9068026146083, 297 | 1055.6936869697365, 298 | 1084.6062011804754, 299 | 1031.7118841392353, 300 | 1048.6511988815773 301 | ] 302 | ] 303 | }, 304 | "secondaryMetrics" : { 305 | } 306 | }, 307 | { 308 | "jmhVersion" : "1.23", 309 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 310 | "mode" : "thrpt", 311 | "threads" : 1, 312 | "forks" : 2, 313 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 314 | "jvmArgs" : [ 315 | ], 316 | "jdkVersion" : "14.0.2", 317 | "vmName" : "OpenJDK 64-Bit Server VM", 318 | "vmVersion" : "14.0.2+12", 319 | "warmupIterations" : 5, 320 | "warmupTime" : "1 s", 321 | "warmupBatchSize" : 1, 322 | "measurementIterations" : 5, 323 | "measurementTime" : "5 s", 324 | "measurementBatchSize" : 1, 325 | "params" : { 326 | "nThreads" : "32" 327 | }, 328 | "primaryMetric" : { 329 | "score" : 1157.099178828576, 330 | "scoreError" : 73.0813333908307, 331 | "scoreConfidence" : [ 332 | 1084.0178454377453, 333 | 1230.1805122194066 334 | ], 335 | "scorePercentiles" : { 336 | "0.0" : 1078.155064732394, 337 | "50.0" : 1162.3505461715795, 338 | "90.0" : 1238.8138448810168, 339 | "95.0" : 1241.9839196376615, 340 | "99.0" : 1241.9839196376615, 341 | "99.9" : 1241.9839196376615, 342 | "99.99" : 1241.9839196376615, 343 | "99.999" : 1241.9839196376615, 344 | "99.9999" : 1241.9839196376615, 345 | "100.0" : 1241.9839196376615 346 | }, 347 | "scoreUnit" : "ops/s", 348 | "rawData" : [ 349 | [ 350 | 1178.6937708041648, 351 | 1118.215456565556, 352 | 1167.367607038353, 353 | 1241.9839196376615, 354 | 1210.2831720712152 355 | ], 356 | [ 357 | 1116.5246606801804, 358 | 1078.155064732394, 359 | 1157.333485304806, 360 | 1173.175890863704, 361 | 1129.2587605877256 362 | ] 363 | ] 364 | }, 365 | "secondaryMetrics" : { 366 | } 367 | }, 368 | { 369 | "jmhVersion" : "1.23", 370 | "benchmark" : "ticketingsystem.PerformanceBenchmark.performTrace", 371 | "mode" : "thrpt", 372 | "threads" : 1, 373 | "forks" : 2, 374 | "jvm" : "C:\\Program Files\\AdoptOpenJDK\\jdk-14.0.2.12-hotspot\\bin\\java.exe", 375 | "jvmArgs" : [ 376 | ], 377 | "jdkVersion" : "14.0.2", 378 | "vmName" : "OpenJDK 64-Bit Server VM", 379 | "vmVersion" : "14.0.2+12", 380 | "warmupIterations" : 5, 381 | "warmupTime" : "1 s", 382 | "warmupBatchSize" : 1, 383 | "measurementIterations" : 5, 384 | "measurementTime" : "5 s", 385 | "measurementBatchSize" : 1, 386 | "params" : { 387 | "nThreads" : "64" 388 | }, 389 | "primaryMetric" : { 390 | "score" : 1143.2925559886198, 391 | "scoreError" : 136.57364636592416, 392 | "scoreConfidence" : [ 393 | 1006.7189096226957, 394 | 1279.866202354544 395 | ], 396 | "scorePercentiles" : { 397 | "0.0" : 1006.4869430114724, 398 | "50.0" : 1195.5759676932903, 399 | "90.0" : 1225.9862480969987, 400 | "95.0" : 1226.5820479642357, 401 | "99.0" : 1226.5820479642357, 402 | "99.9" : 1226.5820479642357, 403 | "99.99" : 1226.5820479642357, 404 | "99.999" : 1226.5820479642357, 405 | "99.9999" : 1226.5820479642357, 406 | "100.0" : 1226.5820479642357 407 | }, 408 | "scoreUnit" : "ops/s", 409 | "rawData" : [ 410 | [ 411 | 1220.624049291865, 412 | 1006.4869430114724, 413 | 1212.692709104342, 414 | 1054.8368998580847, 415 | 1207.476299753562 416 | ], 417 | [ 418 | 1046.8858140984282, 419 | 1053.0417699436482, 420 | 1220.623391227542, 421 | 1183.6756356330188, 422 | 1226.5820479642357 423 | ] 424 | ] 425 | }, 426 | "secondaryMetrics" : { 427 | } 428 | } 429 | ] 430 | 431 | 432 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------