Model Checking Real Time Java Using Java PathFinder

合集下载

JAVA获取当前时间的方法

JAVA获取当前时间的方法

JAVA获取当前时间的方法在Java中,有多种获取当前时间的方法,这些方法包括使用系统时间、Calendar类、Date类、Time类以及使用第三方库等。

下面将为您详细介绍每种方法。

一、使用系统时间Java提供了System类来获取当前的系统时间,可以使用System.currentTimeMillis(方法获取当前的时间戳。

时间戳表示的是当前时刻与1970年1月1日午夜之间的毫秒数。

可以将时间戳转换为特定的日期格式,如下所示:```long currentTimeMillis = System.currentTimeMillis(;Date date = new Date(currentTimeMillis);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String currentTime = sdf.format(date);```二、使用Calendar类Java的Calendar类提供了丰富的方法来处理日期和时间。

可以使用Calendar.getInstance(方法获取当前的日历实例,然后使用get(方法获取各个时间字段的值,如年、月、日、时、分、秒等。

以下是一个示例:```Calendar calendar = Calendar.getInstance(;int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1; // 注意月份从0开始,需要加1int day = calendar.get(Calendar.DAY_OF_MONTH);int hour = calendar.get(Calendar.HOUR_OF_DAY);int minute = calendar.get(Calendar.MINUTE);int second = calendar.get(Calendar.SECOND);```三、使用Date类Java的Date类可以表示特定的日期和时间。

realtime error 的处理

realtime error 的处理

realtime error 的处理"realtime error" 并不是一个特定的错误信息,而是一个泛指的术语,表示在实时系统或应用程序中发生的错误。

实时系统通常要求在特定的时间范围内产生响应,因此错误的处理方式需要考虑实时性的要求。

以下是一些处理实时错误的一般性建议:
1. 错误日志和报警:在实时系统中,记录错误日志对于排除问题和系统监控至关重要。

当发生错误时,及时记录错误信息,并发送报警通知相关人员。

2. 异常处理:在代码中使用适当的异常处理机制,以便在发生错误时能够进行优雅的处理。

这可能包括捕获异常、记录错误信息,并采取适当的措施,例如进行系统恢复或向管理员发出警报。

3. 容错设计:考虑实施容错机制,使系统能够在错误发生时继续运行,而不至于完全崩溃。

这可能包括备份系统、冗余设计、错误恢复等。

4. 实时性要求:确保错误处理机制本身不会引入不可接受的延迟。

在实时系统中,处理错误的方式也需要考虑对系统性能的影响。

5. 自动恢复:实现自动恢复机制,使系统能够在发生错误后自动尝试修复问题,以减少对系统的干扰。

6. 监控和调试:在实时系统中加入监控和调试工具,以便能够实时监测系统的运行状态,迅速发现和诊断错误。

7. 测试和验证:在开发和部署过程中进行充分的测试,以确保系统在面临各种情况下都能正确处理错误。

这可能包括单元测试、集成测试和系统级测试。

总的来说,在处理实时错误时,关键是综合考虑系统的实时性要求、容错能力、自动恢复机制以及及时的监控和报警。

错误处理策略应该是系统设计和开发的一个重要组成部分。

如何调试代码中的时间和日期问题

如何调试代码中的时间和日期问题

如何调试代码中的时间和日期问题在编写代码时,时间和日期是经常涉及到的问题。

然而,由于时间和日期的复杂性和特殊性,调试起来可能会比较困难。

下面将介绍一些常见的时间和日期问题,并提供一些调试技巧。

一、常见的时间和日期问题1.时区问题:当涉及到不同时区时,时间会有所不同。

在处理时间时,要确保正确地转换为所需的时区,以避免出现时间混乱的情况。

2.夏令时问题:夏令时是指在特定季节调整时钟,以节约能源和利用日照时间更长。

在处理夏令时时,需要特别注意时间的转换和计算,以免导致错误的结果。

3.时间戳问题:时间戳是指距离特定时间点或固定日期的秒数。

在处理时间戳时,要确保正确地转换为日期或时间,并注意数据类型的匹配,以免产生不一致的结果。

4.闰年问题:闰年是指能够被4整除但不能被100整除,或者是能够被400整除的年份。

在判断闰年时,要使用合适的算法,以避免出现错误的结果。

5.时间格式问题:不同的编程语言和库可能有不同的时间格式要求。

在处理时间时,要确保使用正确的格式,并且进行必要的转换,以便与系统或其他模块正确交互。

二、调试技巧1.使用调试工具:现代的集成开发环境(IDE)通常提供了强大的调试工具,可以逐步执行代码并观察变量的值。

通过使用断点和单步执行功能,可以查看程序在处理时间和日期时的具体行为,有助于找出问题所在。

2.输出日志信息:在代码中插入适当的日志语句,输出时间和日期相关的变量值以及计算结果。

通过查看日志信息,可以追踪程序执行过程中时间和日期的变化,从而找到出错的地方。

3.对比测试数据:准备一组已知的测试数据,包括一些边界情况和特殊情况。

与预期结果进行对比,分析实际输出和期望输出之间的差异。

通过对比测试数据,可以帮助快速定位问题和找出错误的原因。

4.单元测试:编写单元测试用例,针对时间和日期相关的函数进行测试。

通过输入不同的时间和日期值,验证函数的输出是否符合预期结果。

单元测试是一种高效的调试手段,可以对时间和日期相关问题进行及时发现和修复。

A runtime assertion checker for the Java Modeling Language (JML

A runtime assertion checker for the Java Modeling Language (JML
Yoonsik Cheon and Gary T. Leavens∗ Department of Computer Science, Iowa State University
226 Atanasoff Hall Ames, IA 50011-1040, USA {cheon,leavens}@
One technique that helps to produce an immediate payoff for writing formal interface specifications is to check specification assertions during the execution of programs. A formal interface specification is just a mathematical formula, but it becomes useful for testing and debugging when it can be executed to check the validity of an implementation. Checking assertions at runtime is a practical and effective means for debugging programs, as Meyer and others have emphasized [20, 22]. It also helps one debug the specifications themselves, and thus improves the quality and accuracy of documentation. Also, checking assertions at runtime can help automate parts of testing [3]. Finally, executing formal specifications is much more practical than using them for formal verification of correctness.

java 跳过引用检查编译

java 跳过引用检查编译

Java 跳过引用检查编译概述Java 是一种编译型语言,这意味着在运行之前,代码必须先被编译成机器代码。

编译器的主要任务之一是进行类型检查,以确保代码中使用的变量和对象具有正确的类型。

然而,在某些情况下,开发人员可能需要跳过引用检查编译,以便能够运行不符合类型要求的代码。

跳过引用检查编译的方法有两种主要的方法可以跳过 Java 中的引用检查编译:1. 使用 @SuppressWarnings 注解2. 使用编译器选项 -Xlint:disable1. 使用 @SuppressWarnings 注解@SuppressWarnings 注解允许开发人员指定要抑制的特定警告或错误代码。

要使用此注解,开发人员可以在变量、方法或类声明之前添加@SuppressWarnings 注解,并指定要抑制的警告或错误代码。

例如,以下代码使用@SuppressWarnings 注解来抑制编译器关于使用未初始化变量 x 的警告:java@SuppressWarnings("unused")private int x;2. 使用编译器选项 -Xlint:disable编译器选项-Xlint:disable 允许开发人员禁用所有或部分警告或错误消息。

要使用此选项,开发人员可以在编译命令中添加-Xlint:disable 选项,并指定要禁用的警告或错误代码。

例如,以下命令禁用所有警告消息:javac -Xlint:disable -source 1.8 MyProgram.java跳过引用检查编译的风险跳过引用检查编译可能会带来一些潜在的风险,包括:1. 代码错误:跳过引用检查编译可能会导致代码中出现错误,因为编译器无法检测到不符合类型要求的代码。

这可能会导致程序在运行时出现错误,甚至崩溃。

2. 安全漏洞:跳过引用检查编译还可能会导致安全漏洞,因为编译器无法检测到不安全的代码。

这可能会允许攻击者利用这些漏洞来攻击程序。

验证java是否安装成功的方法

验证java是否安装成功的方法

验证java是否安装成功的方法要验证Java是否成功安装,可以通过以下几种方法来确定:1. 检查Java版本:打开终端或命令提示符窗口,输入“java -version”命令,如果成功安装了Java,将会显示Java的版本信息。

例如,显示类似“java version '1.8.0_271'”这样的信息,即表示已经成功安装了Java。

2. 编写并运行一个简单的Java程序:使用任何文本编辑器创建一个后缀名为.java的Java源代码文件,例如HelloWorld.java。

在该文件中编写以下Java 程序代码:public class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}保存文件后,在终端或命令提示符窗口中使用javac编译器将该文件编译为.class文件,使用命令“javac HelloWorld.java”。

如果没有报错,则说明Java 成功安装。

接下来,使用命令“java HelloWorld”来运行该程序。

如果成功运行并输出“Hello, World!”这句话,则说明Java安装成功。

3. 检查Java环境变量设置:在Windows系统中,可以通过以下步骤来检查Java 环境变量设置。

首先,点击“开始”按钮,选择“计算机”或“我的电脑”,然后右键单击并选择“属性”。

在弹出的窗口中,选择“高级系统设置”,然后点击“环境变量”按钮。

在环境变量窗口中,查找“系统变量”下的“Path”变量,确保包含Java安装的路径。

例如,“C:\Program Files\Java\jdk1.8.0_271\bin”或“C:\Program Files\Java\jre1.8.0_271\bin”。

如果该路径不存在或不正确,可以手动添加或修改。

java 判断时间到现在1小时内的方法

java 判断时间到现在1小时内的方法

java 判断时间到现在1小时内的方法全文共四篇示例,供读者参考第一篇示例:在日常的软件开发中,经常需要对时间进行判断和处理。

其中一个常见的需求是判断当前时间到指定时间点是否在1小时内。

在Java 中,我们可以通过一些方法来实现这个功能。

本文将介绍如何用Java 来判断当前时间到现在1小时内的方法。

我们需要获取当前时间。

在Java中,可以使用`LocalDateTime`类来表示当前时间。

代码如下所示:```javaLocalDateTime now = LocalDateTime.now();```接下来,我们需要获取指定时间点。

可以通过`LocalDateTime`类的`of`方法来构造指定的时间点。

我们可以创建一个距离当前时间1小时的时间点。

然后,我们可以使用`isAfter`和`isBefore`方法来判断当前时间是否在指定时间点的前后。

如果当前时间在指定时间点之后1小时内,则表示当前时间到现在1小时内。

```javaboolean isWithinOneHour = now.isAfter(oneHourAgo) && now.isBefore(oneHourLater);```我们可以根据`isWithinOneHour`的值来进行相应的操作。

打印日志或者触发某些事件。

```javaif(isWithinOneHour) {System.out.println("当前时间到现在1小时内");} else {System.out.println("当前时间不在1小时内");}```需要注意的是,以上方法中使用的时间类是`LocalDateTime`,它的精度是毫秒级别的。

如果需要更高精度的时间,可以考虑使用`Instant`或`ZonedDateTime`类。

需要注意的是,以上方法只能判断当前时间到指定时间点是否在1小时内,如果需要判断任意两个时间点之间的时间间隔是否在1小时内,可以使用`Duration`类。

modeltime包的用法

modeltime包的用法

modeltime包的用法ModelTime是一个Python包,用于时间序列模型的建模和预测。

它提供了一系列的时间序列模型,包括常见的ARIMA模型、GARCH模型、VAR模型等。

此外,ModelTime还提供了一些用于时间序列预处理和特征工程的功能,如季节性分解、平稳性检验等。

本文将详细介绍ModelTime包的使用方法,并通过案例演示如何进行时间序列的建模和预测。

一、安装和导入ModelTime包首先,我们需要安装ModelTime包。

可以通过pip命令来进行安装:pip install ModelTime安装完成后,就可以通过import语句导入ModelTime包了:import ModelTime as mt二、时间序列数据的读取和预处理在进行时间序列模型建模之前,我们需要先读取数据,并对数据进行预处理。

1.读取数据读取时间序列数据可以使用pandas包中的read_csv函数。

假设我们有一个名为data.csv的文件,其中包含了时间序列数据。

可以通过以下代码将数据读取到DataFrame中:import pandas as pddata = pd.read_csv('data.csv')2.转换为时间序列将读取到的数据转换为时间序列数据,可以使用pandas中的to_datetime函数。

假设我们的数据中有一个列名为'date',表示时间。

我们可以通过以下代码将其转换为时间序列数据:data['date'] = pd.to_datetime(data['date'])3.设置时间为索引为了方便进行时间序列的处理和建模,我们需要将时间列设置为数据的索引。

可以使用pandas中的set_index函数来完成这一步骤:data.set_index('date', inplace=True)4.平稳性检验对于时间序列模型,通常要求数据是平稳的。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Model Checking Real Time JavaUsing Java PathFinderGary Lindstrom1,Peter C.Mehlitz2,and Willem Visser21University of Utah2NASA Ames Research CenterAbstract.The Real Time Specification for Java(RTSJ)is an augmen-tation of Java for real time applications of various degrees of hardness.The central features of RTSJ are real time threads;user defined sched-ulers;asynchronous events,handlers,and control transfers;a priorityinheritance based default scheduler;non-heap memory areas such as im-mortal and scoped,and non-heap real time threads whose execution isnot impeded by garbage collection.The Robust Software Systems groupat NASA Ames Research Center has Java PathFinder(JPF)underdevelopment,a Java model checker.JPF at its core is a state exploringJVM which can examine alternative paths in a Java program(e.g.,viabacktracking)by trying all nondeterministic choices,including threadscheduling order.This paper describes our implementation of an RTSJprofile(subset)in JPF,including requirements,design decisions,andcurrent implementation status.Two examples are analyzed:jobs on amultiprogramming operating system,and a complex resource contentionexample involving autonomous vehicles crossing an intersection.The util-ity of JPF infinding logic and timing errors is illustrated,and the re-maining challenges in supporting all of RTSJ are assessed.1OverviewThe possibility of using Real Time Specification for Java(RTSJ)[fJEG]soft-ware on future missions is under consideration at NASA,for all the familiar reasons:standardized(i.e.,platform independent)semantics,a rich and vigorous marketplace of implementations and tools,and the overall software engineering advantages of Java as a type safe object-oriented programming language.RTSJ is not based on any Java core language extensions;rather,all its capabilities are conveyed by new classes with special semantics,albeit with some refine-ment of semantics for existing Java classes.This design decision in effect strikes a bargain:less run time predictability,in exchange for language stability.An alternative choice might have been to enhance the declarative content of the language in the interest of stronger compile time program validation,as was done for example with exceptions in Java.The dual consequence of this design decision is inadequacy of static analysis for RTSJ software verification and validation,and a corresponding vital need for techniques performing dynamic analysis,e.g.,model checking.In particular, D.A.Peled and Y.-K.Tsay(Eds.):ATV A2005,LNCS3707,pp.444–456,2005.c Springer-Verlag Berlin Heidelberg2005Model Checking Real Time Java Using Java PathFinder445 many of the dynamic features of RTSJ are beyond the scope of current worst-case execution time(WCET)analysis techniques.While RTSJ programmers can in principle restrict themselves to an RTSJ subset amendable to WCET analysis, this would significantly reduce the appeal and advantages of using RTSJ over existing real time languages.We report here on an application of the Java PathFinder model checker(JPF)[VHB+03,JPFa]to RTSJ programs,focusingon the latter’s dynamic,time quantified behavior,with the goal of developing a tool capable of validating RTSJ applications,ideally to the level of mission deployability.Our approach emphasizes the central issue of temporal correctness (e.g.,threads meeting deadlines)under nondeterministic choices;correctness of memory usages and asynchronous controlflow are reserved for future work.Thus we are focusing on classical correctness issues in real time software,rather than issues related to specialized JVM behavior.Our approach uses discrete event simulation(DES)as a basis for modeling time.Real time threads are modeled as ordinary Java threads,constrained to run one at a time,i.e.,as coroutine’s.Their interactions,e.g.,through CPU scheduling,are modeled by resource contention techniques familiar to DES pro-gramming(a summary of DES concepts is given in§3).This permits execution of programs within our RTSJ profile on any Java implementation.However,two important capabilities are provided by analyzing(running) RTSJ programs under JPF:(a)execution cost logging at the bytecode level,and (b)alternative execution path exploration via nondeterministic choice selection. Point(a)permits closing an important causality loop impossible on an ordinary JVM:thread execution cost→deadline misses→miss events→event handlers→additional thread execution cost Analyzing such loops is a critical requirement in the validation and verifica-tion of complex RTSJ applications,and is well beyond the capability of current static analyzers.2RTSJ Under JPF:Requirements and ObjectivesThefirst question is clearly what does it mean to model check an RTSJ program? The starting point is to view the RTSJ program as just another Java program (albeit with a class library with special semantics),and simply execute it using the model checking vigilance of JPF.This isfine,except that this presumes the availability of an RTSJ enabled JVM within JPF,which we do not have.Unlike a simple Java program,in which the notion of time generally plays an insignificant role,time in RTSJ programs plays a major correctness role,e.g., in quantifying real time deadlines.Moreover,an RTSJ program(the embedded program)must be exercised within an implementation of its environment(the embedding program).In our view,specifying,constructing and verifying such environments are often tasks of difficulty equal to or greater than that of the446G.Lindstrom,P.C.Mehlitz,and W.Visserembedded system.An example is aflight control system,where a fully accurate embedding system must model all the dynamics of the aircraft,as is done in a flight simulator.Hence ensuring that embedding code is correct is as important (or more so)than ensuring that the embedded code is correct.We adopted the following goals for model checking RTSJ under JPF:1.Make no changes to the JPF implementation–clearly,a major softwareengineering win if achievable.2.Implement the embedding code in Java,and model check the entire combinedsystem–a major validation win if possible.3.Deal with time through DES modeling–a familiar and well understoodtechnology.4.Implement all RTSJ thread interactions(e.g.,priority based scheduling withpriority inversion avoidance via priority inheritance)through resource con-tention techniques traditional to DES.5.Exploit the run time cost accounting capabilities of JPF to detect deadlinemisses by real time threads,and to take appropriate actions,e.g.,invoking overrun handlers in the embedded code.6.Finally,utilize the path coverage capabilities of JPF to locate bugs involvingnondeterminacy and race conditions,notably nondeterministic choice points in the embedding code providing greater test coverage.3Step1:RTSJ in a Simulation EnvironmentThefirst step in model checking RTSJ is to implement a profile of RTSJ as a set of conventional Java classes.This we have done to afirst level of realism–several features have yet to be implemented,as discussed in§10.The classes in our im-plementation include RealtimeThread,PriorityScheduler,AsyncEvent,AsyncEven-tHandler,OneShotTimer,PeriodicTimer and RelativeTime.The fundamental concepts of DES(as developed in the Simula system of the 1970’s[BDMN73])can be summarized as follows:–Individual processes(the traditional terminology–henceforth we will use thread)are conceptually concurrent,but in fact execute in an interleaved fashion as coroutines,as mentioned above.–A thread may be executing,activated,or passivated.•An executing thread is the one currently running as a coroutine;•An activated thread is not executing,but is scheduled to do so in the future at a time indicated its event notice on the simulation’s event list.•A passivated thread is neither executing nor active;such threads are typ-ically waiting for some condition to become true,such as being granteda resource.–Scheduling operations on threads include activate(schedule),passivate,and hold,which is a compound operation comprising activation at a later sched-uled time time,and passivation.Model Checking Real Time Java Using Java PathFinder447–The main thread controls the overall simulation by repeatedly dequeueing from the event list the event notice with the earliest event time,advancing the simulation clock to the time in that event notice,and notifying the associated thread to run–until the event list becomes empty,or a global shutdown operation is invoked.Since RealtimeThread’s are constrained to run as coroutines,the JVM sched-uler has only one scheduling choice possible,and DES event based scheduling is used in an outboard manner to orchestrate thread interleaving.As mentioned in §2,all RealtimeThread interactions are achieved by contention for Resource ob-jects,e.g.,a CPU.The upshot is that no changes are necessary to the schedulersof the underlying JVM or JPF to implement scheduling policies such as prior-ity inheritance with FIFO ordering within priorities,as required by the default RTSJ scheduler.Since Java’s real time clock is replaced by the simulation clock, all RTSJ executions in this implementation are deterministic(repeatable),even if they use pseudo random methods to draw numbers from probability distri-butions(assumingfixed seeds)or offer the option of pseudo randomly selecting orders of events scheduled at identical times.Fig.1.RTSJ architecture under JPF4Step2:Combining RTSJ and JPFEmbedded code written in our RTSJ profile,together with its embedding test code using DES facilities including simulated time,comprise an ordinary Java program that can be run under any Java implementation(without accurate run time modeling,however).The next step is to run the combined program under JPF,with the following additional benefits:–Nondeterministic state exploration,including all orderings of equal priority events scheduled for the same instant,and choice points in the embedding code,and–Cost accounting,with overrun detection and invocation of appropriate han-dlers,as described below.448G.Lindstrom,P.C.Mehlitz,and W.VisserOur adaptation of JPF is being done in two stages.Thefirst stage exploits two customization features already available in JPF:its JVM listener interface [JPFb],and its Model Java Interface(MJI)[JPFc](both features are utilized in the Control Program box in Fig.1).JVM listener interface:Logging run time(albeit idealized)for Java code un-der JPF can be done using JPF’s JVM listener interface,which invokes control program listener methods on various occurrences,including the execution of each byte code instruction.We use a very simple accounting technique here,whereby each byte code is assigned afixed run time in a look up table.By this technique the execution time(summed byte code costs)from the start to the end of a RealtimeThread can be accumulated.Similarly,this interface is used to detect execution path backtracking by the JPF JVM,so that path specific accounting data structures can be correspondingly backtracked.Model Java interface:The MJI interface permits Java code executing under JPF’s specialized JVM to access the underlying JVM for access to native facili-ties.This turns out to be crucial in arranging that run time cost logging,which executes outside the JPF JVM,is accessible to the RTSJ application code,which executes within the JPF JVM.For example,suppose an AsyncEventHandler in-vocation has a run time in excess of its stipulated limit,as observed through an MJI native method.This can trigger the invocation of an overrun event handler, which must execute within the JPF JVM.The second and more difficult stage of adapting JPF for RTSJ concerns fea-tures that must be implemented by JVM modifications.These features,which include non-heap memory areas and non-heap real time threads,as well as asyn-chronous control transfers,are discussed in§7.1.5Scheduling PoliciesWe now give more details on our control of scheduling by means of resource con-tention policies.We illustrate our approach by discussion offive representative policies:FIFO,priority,priority inheritance,priority ceiling,and preemption. Thefirst two are naive policies inviting priority inversion;the third is obliga-tory in RTSJ’s default scheduler;the fourth is an explicit option,and the RTSJ specification is silent on thefifth.1)FIFO:This simplistic policy guarantees fairness,but ignores thread priority.2)Priority:Here threads waiting for a resource are selected by(fixed)priority first,and then by FIFO within equal priorities.This policy,as well as FIFO above,provides no defense against priority inversion.3)Priority inheritance(PI):This well known policy works by increasing the priority of the thread possessing a PI resource to equal the maximum priority of any thread waiting for that resource(its dynamic priority).There are two perhaps unobvious consequences of this policy:Model Checking Real Time Java Using Java PathFinder449 1.Since a thread may possess multiple resources,its dynamic priority is basedon the maximum priority of any thread waiting for any of the resources it possesses,and2.The priorities involved are of course dynamic priorities,so an attemptedseize of a resource held by a thread waiting for another resource can cause cascaded priority inheritance effects(and conversely for release’s).4)Priority ceiling(PC):A PC resource has afixed priority(its ceiling pri-ority)which is used to temporarily elevate the priority of any thread possessing it.If a thread has a dynamic priority greater than the resource’s ceiling priority, an attempt to seize the resource causes a PriorityCeilingException to be thrown (the absence of which is an important verification condition).5)Preemption:A resource managed under this policy does not change a thread’s priority when seized.A thread seizing a resource of this kind only waits if the resource is currently held,and the thread’s priority is less than or equal to the priority of the thread holding the resource.If the thread’s priority is greater that that of the thread holding the resource,it steals the resource.Modeling thefirst four policies is straightforward DES programming.Pre-emption is a bit trickier,because possession periods(e.g.,modeling computa-tional activity by a thread using a CPU resource)can be prematurely ended when the resource is stolen by a higher priority thread.This can be implemented by wrapping such hold method calls in loops that sum actual hold times,and re-exert hold invocations until the stipulated hold time is attained.Allfive policy implementations easily generalize to multiprocessing systems by managing pools of CPU resources.6ApplicationsWe now discuss application of our RTSJ implementation in JPF to two example programs.Thefirst is a simple model of a multiprogramming operating system (OS),while the second is a complex resource contention example involving au-tonomous cars crossing an intersection.The utility of JPF infinding logic and timing errors in each is illustrated.6.1Multiprogramming Operating SystemThis example models a simple multiprogramming computer system,where jobs (as RealtimeThread’s)contend for a CPU,which is a resource of one of thefive types discussed in§5.Of these,preemption is the most interesting,because (i)it guarantees absence of priority inversion,(ii)it is pervasive in modern operating systems,(iii)its behavior on realistic job mixes defies static analysis, and consequently(iv)real time OS’s typically do not employ it,despite the appeal of(i).Afixed job mix was analyzed using our RTSJ implementation in JFP,using CPU’s of each of ourfive resource types.The results are given in Fig.2.In450G.Lindstrom,P.C.Mehlitz,and W.VisserCPU Job1(6)Job2(5)Job3(4)Job4(3)Time FIFO3681/72%/6.03780/73%/5.03879/74%/4.03979/74%/3.03979 Priority1891/46%/6.01990/49%/5.03880/74%/4.03979/74%/3.03979 PC(6)1891/46%/6.01990/49%/5.23880/74%/4.53979/74%/3.73979 PI1891/46%/6.01990/49%/5.23880/74%/4.03979/74%/3.23979 Preempt1004/0%/6.02008/49%/5.03012/66%/4.04015/74%/3.04015 Fig.2.Multiprogramming results,by resource type.The parenthesized number in for each job indicates its priority.Columns for each job indicate its duration in simulated milliseconds,followed by its percentage wait time and average priority.Time is the completion time of the entire job mix,in simulated milliseconds.this scenario,there are four jobs that are identical in behavior(10compute/ wait cycles),with identical wait times between cycles.They are all started at time zero.This simple stress test keeps the CPU99%busy independent of its resource type(the simulation ends after the last job terminates).The following observations can be made of the results in Fig.2:–The FIFO CPU gives the most fair service to the four jobs–because it ignores priority.–The Priority,Priority Ceiling,and Priority Inheritance CPUs deliver identi-cal service,because the priority of a job only affects its competitive position when more than one job is waiting for the CPU,which does not occur in this simple scenario(an example of priority improving service is given in§6.2).–Jobs under the Preemptable CPUfinish strictly according to priority.How-ever,the overall completion time is slightly longer,due to the additional scheduling overhead.When run under JPF with nondeterminism turned on,there are4!=24 choices for activation order at time zero for the four jobs(the statistically rare case of events scheduled at exactly the same time does not occur after simulation start).Priority inversion was detected in all24paths under FIFO and Priority CPUs,and on no paths under Priority Ceiling(6),Priority Inheritance,and Preemptable CPUs.6.2Intersection CrossingThe example in§6.1emphasizes the effect of role of resource types in thread scheduling.Our second application is a more complex example,illustrating more advanced features of our RTSJ implementation in JPF.This models autonomous cars transiting an intersection,where the cars(real time threads)can drive straight through,turn right,or turn left.Cars are given priorities chosen from 1to8.The intersection is modeled by four sectors(NW,NE,SW,SE),each of which is a resource.For a car driving north,turning right requires possessionModel Checking Real Time Java Using Java PathFinder451 Sector type Car0(5/N/S)Car1(2/S/L)Car2(8/E/L)FIFO33/0%183/18%49/21%Priority33/0%183/18%49/21%PC(8)25/0%63/40%45/15%PI30/0%180/16%46/17%Fig.3.Intersection results using four sector resource types.(5/N/S)indicates that Car0has priority5,is heading north,and going straight,etc.Car0and Car1start at time0;Car2has a start delay of5seconds.Thefigures in each column are completiontime in seconds,and percentage wait time.of sector SE;driving straight requires SE and NE(granted simultaneously,toavoid deadlock;SE is released half way through),and turning left involves(i)seizing SE and NE together;(ii)releasing SE,(iii)seizing NW,(iv)releasing NE and NW.The net effect is a model of an uncontrolled intersection of two laneroads,where cars follow the common conventions that a car can drive straightthrough if the car on its left(if any)is not driving straight through or turning left,the car on its right(if any)is not driving either straight,left or right,andthe opposing car(if any)is not turning left.These rules are complex but deadlock free,which as been confirmed(for specific scenarios)by exhaustive search using JPF on initial event schedulingorders.By comparison,deadlocks caused by the naive policy of seizing all of SE, NE,and NW for a northbound car making a left turn(and correspondingly forcars heading in other directions)were quickly located by JPF.Car speed is governed by car priority,in the following manner.The time required by a car to transit a sector is t=100sec/p,where p is the car’spriority.At the extremes,p=1yields a sector transit time of100seconds,and p=8yields12.5seconds.Experiments were run using four resource types for sectors:FIFO,priority,priority ceiling8,and priority inheritance.There areready intuitions for each of these cases:FIFO is round robin,priority is fastestvehiclefirst,priority ceiling is a minimum sector speed,and priority inheritance is when one sees an ambulance rapidly approaching,and speeds up accordingly. The preemption case is physically impossible!Sample results are shown in Fig.3.Note that all cars benefit from higherpriority under priority ceiling,and marginally so under priority inheritance.The utility of run time cost logging under JPF was demonstrated by giving each car a maximum lifetime(its release deadline in RTSJ’s vocabulary).If the deadline is set uniformly at75seconds,under priority inheritance the RTSJ miss handler for Car1is invoked,but not for Cars0or Car2.The above analysis can be accomplished under both native Java and JPF,since it is based solely on simulated time.By contrast,analysis of miss handlerbehavior in RTSJ programs can only be exercised under JPF,where a listener method in our control program records each byte code execution in the subject program.To demonstrate this capability,an onboard computer was postulated for each car(its autonomous controller),and a cycle soaker method was invoked452G.Lindstrom,P.C.Mehlitz,and W.Visserduring passage through each sector(arbitrarily set at100,000double divides, with100nanosecond cost per byte code;a total of1,400,024DDIV’s are ob-served in the deterministic case).If a cost limit of350milliseconds is imposed, under priority inheritance Car0terminates without handler invocation,Car2 terminates with cost overrun handler invocation,and Car1terminates with both handlers invoked.7Critique of JPFThis application breaks new ground for Java PathFinder in its focus on quan-tified time as a program correctness issue.Much as been learned about itsflex-ibility in supporting this new and unanticipated correctness dimension,as well as the limits of our approach that implements RTSJ without making any modi-fications to JPF.7.1Features Not Easily Implemented Under This ApproachIn§4we indicated two areas pose more difficult challenges,which we believe can only be implemented by JVM modification:–ScopedMemoryArea’s and NoHeapRealtimeThread’s,which deal with non garbage collected MemoryArea’s,and–Asynchronous transfers of control(ATC),e.g.,threads that implement the Interruptible interface and methods that throw AsynchronouslyInterruptedEx-ception.While it may be possible in principle to implement at least thefirst these features using per-bytecode analysis in a JPF listener method,the overhead of this approach is likely to be prohibitive.7.2Opportunities for Application of Other JPF FeaturesThis project thus far has used only basic Java PathFinder features.Several advanced features of JPF offer attractive opportunities for increased utility in verifying RTSJ programs.Heuristic search:The default program path exploration strategy is depth first search,using backtracking.Other strategies,such as bounded breadth-first search,can selectively search longer paths due to elimination of the backtrack stack[GV04].Several criteria for preferring paths in RTSJ programs with higher error potential are evident,such as favoring states with threads whose extrapo-lated completion time is beyond their stipulated deadlines.State abstraction:By default JPF saves all previously encountered program states and performs precise equality checks to detect re-encountered states.This policy has several consequences,including(i)significant space overhead,and(ii) inability to recognize states that insignificantly vary from previously seen states.Model Checking Real Time Java Using Java PathFinder453 In particular,the extremelyfine representation of time in RTSJ(to nanosec-ond precision),exacerbates(ii).To illustrate,consider state abstraction meth-ods focusing on the core data structure of our system,the scheduled event list. Opportunities for abstraction here include fuzz on scheduled event times,e.g., equality to resolution of say100nanoseconds,or even ignoring event times al-together,and considering two event lists to be equal if they reference the same real time threads positioned at the same execution point(say,method and byte code address).Symbolic execution:JPF interfaces to a constraint system that can solve equations involving linear inequalities[SKV03].This presents the possibility of asserting constraints on scheduled event times.–For example,it could be asserted that event e1should run at time t0+t(e2), where t(e)is the scheduled time of an event e,and t(e2)is not yet known,i.e.,is symbolic.When t(e2)becomes bound,e1would be scheduled at aconcrete time.–Now suppose two scheduled events e1and e2have symbolic event times t(e1) and t(e2),and the event list is otherwise empty.We then have two options to pursue nondeterministically:(a)e1runs next,t(e1)≤t(e2)is asserted,and the simulation clock is set(symbolically)to t(e1),or(b)symmetrically,e2 runs next,t(e2)≤t(e1)is asserted,and the simulation clock is set to t(e2).Fault driven automatic test case generation:The execution driven symbolic constraint refinement technique just sketched can be the basis forfinding neces-sary and sufficient conditions that lead to specific faults[VPK04].For example, suppose the real time code is modeling the performance of an aircraft pre-landing checklist.There have been published accident scenarios where a mandatory air-craft response,e.g.,completion of landing gear deployment,did not occur in time to ensure the safety of the next step in the checklist,and the pilot under time pressure(the ground is approaching)inappropriately proceeded[Deg04].Condi-tions revealing suchflaws in real time checklist procedures might be determined by symbolic execution in this manner.8PerformanceWe now present performancefigures for our RTSJ profile implementation in JPF.All performancefigures are taken from executions in the Eclipse Java IDE with a heap size of one gigabyte on a Pentium2laptop with768MB of RAM.Our system can be run infive modes:native Java with deterministic or pseudo random choice selection,or JPF with deterministic,pseudo random,or nondeterministic choice selection.We have tested our system in allfive modes on the applications presented in§6.Run timefigures for the multiprocessing operating system example in§6.1under deterministic mode are120ms for native Java vs.6,257ms under JPF(the pseudo random mode numbers are analogous). These absolute numbers are not important;instead,their relative magnitudes are more informative.Two observations emerge:(a)the native Java implementation454G.Lindstrom,P.C.Mehlitz,and W.Visseris quite fast,and(b)the JPF implementation is slower by a factor of about50–but it must be remembered that under JPF an interpretive JVM(written in Java)is being employed,cost logging presents a linear execution time overhead, and state saving is performed to support exploration of alternative execution paths(not exploited in the deterministic and pseudo random cases).CPU type Run timeFIFO79.4secPriority80.9secPC(6)91.6secPI99.6secPreemptable106.2secFig.4.Run times for the multiprogramming example under JPF nondeterministic search(backtracking over24paths)To illustrate the cost of JPF state exploration,the CPU example was run under nondeterminism,exploring the4!=24choices for activation order at time zero for the four jobs discussed in§6.1Results are shown in Fig.4.9Related WorkModel checking of timed automata representations has become very popular ([BLR05];see[BY04]for a good overview)for the analysis of real time systems. Our approach differs in that we are analyzing systems with complex transitions but simple explicit timing information,whereas in the timed automata approach is typically applied to analyze systems with complex timing,but simple tran-sitions(e.g.,between abstract states in given time intervals).By contrast we are performing genuine program execution(not abstracted,or symbolic).The notion of applying timed automata style reasoning is appealing,but represents a major new line of research,due to the complex transitions in our program executions,e.g.memory allocation,exception handling,etc.).Our emphasis at present is checking program safety properties including scheduling errors such as priority inversion,as well as classic Java errors such as uncaught exceptions and assertion violations.It has been reported that more than3000people have used the RTSJ refer-ence implementation or a commercial RTSJ-compliant JVM to create applica-tion prototypes[Loc04].Tools are available to benchmark RTSJ implementations [CS02].Model checking is a vigorously evolving research area.Bandera[Ban],Bogor [DHHR05],and the work of Bart Jacobs et al.on JavaCard verification[JMR04] are examples of model checking applied to Java programs.A closely related area is run time verification of Java systems[KKLS01].Capability for dealing。

相关文档
最新文档