分布式系统概念与设计(第三版)课后习题与答案Chapter5
计算机操作系统(第三版)完整课后习题答案
第一章1.设计现代OS的主要目标是什么?答:(1)有效性(2)方便性(3)可扩充性(4)开放性2.OS的作用可表现在哪几个方面?答:(1)OS作为用户与计算机硬件系统之间的接口(2)OS作为计算机系统资源的管理者(3)OS实现了对计算机资源的抽象3.为什么说OS实现了对计算机资源的抽象?答:OS首先在裸机上覆盖一层I/O设备管理软件,实现了对计算机硬件操作的第一层次抽象;在第一层软件上再覆盖文件管理软件,实现了对硬件资源操作的第二层次抽象。
OS 通过在计算机硬件上安装多层系统软件,增强了系统功能,隐藏了对硬件操作的细节,由它们共同实现了对计算机资源的抽象。
4.试说明推劢多道批处理系统形成和収展的主要劢力是什么?答:主要动力来源于四个方面的社会需求与技术发展:(1)不断提高计算机资源的利用率;(2)方便用户;(3)器件的不断更新换代;(4)计算机体系结构的不断发展。
5.何谓脱机I/O和联机I/O?答:脱机I/O 是指事先将装有用户程序和数据的纸带或卡片装入纸带输入机或卡片机,在外围机的控制下,把纸带或卡片上的数据或程序输入到磁带上。
该方式下的输入输出由外围机控制完成,是在脱离主机的情况下进行的。
而联机I/O方式是指程序和数据的输入输出都是在主机的直接控制下进行的。
6.试说明推劢分时系统形成和収展的主要劢力是什么?答:推动分时系统形成和发展的主要动力是更好地满足用户的需要。
主要表现在:CPU 的分时使用缩短了作业的平均周转时间;人机交互能力使用户能直接控制自己的作业;主机的共享使多用户能同时使用同一台计算机,独立地处理自己的作业。
7.实现分时系统的关键问题是什么?应如何解决?答:关键问题是当用户在自己的终端上键入命令时,系统应能及时接收并及时处理该命令,在用户能接受的时延内将结果返回给用户。
解决方法:针对及时接收问题,可以在系统中设臵多路卡,使主机能同时接收用户从各个终端上输入的数据;为每个终端配臵缓冲区,暂存用户键入的命令或数据。
分布式数据库参考资料参考答案
1、何为分布式数据库系统?一个分布式数据库系统有哪些特点?P4答案:分布式数据库系统通俗地说,是物理上分散而逻辑上集中的数据库系统。
分布式数据库系统使用计算机网络将地理位置分散而管理和控制又需要不同程度集中的多个逻辑单位连接起来,共同组成一个统一的数据库系统。
因此,分布式数据库系统可以看成是计算机网络与数据库系统的有机结合。
一个分布式数据库系统具有如下特点:物理分布性,即分布式数据库系统中的数据不是存储在一个站点上,而是分散存储在由计算机网络连接起来的多个站点上,而且这种分散存储对用户来说是感觉不到的。
逻辑整体性,分布式数据库系统中的数据物理上是分散在各个站点中,但这些分散的数据逻辑上却构成一个整体,它们被分布式数据库系统的所有用户共享,并由一个分布式数据库管理系统统一管理,它使得“分布”对用户来说是透明的。
站点自治性,也称为场地自治性,各站点上的数据由本地的DBMS管理,具有自治处理能力,完成本站点的应用,这是分布式数据库系统与多处理机系统的区别。
另外,由以上三个分布式数据库系统的基本特点还可以导出它的其它特点,即:数据分布透明性、集中与自治相结合的控制机制、存在适当的数据冗余度、事务管理的分布性。
2、简述分布式数据库系统的模式结构和各层模式的概念。
P12-P13分布式数据库是多层的,国内分为四层:全局外层:全局外模式,是全局应用的用户视图,所以也称全局试图。
它为全局概念模式的子集,表示全局应用所涉及的数据库部分。
全局概念层:全局概念模式、分片模式和分配模式全局概念模式描述分布式数据库中全局数据的逻辑结构和数据特性,与集中式数据库中的概念模式是集中式数据库的概念视图一样,全局概念模式是分布式数据库的全局概念视图。
分片模式用于说明如何放置数据库的分片部分。
分布式数据库可划分为许多逻辑片,定义片段、片段与概念模式之间的映射关系。
分配模式是根据选定的数据分布策略,定义各片段的物理存放站点。
局部概念层:局部概念模式是全局概念模式的子集。
计算机操作系统教程第三版答案
第一章操作系统概述课后习题. 硬件将处理机划分为两种状态,即管态和目态,这样做给操作系统设计带来什么好处答:便于设计平安可靠的操作系统。
管态和目态是计算机硬件为保护操作系统免受用户程序的干扰和破坏而引入的两种状态。
通常操作系统在管态下运行,可以执行所有机器指令;而用户程序在目态下运行,只能执行非特权指令。
如果用户程序企图在目态下执行特权指令,将会引起保护性中断,由操作系统终止该程序的执行,从而保护了操作系统。
. 何为特权指令举例说明之。
如果允许用户执行特权指令,会带来什么后果?答:只能在管态下才能执行的指令称为特权指令。
如开关中断、置程序状态存放器等。
如果允许用户执行特权指令,它将不仅影响当前运行的程序,而且还有可能影响操作系统的正常运行,甚至整个系统。
. 中断向量在机器中的存储位置是由硬件确定的,还是由软件确定的答:中断向量在机器中的位置是由硬件确定的。
例如,在中,内存空间——为中断向量空间。
. 中断向量的内容是由操作系统程序确定的还是由用户程序确定的?答:中断向量的内容是由操作系统程序确定的。
向量的内容包括中断处理程序的入口地址和程序状态字〔中断处理程序运行环境〕,中断处理程序是由操作系统装入内存的,操作系统将根据装入的实际地址和该中断处理程序的运行环境来填写中断向量。
. 中断向量内的处理机状态位应当标明是管态还是目态为什么答:应当标明是管态。
该状态由系统初试化程序设置,这样才能保证中断发生后进入操作系统规定的中断处理程序。
. 中断和程序并发之间的关系是什么?答:中断是程序并发的必要条件。
如果没有中断,操作系统不能获得系统控制权,无法按调度算法对处机进展重新分配,一个程序将一直运行到完毕而不会被打断。
. 说明“栈〞和“堆〞的差异.答:栈是一块按后进先出〔〕规则访问的存储区域,用来实现中断嵌套和子程序调用的参数和返回断点。
而堆虽然是一块存储区域,但是对堆的访问是任意的,没有后进先出的要求,堆主要用来为动态变量分配存储空间。
分布式课后习题答案
分布式课后习题答案第⼀章分布式数据库系统概述1.1请⽤⾃⼰的语⾔定义下列分布式数据库系统中的术语:(1)局部数据:只提供本站点的局部应⽤所需要的数据。
全局数据:虽然物理上存储在个站点上,但是参与全局应⽤(2)全局/局部⽤户:局部⽤户:⼀个⽤户或⼀个应⽤如果只访问他注册的那个站点上的数据称为本地或局部⽤户或本地应⽤;全局⽤户:如果访问涉及两个或两个以上的站点中的数据,称为全局⽤户或全局应⽤。
全局/局部DBMS:1)LDBMS(Local DBMS):局部场地上的数据库管理系统,其功能是建⽴和管理局部数据库,提供场地⾃治能⼒,执⾏局部应⽤及全局查询的⼦查询。
(2)GDBMS(Global DBMS):全局数据库管理系统,主要功能是提供分布透明性,协调全局事物的执⾏,协调各局部DBMS 以完成全局应⽤,保证数据库的全局⼀致性,执⾏并发控制,实现更新同步,提供全局恢复功能等。
(3)全局外模式:全局应⽤的⽤户视图,也称全局视图。
从⼀个由各局部数据库组成的逻辑集合中抽取,即全局外模式是全局概念式的⼦集。
对全局⽤户⽽⾔,都可以认为在整个分布式数据库系统的各个站点上的所有数据库都如同在本站点上⼀样,只关⼼他们⾃⼰所使⽤的那部分数据(4)全局概念模式:描述分布式数据库中全局数据的逻辑结构和数据特性,是分布式数据库的全局概念视图。
采⽤关系模型的全局概念模式由⼀组全局关系的定义(如关系名、关系中的属性、每⼀属性的数据类型和长度等)和完整性定义(关系的主键、外键及完整性其他约束条件等)组成。
(5)分⽚模式:描述全局数据的逻辑划分。
每个全局关系可以通过选择和投影的关系操作被逻辑划分为若⼲⽚段。
分⽚模式描述数据分⽚或定义⽚段,以及全局关系与⽚段之间的映像。
这种映像是⼀对多的。
(6)分配模式:根据选定的数据分布策略,定义各⽚段的物理存放站点,即定义⽚段映像的类型,确定分布式数据库是冗余的还是⾮冗余的,以及冗余的程度。
如果⼀个⽚段分配在多个站点上,则⽚段的映像是⼀对多的,分布式数据库是冗余的,否则是不冗余的。
操作系统教程课后习题答案
操作系统1.什么是计算机系统?计算机系统是怎么构成的?了解PC的组成情况,说明:1)硬件组织的基本结构,画出硬件配置图;2)主要系统软件和应用软件(若有的话)他们的作用。
答:计算机系统就是按照人的要求接收和存储信息,自动进行数据处理和计算,并输出结果信息的系统。
计算机系统由硬件子系统和软件子系统组成。
计算机系统的构成包括:如图1.2计算机硬件系统的构成:如图1.42.从功能以及程序涉设计的角度说明计算机系统中软件系统是如何构成的?答:分为系统软件,支撑软件和应用软件三层。
3.什么是操作系统?请举例说明操作系统在计算机系统中的重要地位。
答:操作系统是计算机系统中的一个系统软件,是一些程序模块的集合。
它们能以尽量有效、合理的方式组织和管理计算机的软硬件资源,合理的组织计算机的工作流程,控制程序的执行并向用户提供各种服务功能,使得用户能够灵活、方便、有效的使用计算机,使整个计算机系统能安全高效地运行4.请举一个实际的例子来说明操作系统的功能。
答:你能用用操作系统管理很多资源5.为什么说“操作系统是控制硬件的软件”的说法不确切?答:操作系统不仅能够控制硬件,也可以控制各种软件资源。
6.操作系统的基本特征是什么?说明他们之间的关系。
答:1.并发性2.共享性3.随机性7.试从独立性,并发性和交互性和实时性四个方面来比较批处理系统,分时系统以及实时系统。
答:分时系统:并发性是指同时有多个用户共同使用一个计算机,宏观上看是多个人同时使用一个CPU,微观上是多个人在不同时刻轮流使用CPU.独占性,是指用户感觉不到计算机为他们服务,就好像整个系统为他所独占。
交互性:是指用户根据系统响应结果进一步提出新要求,用户直接干预每一步。
实时性:是指系统对用户提出的请求及时响应。
8.引入多道程序设计技术的起因和目的是什么?多道程序系统的特征是什么?答:多道程序设计的基本思想在内存中保持多个作业,主机可以交替的方式同时处理多个作业,一般来说任何一道作业的运行总是要交替的使用处理器和外设子案9.多道程序设计的度是指在任一给定时刻,单个CPU所能支持的进程数目最大值。
分布式课后习题答案
第一章分布式数据库系统概述请用自己的语言定义下列分布式数据库系统中的术语:(1)全局/局部数据:(详见课本第9页所谓的局部数据是指……;所谓的全局数据是指……)(2)全局/局部用户(应用):(3)全局/局部DBMS:(4)全局/局部DB:(5)全局外模式:(详见课本第13页)由全局用户视图组成,是全局概念模式的子集。
(6)全局概念模式:(详见课本第13页)定义分布式数据库系统中所有数据的整体逻辑结构,是全局应用的公共数据视图。
(7)分片模式:(详见课本第13页)是全局数据整体逻辑结构分割后的局部逻辑结构,是DDBS 的全局数据的逻辑划分视图.(8)分配模式:(详见课本第13页)用于根据选定的数据总体分配方案,定义各片段的物理存放地点.(9)局部概念模式:(详见课本第13-14页)是全局概念模式被分片和分配到局部场地上的映像的逻辑结构及特征的描述,是全局概念模式的子集。
其逻辑结构与局部DBMS所支持的数据模型有关,当全局数据模型与局部数据模型不同时,局部概念模式还应包括数据模型转换的描述。
(10)局部内模式:描述局部概念模式涉及的数据在局部DBMS中的物理结构及物理存储细节,完全与非分布式系统相同。
1.2采用分布式数据库系统的主要原因是什么?(P1)1.3分布式数据库系统可分为哪些类?(课件第1章。
课本P6,7,8)1.4什么是分布式数据库系统?它具有哪些主要特点?怎么样区别分布式数据库系统与只提供远程数据访问功能的网络数据库系统?(分布式数据库系统的定义、特点详见课件第1.课本P6)1.5分布式DBMS具有哪些集中式DBMS不具备的功能?(课件第1章。
课本P15)用自己的语言解析“什么时候需要进行数据分片和数据复制”?(课本第10,11页)式数据库系统中,为什么要对数据进行分片?什么是关系的片段?关系的片段有哪些主要类型?(课本第9-10页。
数据分片是指数据存放单位不是全部关系,而是关系的一个片段。
分布式系统原理与范型课后习题答案
分布式系统原理与范型课后习题答案专业专心专注第一章绪论1、中间件在分布式系统中扮演什么角色,答:中间件主要是为了增强分布式系统的透明性(这正是网络操作系统所缺乏的),换言之,中间件的目标是分布式系统的单系统视图。
2、解释(分布)透明性的含义,并且给出各种类型透明性的例子。
答:分布透明性是一种现象,即一个系统的分布情况对于用户和应用来说是隐藏的。
包括:访问透明、位置透明、移植透明、重定位透明、复制透明、并发透明、故障透明和持久性透明。
3、在分布式系统中,为什么有时难以隐藏故障的发生以及故障恢复过程,答:通常,要探测一个服务器是停止服务还是该服务器的反应变慢这些情况是不可能的。
因此,一个系统可能在服务响应变慢的时候报告该服务已经停止了。
4、为什么有时候要求最大程度地实现透明性并不好,答:最大程度地实现透明性可能导致相当大的性能损失,从而导致用户无法接受。
5、什么是开放的分布式系统,开放性带来哪些好处,答:开放的分布式系统根据明确定义的规则来提供服务。
开放系统能够很容易地与其它系统协作,同时也允许应用移植到同一个系统的不同实现中。
6、请对可扩展系统的含义做出准确描述答:一个系统的可扩展包含下面几个方面:组件的数量、几何尺寸、管理域的数量与尺寸,前提是这个系统可以在上面几个方面进行增加而不会导致不可接受的性能损失。
7、可以通过应用多种技术来取得可扩展性。
请说出这些技术。
答:可扩展性可以通过分布式、复制和缓存来获得。
8、多处理器系统与多计算机系统有什么不同,答:在多处理器系统中,多个CPU访问共享的主存储器。
在多计算机系统中没有共享存储器,CPU之间只能通过消息传递来进行通信。
9、在多计算机系统中的256个CPU组成了一个16 X 16的网格方阵。
在最坏的情况下,消息的延迟时间有多长(以跳(hop)的形式给出,跳是结点之间的逻辑距离),答:假设路由是最优的,最长的路由是从网格方阵的一个角落到对角的角落。
那么这个路由的长度是30跳。
分布式数据库系统部分课后题答案
分布式数据库系统部分课后习题答案
ASG9 ENO E2 PNO P2 RESP Analyst DUR 6
ASG10 ENO E2 PNO P1 RESP Analyst DUR 24
5.3 EMP TITLE PAY 的连接图如下: PAY1 TITLE SAL PAY2 TITLE SAL
EMP1
ENO ENAME TITLE
EMP2
ENO ENAME TITLE
EMP3
ENO ENAME TITLE
EMP4
ENO ENAME TITLE
这个图显然不是一个简单图。 我们可以通过将 PAY 关系根据 EMP 关系的分片进行诱导分片,即 PAY1 = PAY EMP1; PAY2 = PAY EMP2; PAY3 = PAY EMP3; PAY4 = PAY EMP4; 或 将 EMP 关系根据 PAY 关系的分片进行诱导分片(推荐此方案) ,即 EMP1 = EMP PAY1; EMP2 = EMP PAY2;
分布式系统原理与范型 课后答案
DISTRIBUTED SYSTEMS PRINCIPLES AND PARADIGMS PROBLEM SOLUTIONS ANDREW S.TANENBAUM MAARTEN VAN STEEN Vrije Universiteit Amsterdam,The Netherlands PRENTICE HALL UPPER SADDLE RIVER,NJ 07458w w w .k h d a w .c o m 课后答案网SOLUTIONS TO CHAPTER 1PROBLEMS1.Q:What is the role of middleware in a distributed system?A:To enhance the distribution transparency that is missing in network operat-ing systems.In other words,middleware aims at improving the single-system view that a distributed system should have.2.Q:Explain what is meant by (distribution)transparency,and give examples of different types of transparency.A:Distribution transparency is the phenomenon by which distribution aspects in a system are hidden from users and applications.Examples include access transparency,location transparency,migration transparency,relocation tran-sparency,replication transparency,concurrency transparency,failure tran-sparency,and persistence transparency.3.Q:Why is it sometimes so hard to hide the occurrence and recovery from failures in a distributed system?A:It is generally impossible to detect whether a server is actually down,or that it is simply slow in responding.Consequently,a system may have to report that a service is not available,although,in fact,the server is just slow.4.Q:Why is it not always a good idea to aim at implementing the highest degree of transparency possible?A:Aiming at the highest degree of transparency may lead to a considerable loss of performance that users are not willing to accept.5.Q:What is an open distributed system and what benefits does openness pro-vide?A:An open distributed system offers services according to clearly defined rules.An open system is capable of easily interoperating with other open sys-tems but also allows applications to be easily ported between different imple-mentations of the same system.6.Q:Describe precisely what is meant by a scalable system.A:A system is scalable with respect to either its number of components,geo-graphical size,or number and size of administrative domains,if it can grow in one or more of these dimensions without an unacceptable loss of perfor-mance.7.Q:Scalability can be achieved by applying different techniques.What arethese techniques?A:Scaling can be achieved through distribution,replication,and caching.w w w .k h d a w .c o m 课后答案网2PROBLEM SOLUTIONS FOR CHAPTER 18.Q:What is the difference between a multiprocessor and a multicomputer?A:In a multiprocessor,the CPUs have access to a shared main memory.There is no shared memory in multicomputer systems.In a multicomputer system,the CPUs can communicate only through message passing.9.Q:A multicomputer with 256CPUs is organized as a 16×16grid.What is the worst-case delay (in hops)that a message might have to take?A:Assuming that routing is optimal,the longest optimal route is from one corner of the grid to the opposite corner.The length of this route is 30hops.If the end processors in a single row or column are connected to each other,the length becomes 15.10.Q:Now consider a 256-CPU hypercube.What is the worst-case delay here,again in hops?A:With a 256-CPU hypercube,each node has a binary address,from 00000000to 11111111.A hop from one machine to another always involves changing a single bit in the address.Thus from 00000000to 00000001is one hop.From there to 00000011is another hop.In all,eight hops are needed.11.Q:What is the difference between a distributed operating system and a net-work operating system?A:A distributed operating system manages multiprocessors and homogene-ous multicomputers.A network operating system connects different indepen-dent computers that each have their own operating system so that users can easily use the services available on each computer.12.Q:Explain how microkernels can be used to organize an operating system in a client-server fashion.A:A microkernel can separate client applications from operating system ser-vices by enforcing each request to pass through the kernel.As a consequence,operating system services can be implemented by (perhaps different)user-level servers that run as ordinary processes.If the microkernel has networking capabilities,there is also no principal objection in placing those servers on remote machines (which run the same microkernel).13.Q:Explain the principal operation of a page-based distributed shared memory system.A:Page-based DSM makes use of the virtual memory capabilities of an operating system.Whenever an application addresses a memory location thatis currently not mapped into the current physical memory,a page fault occurs,giving the operating system control.The operating system can then locate the referred page,transfer its content over the network,and map it to physical memory.At that point,the application can continue.w w w .k h d a w .c o m 课后答案网PROBLEM SOLUTIONS FOR CHAPTER 1314.Q:What is the reason for developing distributed shared memory systems?What do you see as the main problem hindering ef ficient implementations?A:The main reason is that writing parallel and distributed programs based on message-passing primitives is much harder than being able to use shared memory for communication.Ef ficiency of DSM systems is hindered by the fact,no matter what you do,page transfers across the network need to take place.If pages are shared by different processors,it is quite easy to get into a state similar to thrashing in virtual memory systems.In the end,DSM sys-tems can never be faster than message-passing solutions,and will generally be slower due to the overhead incurred by keeping track of where pages are.15.Q:Explain what false sharing is in distributed shared memory systems.What possible solutions do you see?A:False sharing happens when data belonging to two different and indepen-dent processes (possibly on different machines)are mapped onto the same logical page.The effect is that the page is swapped between the two processes,leading to an implicit and unnecessary dependency.Solutions include making pages smaller or prohibiting independent processes to share a page.16.Q:An experimental file server is up 3/4of the time and down 1/4of the time,due to bugs.How many times does this file server have to be replicated to give an availability of at least 99%?A:With k being the number of servers,we have that (1/4)k <0.01,expressing that the worst situation,when all servers are down,should happen at most 1/100of the time.This gives us k =4.17.Q:What is a three-tiered client-server architecture?A:A three-tiered client-server architecture consists of three logical layers,where each layer is,in principle,implemented at a separate machine.The highest layer consists of a client user interface,the middle layer contains the actual application,and the lowest layer implements the data that are being used.18.Q:What is the difference between a vertical distribution and a horizontal dis-tribution?A:Vertical distribution refers to the distribution of the different layers in a multitiered architectures across multiple machines.In principle,each layer is implemented on a different machine.Horizontal distribution deals with the distribution of a single layer across multiple machines,such as distributing asingle database.19.Q:Consider a chain of processes P 1,P 2,...,P n implementing a multitieredclient-server architecture.Process P i is client of process P i +1,and P i will return a reply to P i −1only after receiving a reply from P i +1.What are the w w w .k h d a w .c o m 课后答案网4PROBLEM SOLUTIONS FOR CHAPTER 1main problems with this organization when taking a look at the request-reply performance at process P 1?A:Performance can be expected to be bad for large n .The problem is that each communication between two successive layers is,in principle,between two different machines.Consequently,the performance between P 1and P 2may also be determined by n −2request-reply interactions between the other layers.Another problem is that if one machine in the chain performs badly or is even temporarily unreachable,then this will immediately degrade the per-formance at the highest level.w w w .k h d a w .c o m 课后答案网5SOLUTIONS TO CHAPTER 2PROBLEMS1.Q:In many layered protocols,each layer has its own header.Surely it would be more ef ficient to have a single header at the front of each message with all the control in it than all these separate headers.Why is this not done?A:Each layer must be independent of the other ones.The data passed from layer k +1down to layer k contains both header and data,but layer k cannot tell which is which.Having a single big header that all the layers could read and write would destroy this transparency and make changes in the protocol of one layer visible to other layers.This is undesirable.2.Q:Why are transport-level communication services often inappropriate for building distributed applications?A:They hardly offer distribution transparency meaning that application developers are required to pay signi ficant attention to implementing commun-ication,often leading to proprietary solutions.The effect is that distributed applications,for example,built directly on top of sockets are dif ficult to port and to interoperate with other applications.3.Q:A reliable multicast service allows a sender to reliably pass messages to a collection of receivers.Does such a service belong to a middleware layer,or should it be part of a lower-level layer?A:In principle,a reliable multicast service could easily be part of the trans-port layer,or even the network layer.As an example,the unreliable IP multi-casting service is implemented in the network layer.However,because such services are currently not readily available,they are generally implemented using transport-level services,which automatically places them in the middleware.However,when taking scalability into account,it turns out that reliability can be guaranteed only if application requirements are considered.This is a strong argument for implementing such services at higher,less gen-eral layers.4.Q:Consider a procedure incr with two integer parameters.The procedure adds one to each parameter.Now suppose that it is called with the same vari-able twice,for example,as incr (i ,i ).If i is initially 0,what value will it have afterward if call-by-reference is used?How about if copy/restore is used?A:If call by reference is used,a pointer to i is passed to incr .It will be incre-mented two times,so the final result will be two.However,with copy/restore,i will be passed by value twice,each value initially 0.Both will be incre-mented,so both will now be 1.Now both will be copied back,with the second copy overwriting the first one.The final value will be 1,not 2.w w w .k h d a w .c o m 课后答案网6PROBLEM SOLUTIONS FOR CHAPTER 25.Q:C has a construction called a union,in which a field of a record (called a struct in C)can hold any one of several alternatives.At run time,there is no sure-fire way to tell which one is in there.Does this feature of C have any implications for remote procedure call?Explain your answer.A:If the runtime system cannot tell what type value is in the field,it cannot marshal it correctly.Thus unions cannot be tolerated in an RPC system unless there is a tag field that unambiguously tells what the variant field holds.The tag field must not be under user control.6.Q:One way to handle parameter conversion in RPC systems is to have each machine send parameters in its native representation,with the other one doing the translation,if need be.The native system could be indicated by a code in the first byte.However,since locating the first byte in the first word is pre-cisely the problem,can this actually work?A:First of all,when one computer sends byte 0,it always arrives in byte 0.Thus the destination computer can simply access byte 0(using a byte instruc-tion)and the code will be in it.It does not matter whether this is the low-order byte or the high-order byte.An alternative scheme is to put the code in all the bytes of the first word.Then no matter which byte is examined,the code will be there.7.Q:Assume a client calls an asynchronous RPC to a server,and subsequently waits until the server returns a result using another asynchronous RPC.Is this approach the same as letting the client execute a normal RPC?What if we replace the asynchronous RPCs with asynchronous RPCs?A:No,this is not the same.An asynchronous RPC returns an acknowledge-ment to the caller,meaning that after the first call by the client,an additional message is sent across the network.Likewise,the server is acknowledged that its response has been delivered to the client.Two asynchronous RPCs may be the same,provided reliable communication is guaranteed.This is generally not the case.8.Q:Instead of letting a server register itself with a daemon as is done in DCE,we could also choose to always assign it the same endpoint.That endpoint can then be used in references to objects in the server ’s address space.What is the main drawback of this scheme?A:The main drawback is that it becomes much harder to dynamically allo-cate objects to servers.In addition,many endpoints need to be fixed,instead of just one (i.e.,the one for the daemon).For machines possibly having alarge number of servers,static assignment of endpoints is not a good idea.9.Q:Give an example implementation of an object reference that allows a client to bind to a transient remote object.w w w .k h d a w .c o m 课后答案网PROBLEM SOLUTIONS FOR CHAPTER 27A:Using Java,we can express such an implementation as the following class:public class Object reference {InetAddress server address;//network address of object’s server int server endpoint;//endpoint to which server is listening int object identifier;//identifier for this object URL client code;//(remote)file containing client-side stub byte[]init data;//possible additional initialization data }The object reference should at least contain the transport-level address ofthe server where the object resides.We also need an object identi fier as the server may contain several objects.In our implementation,we use a URL to refer to a (remote)file containing all the necessary client-side code.A generic array of bytes is used to contain further initialization data for that code.An alternative implementation would have been to directly put the client-code into the reference instead of a URL.This approach is followed,for example,in Java RMI where proxies are passed as reference.10.Q:Java and other languages support exceptions,which are raised when an error occurs.How would you implement exceptions in RPCs and RMIs?A:Because exceptions are initially raised at the server side,the server stub can do nothing else but catch the exception and marshal it as a special error response back to the client.The client stub,on the other hand,will have to unmarshal the message and raise the same exception if it wants to keep access to the server transparent.Consequently,exceptions now also need to be described in an interface de finition language.11.Q:Would it be useful to also make a distinction between static and dynamic RPCs?A:Yes,for the same reason it is useful with remote object invocations:it simply introduces more flexibility.The drawback,however,is that much of the distribution transparency is lost for which RPCs were introduced in the first place.12.Q:Some implementations of distributed-object middleware systems are entirely based on dynamic method invocations.Even static invocations are compiled to dynamic ones.What is the bene fit of this approach?A:Realizing that an implementation of dynamic invocations can handle all invocations,static ones become just a special case.The advantage is that onlya single mechanism needs to be implemented.A possible disadvantage is that performance is not always as optimal as it could be had we analyzed the static invocation.w w w .k h d a w .c o m 课后答案网8PROBLEM SOLUTIONS FOR CHAPTER 213.Q:Describe how connectionless communication between a client and a server proceeds when using sockets.A:Both the client and the server create a socket,but only the server binds the socket to a local endpoint.The server can then subsequently do a blocking read call in which it waits for incoming data from any client.Likewise,after creating the socket,the client simply does a blocking call to write data to the server.There is no need to close a connection.14.Q:Explain the difference between the primitives mpi bsend and mpi isend in MPI.A:The primitive mpi bsend uses buffered communication by which the caller passes an entire buffer containing the messages to be sent,to the local MPI runtime system.When the call completes,the messages have either been transferred,or copied to a local buffer.In contrast,with mpi isend ,the caller passes only a pointer to the message to the local MPI runtime system after which it immediately continues.The caller is responsible for not overwriting the message that is pointed to until it has been copied or transferred.15.Q:Suppose you could make use of only transient asynchronous communica-tion primitives,including only an asynchronous receive primitive.How would you implement primitives for transient synchronous communication?A:Consider a synchronous send primitive.A simple implementation is to send a message to the server using asynchronous communication,and subse-quently let the caller continuously poll for an incoming acknowledgement or response from the server.If we assume that the local operating system stores incoming messages into a local buffer,then an alternative implementation is to block the caller until it receives a signal from the operating system that a message has arrived,after which the caller does an asynchronous receive.16.Q:Now suppose you could make use of only transient synchronous commun-ication primitives.How would you implement primitives for transient asyn-chronous communication?A:This situation is actually simpler.An asynchronous send is implemented by having a caller append its message to a buffer that is shared with a process that handles the actual message transfer.Each time a client appends a mes-sage to the buffer,it wakes up the send process,which subsequently removes the message from the buffer and sends it its destination using a blocking call to the original send primitive.The receiver is implemented similarly by offer-ing a buffer that can be checked for incoming messages by an application.17.Q:Does it make sense to implement persistent asynchronous communicationby means of RPCs?A:Yes,but only on a hop-to-hop basis in which a process managing a queue passes a message to a next queue manager by means of an RPC.Effectively,w w w .k h d a w .c o m 课后答案网PROBLEM SOLUTIONS FOR CHAPTER 29the service offered by a queue manager to another is the storage of a message.The calling queue manager is offered a proxy implementation of the interface to the remote queue,possibly receiving a status indicating the success or failure of each operation.In this way,even queue managers see only queues and no further communication.18.Q:In the text we stated that in order to automatically start a process to fetchmessages from an input queue,a daemon is often used that monitors the input queue.Give an alternative implementation that does not make use of a dae-mon.A:A simple scheme is to let a process on the receiver side check for any incoming messages each time that process puts a message in its own queue.19.Q:Routing tables in IBM MQSeries,and in many other message-queuing systems,are con figured manually.Describe a simple way to do this automati-cally.A:The simplest implementation is to have a centralized component in which the topology of the queuing network is maintained.That component simply calculates all best routes between pairs of queue managers using a known routing algorithm,and subsequently generates routing tables for each queue manager.These tables can be downloaded by each manager separately.This approach works in queuing networks where there are only relatively few,but possibly widely dispersed,queue managers.A more sophisticated approach is to decentralize the routing algorithm,by having each queue manager discover the network topology,and calculate its own best routes to other managers.Such solutions are widely applied in com-puter networks.There is no principle objection for applying them to message-queuing networks.20.Q:How would you incorporate persistent asynchronous communication into a model of communication based on RMIs to remote objects?A:An RMI should be asynchronous,that is,no immediate results are expected at invocation time.Moreover,an RMI should be stored at a special server that will forward it to the object as soon as the latter is up and running in an object server.21.Q:With persistent communication,a receiver generally has its own local buffer where messages can be stored when the receiver is not executing.To create such a buffer,we may need to specify its size.Give an argument why this is preferable,as well as one against speci fication of the size.A:Having the user specify the size makes its implementation easier.The sys-tem creates a buffer of the speci fied size and is done.Buffer management becomes easy.However,if the buffer fills up,messages may be lost.The alternative is to have the communication system manage buffer size,starting w w w .k h d a w .c o m 课后答案网10PROBLEM SOLUTIONS FOR CHAPTER 2with some default size,but then growing (or shrinking)buffers as need be.This method reduces the chance of having to discard messages for lack of room,but requires much more work of the system.22.Q:Explain why transient synchronous communication has inherent scalabil-ity problems,and how these could be solved.A:The problem is the limited geographical scalability.Because synchronous communication requires that the caller is blocked until its message is received,it may take a long time before a caller can continue when the receiver is far away.The only way to solve this problem is to design the cal-ling application so that it has other useful work to do while communication takes place,effectively establishing a form of asynchronous communication.23.Q:Give an example where multicasting is also useful for discrete datastreams.A:Passing a large file to many users as is the case,for example,when updat-ing mirror sites for Web services or software distributions.24.Q:How could you guarantee a maximum end-to-end delay when a collectionof computers is organized in a (logical or physical)ring?A:We let a token circulate the ring.Each computer is permitted to send data across the ring (in the same direction as the token)only when holding the token.Moreover,no computer is allowed to hold the token for more than T seconds.Effectively,if we assume that communication between two adjacent computers is bounded,then the token will have a maximum circulation time,which corresponds to a maximum end-to-end delay for each packet sent.25.Q:How could you guarantee a minimum end-to-end delay when a collection of computers is organized in a (logical or physical)ring?A:Strangely enough,this is much harder than guaranteeing a maximum delay.The problem is that the receiving computer should,in principle,not receive data before some elapsed time.The only solution is to buffer packets as long as necessary.Buffering can take place either at the sender,the receiver,or somewhere in between,for example,at intermediate stations.The best place to temporarily buffer data is at the receiver,because at that point there are no more unforeseen obstacles that may delay data delivery.The receiver need merely remove data from its buffer and pass it to the applica-tion using a simple timing mechanism.The drawback is that enough buffering capacity needs to be provided.26.Q:Imagine we have a token bucket speci fication where the maximum dataunit size is 1000bytes,the token bucket rate is 10million bytes/sec,the token bucket size is 1million bytes,and the maximum transmission rate is 50mil-lion bytes/sec.How long can a burst of maximum speed last?w w w .k h d a w .c o m 课后答案网PROBLEM SOLUTIONS FOR CHAPTER 211A:Call the length of the maximum burst interval ∆t .In an extreme case,the bucket is full at the start of the interval (1million bytes)and another 10∆t comes in during that interval.The output during the transmission burst con-sists of 50∆t million bytes,which should be equal to (1+10∆t ).Consequently,∆t is equal to 25msec.w w w .khda w.com课后答案网12SOLUTIONS TO CHAPTER 3PROBLEMS1.Q:In this problem you are to compare reading a file using a single-threaded file server and a multithreaded server.It takes 15msec to get a request for work,dispatch it,and do the rest of the necessary processing,assuming that the data needed are in a cache in main memory.If a disk operation is needed,as is the case one-third of the time,an additional 75msec is required,during which time the thread sleeps.How many requests/sec can the server handle if it is single threaded?If it is multithreaded?A:In the single-threaded case,the cache hits take 15msec and cache misses take 90msec.The weighted average is 2/3×15+1/3×90.Thus the mean request takes 40msec and the server can do 25per second.For a mul-tithreaded server,all the waiting for the disk is overlapped,so every request takes 15msec,and the server can handle 662/3requests per second.2.Q:Would it make sense to limit the number of threads in a server process?A:Yes,for two reasons.First,threads require memory for setting up their own private stack.Consequently,having many threads may consume too much memory for the server to work properly.Another,more serious reason,is that,to an operating system,independent threads tend to operate in a chaotic manner.In a virtual memory system it may be dif ficult to build a rela-tively stable working set,resulting in many page faults and thus I/O.Having many threads may thus lead to a performance degradation resulting from page thrashing.3.Q:In the text,we described a multithreaded file server,showing why it is better than a single-threaded server and a finite-state machine server.Are there any circumstances in which a single-threaded server might be better?Give an example.A:Yes.If the server is entirely CPU bound,there is no need to have multiple threads.It may just add unnecessary complexity.As an example,consider a telephone directory assistance number (like 555-1212)for an area with 1mil-lion people.If each (name,telephone number)record is,say,64characters,the entire database takes 64megabytes,and can easily be kept in the server ’s memory to provide fast lookup.4.Q:Statically associating only a single thread with a lightweight process is not such a good idea.Why not?A:Such an association effectively reduces to having only kernel-levelthreads,implying that much of the performance gain of having threads in the first place,is lost.5.Q:Having only a single lightweight process per process is also not such a good idea.Why not?w w w .k h d a w .c o m 课后答案网PROBLEM SOLUTIONS FOR CHAPTER 313A:In this scheme,we effectively have only user-level threads,meaning that any blocking system call will block the entire process.6.Q:Describe a simple scheme in which there are as many lightweight processes as there are runnable threads.A:Start with only a single LWP and let it select a runnable thread.When a runnable thread has been found,the LWP creates another LWP to look for a next thread to execute.If no runnable thread is found,the LWP destroys itself.7.Q:Proxies can support replication transparency by invoking each replica,as explained in the text.Can (the server side of)an object be subject to a repli-cated invocation?A:Yes:consider a replicated object A invoking another (nonreplicated)object B .If A consists of k replicas,an invocation of B will be done by each replica.However,B should normally be invoked only once.Special measures are needed to handle such replicated invocations.8.Q:Constructing a concurrent server by spawning a process has some advan-tages and disadvantages compared to multithreaded servers.Mention a few.A:An important advantage is that separate processes are protected against each other,which may prove to be necessary as in the case of a superserver handling completely independent services.On the other hand,process spawn-ing is a relatively costly operation that can be saved when using mul-tithreaded servers.Also,if processes do need to communicate,then using threads is much cheaper as in many cases we can avoid having the kernel implement the communication.9.Q:Sketch the design of a multithreaded server that supports multiple proto-cols using sockets as its transport-level interface to the underlying operating system.A:A relatively simple design is to have a single thread T waiting for incom-ing transport messages (TPDUs).If we assume the header of each TPDU con-tains a number identifying the higher-level protocol,the tread can take the payload and pass it to the module for that protocol.Each such module has a separate thread waiting for this payload,which it treats as an incoming request.After handling the request,a response message is passed to T ,which,in turn,wraps it in a transport-level message and sends it to tthe proper desti-nation.10.Q:How can we prevent an application from circumventing a windowmanager,and thus being able to completely mess up a screen?A:Use a microkernel approach by which the windowing system including the window manager are run in such a way that all window operations are w w w .kh d a w .c o m 课后答案网。
第三版操作系统部分课后答案
第1章1.答:所谓“多道程序设计”技术,即是通过软件的手段,允许在计算机内存中同时存放几道相互独立的作业程序,让它们对系统中的资源进行“共享”和“竞争”,以使系统中的各种资源尽可能地满负荷工作,从而提高整个计算机系统的使用效率。
基于这种考虑,计算机科学家开始把CPU、存储器、外部设备以及各种软件都视为计算机系统的“资源”,并逐步设计出一种软件来管理这些资源,不仅使它们能够得到合理地使用,而且还要高效地使用。
具有这种功能的软件就是“操作系统”。
所以,“多道程序设计”的出现,加快了操作系统的诞生。
2.答:拿操作系统来说,它是在裸机上加载的第一层软件,是对计算机硬件系统功能的首次扩充。
从用户的角度看,计算机配置了操作系统后,由于操作系统隐蔽了硬件的复杂细节,用户会感到机器使用起来更方便、容易了。
这样,通过操作系统的作用使展现在用户面前的是一台功能经过扩展了的机器。
这台“机器”不是硬件搭建成的,现实生活中并不存在具有这种功能的真实机器,它只是用户的一种感觉而已。
所以,就把这样的机器称为“虚拟机”。
3.答:在分时系统中,系统把CPU时间划分成许多时间片,每个终端用户可以使用由一个时间片规定的CPU时间,多个用户终端就轮流地使用CPU。
这样的效果是每个终端都开始了自己的工作,得到了及时的响应。
也就是说,“从宏观上看,多个用户同时工作,共享系统的资源”。
但实际上,CPU在每一时刻只为一个终端服务,即“从微观上看,各终端程序是轮流运行一个时间片”。
4.答:由于分布式系统的处理和控制功能是分布的,任何站点发生的故障都不会给整个系统造成太大的影响。
另外,当系统中的设备出现故障时,可以通过容错技术实现系统的重构,以保证系统的正常运行。
这一切都表明分布式系统具有健壮性。
5.答:基于嵌入式应用的多样化,嵌入式操作系统应该面向用户、面向产品、面向应用。
它必须有很强的适应能力,能够根据应用系统的特点和要求,灵活配置,方便剪裁,伸缩自如。
分布式算法习题参考答案
May 2002
This booklet contains (partial) solutions to most of the exercises in the book Introduction to Distributed Algorithms [Tel00]. Needless to say, the book as well as this document contain numerous errors; please find them and mail them to me! I have not included answers or hints for the following exercises and projects: 2.3, 2.9, 2.10, 3.2, 3.7, 6.16, 10.2, 12.8, 12.10, 12.11, 14.6, 17.5, 17.9, 17.11, B.5. Gerard Tel.
(. . . , cpi , . . . , cpj , . . .), (. . . , cpi , . . . , cpj , . . .) for which there is a message m ∈ M2 such that (cpi , m, cpi ) ∈
s pij ) ∈
.
Exercise 2.2. Consider the system S = ({γ, δ }, {(γ → δ )}, ∅), and define P to be true in γ but false in δ . As there are no initial configurations, this system has no computations, hence trivially P is always true in S . On the other hand, P is falsified in the only transition of the system, so P is not invariant. If an empty set of initial configurations is not allowed, the three state system S = ({β, γ, δ }, {(γ → δ )}, {β } is the minimal solution. The difference between invariant and always true is caused by the existence of transitions that falsify a predicate, but are applicable in an unreachable configuration, so that they do not “harm” any computation of the system. Exercise 2.4. (1) If each pair (γ, δ ) in →1 satisfies P (γ ) ⇒ P (δ ) and each such pair in →2 does so, then each pair in the union satisfies this relation. (2) Similarly, if (Q(γ ) ∧ P (γ )) ⇒ (Q(δ ) ⇒ P (δ )) holds for each pair (γ, δ ) in →1 and in →2 , then it holds for each pair in the union. (3) In the example, P is an invariant of S1 , and always true in S2 , but is falsified by a transition of S2 which is unreachable in S2 but reachable in S1 . This occurs when S1 = ({γ, δ, }, {(γ → δ )}, {γ }) and S2 = ({γ, δ, }, {(δ → )}, {γ }) with the assertion P , which is false in . Exercise 2.5. In (N2 , ≤l ), (1, k ) <l (2, 0) for each k ; hence there are infinitely many elements smaller than (2, 0). It is shown by induction on n that (Nn , ≤l ) is well-founded. 2
分布式系统概念与设计(第三版)课后习题与答案Chapter15
Chapter 15Solutions15.1Outline a system to support a distributed music rehearsal facility. Suggest suitable QoSrequirements and a hardware and software configuration that might be used.15.1 Ans..This is a particularly demanding interactive distributed multimedia application. Konstantas et al. [1997] report that a round-trip delay of less than 50 ms is required for it. Clearly, video and sound should be tightly synchronized so that the musicians can use visual cues as well as audio ones. Bandwidths should be suitable for the cameras and audio inputs used, e.g. 1.5 Mbps for video streams and 44 kbps for audio streams. Loss rates should be low, but not necessarily zero.The QoS requirements are much stricter than for conventional videoconferencing – music performance is impossible without strict synchronization. A software environment that includes QoS management with resource contracts is required. The operating systems and networks used should provide QoS guarantees. Few general-purpose OS’s provide them at present. Dedicated real-time OS’s are available but they are difficult to use for high-level application development.Current technologies that should be suitable:•ATM network.•PC’s with hardware for MPEG or MJPEG compression.•Real-time OS with support for high-level software development, e.g. in CORBA or Java.15.2The Internet does not currently offer any resource reservation or quality of service managementfacilities. How do the existing Internet-based audio and video streaming applications achieveacceptable quality? What limitations do the solutions they adopt place on multimediaapplications?15.2 Ans..There are two types of Internet-based applications:a)Media delivery systems such as music streaming, Internet radio and TV applications.b)Interactive applications such as Internet phone and video conferencing (NetMeeting, CuSeemMe).For type (a), the main technique used is traffic shaping, and more specifically, buffering at the destination.Typically, the data is played out some 5–10 seconds after its delivery at the destination. This masks the uneven latency and delivery rate (jitter) of Internet protocols and masks the delays incurred in the network and transport layers of the Internet due to store-and-forward transmission and TCP’s reliability mechanisms.For type (b), the round trip delay must be kept below 100 ms so the above technique is ruled out. Instead, stream adaptation is used. Specifically, video is transmitted with high levels of compression and reduced frame rates. Audio requires less adaptation. UDP is generally used.Overall, type (a) systems work reasonably well for audio and low-resolution video only. For type (b) the results are usually unsatisfactory unless the network routes and operating system priorities are explicitly managed.15.3Explain the distinctions between the three forms of synchronization (synchronous distributedstate, media synchronization and external synchronization) that may be required in distributedmultimedia applications. Suggest mechanisms by which each of them could be achieved, forexample in a videoconferencing application.15.3 Ans..synchronous distributed state: All users should see the same application state. For example, the results of operation on controls for a video, such as start and pause should be synchronized, so that all users see the same frame. This can be done by associating the current state (sample number) of the active multimedia streams with each state-change message. This constitutes a form of logical vector timestamp.media synchronization: Certain streams are closely coupled. E.g. the audio that accompanies a video stream.They should be synchronised using timestamps embedded in the media data.external synchronization: This is really an instance of synchronous distributed state. The messages that update shared whiteboards and other shared objects should carry vector timestamps giving the states of media streams.15.4Outline the design of a QoS manager to enable desktop computers connected by an ATM networkto support several concurrent multimedia applications. Define an API for your QoS manager,giving the main operations with their parameters and results.15.4 Ans..Each multimedia application requires a resource contract for each of its multimedia streams. Whenever a new stream is to be started, a request is made to the QoS manager specifying CPU resources, memory and network connections with their Flow Specs. The QoS manager performs an analysis similar to Figure 15.6 for each end-to-end stream. If several streams are required for a single application, there is a danger of deadlock – resources are allocated for some of the streams, but the needs of the remaining streams cannot be satisfied. When this happens, the QoS negotiation should abort and restart, but if the application is already running, this is impractical, so a negotiation takes place to reduce the resources of existing streams.API:QoSManager.QoSRequest(FlowID, FlowSpec) –> ResourceContractThe above is the basic interface to the QoS Manager. It reserves resources as specified in the FlowSpec and returns a corresponding ResourceContract.A FlowSpec is a multi-valued object, similar to Figure 15.8.A ResourceContract is a token that can be submitted to each of the resource handlers (CPU scheduler,memory manager, network driver, etc.).Application.ScaleDownCallback(FlowID, FlowSpec) -> AcceptRejectThe above is a callback from the QoS Manager to an application, requesting a change in the FlowSpec fora stream. The application can return a value indicating acceptance or rejection.15.5In order to specify the resource requirements of software components that process multimediadata, we need estimates of their processing loads. How should this information be obtained?15.5 Ans..The main issue is how to measure or otherwise evaluate the resource requirements (CPU, memory, network bandwidth, disk bandwidth) of the components that handle multimedia streams without a lot of manual testing.A test framework is required that will evaluate the resource utilization of a running component. But there isalso a need for resource requirement models of the components – so that the requirements can be extrapolated to different application contexts and stream characteristics and different hardware environments (hardware performance parameters).15.6How does the Tiger system cope with a large number of clients all requesting the same movie atrandom times?15.6 Ans..If they arrive within a few seconds of each other, then they can be placed sufficiently close together in the schedule to take advantage of caching in the cubs, so a single disk access for a block can service several clients.If they are more widely spaced, then they are placed independently (in an empty slot near the disk holding he first block of the movie at the time each request is received). There will be no conflict for resources because different blocks of the movie are stored on different disks and cubs.15.7The Tiger schedule is potentially a large data structure that changes frequently, but each cub needsan up-to-date representation of the portions it is currently handling. Suggest a mechanism for thedistribution of the schedule to the cubs.15.7 Ans..In the first implementation of Tiger the controller computer was responsible for maintaining an up-to-date version of the schedule and replicating it to all of the cubs. This does not scale well – the processing and communication loads at the controller grow linearly with the number of clients – and is likely to limit the scale of the service that Tiger can support. In a later implementation, the cubs were made collectively responsible for maintaining the schedule. Each cub holds a fragment of the schedule – just those slots that it will be playing processing in the near future. When slots have been processed they are updated to show the current viewer state and then they are passed to the next ‘downstream’ cub. Cubs retain some extra fragments for fault-tolerance purposes.When the controller needs to modify the schedule – to delete or suspend an existing entry or to insert a viewer into an empty slot – it sends a request to the cub that is currently responsible for the relevant fragment of the schedule to make the update. The cub then uses the updated schedule fragment to fulfil its responsibilities and passes it to the next downstream cub.15.8When Tiger is operating with a failed disk or cub, secondary data blocks are used in place ofmissing primaries. Secondary blocks are n times smaller than primaries (where n is the declusterfactor), how does the system accommodate this variability in block size?15.8 Ans..Whether they are large primary or smaller secondary blocks, they are always identified by a play sequence number. The cubs simply deliver the blocks to the clients in order via the ATM network. It is the clients’responsibility to assemble them in the correct sequence and then to extract the frames from the incoming sequence of blocks and play the frames according to the play schedule.。
分布式系统试题及答案
分布式系统复习题库及答案1、计算机系统的硬件异构性、软件异构性主要表现在哪几方面?参考答案:计算机系统的硬件异构性主要有三个方面的表现,即:①计算机的指令系统不同。
这意味着一种机器上的程序模块不能在另一种不兼容的机器上执行,很显然,一种机器上的可执行代码程序不能在另一种不兼容的机器上执行。
②数据表示方法不同。
例如不同类型的计算机虽然都是按字节编址的,但是高字节和低字节的规定可能恰好相反。
浮点数的表示方法也常常不一样。
③机器的配置不同。
尽管机器的类型可能相同,其硬件配置也可以互不兼容。
计算机系统的软件异构性包括操作系统异构性和程序设计语言异构性。
操作系统异构性的三个主要表现方面为:①操作系统所提供的功能可能大不相同。
例如,不同的操作系统至少提供了不同的命令集。
②操作系统所提供的系统调用在语法、语义和功能方面也不相同。
③文件系统不同。
程序设计语言的异构性表现在不同的程序设计语言用不同方法在文件中存储数据。
2、由于分布计算系统包含多个(可能是不同种类的)分散的、自治的处理资源,要想把它们组织成一个整体,最有效地完成一个共同的任务,做到这一点比起传统的集中式的单机系统要困难得多,需要解决很多新问题。
这些问题主要表现在哪些方面?参考答案:①资源的多重性带来的问题。
由于处理资源的多重性,分布计算系统可能产生的差错类型和次数都比集中式单机系统多。
最明显的一个例子是部分失效问题:系统中某一个处理资源出现故障而其他计算机尚不知道,但单机系统任何一部分出现故障时将停止整个计算。
另一个例子是多副本信息一致性问题。
可见,资源多重性使得差错处理和恢复问题变得很复杂。
资源多重性还给系统资源管理带来新的困难。
②资源的分散性带来的问题。
在分布计算系统中,系统资源在地理上是分散的。
由于进程之间的通信采用的是报文传递的方式进行的,通信将产生不可预测的、有时是巨大的延迟,特别是在远程网络所组成的分布计算系统中更是这样。
例如使用卫星通信会产生270毫秒的延迟。
《分布式系统概念与设计》(第5版)第一章答案
Distributed Systems: Concepts and DesignEdition 5By George Coulouris, Jean Dollimore and Tim Kindberg and Gordon BlairAddison-Wesley ©Pearson Education 2012Chapter1Exercise Solutions1.1We define a distributed system as one in which hardware or software components located atnetworked computers communicate and coordinate their actions only by passing messages. Whatare the consequences of defining a distributed system in this manner?1.1 Ans.a.Concurrencyb.No global clockc.Independent failures.1.2How might the clocks in two computers that are linked by a local network be synchronized withoutreference to an external time source? What factors limit the accuracy of the procedure you havedescribed? How could the clocks in a large number of computers connected by the Internet besynchronized? Discuss the accuracy of that procedure.1.2 Ans.Several time synchronization protocols are described in Section 10.3. One of these is Cristian’s protocol.Briefly, the round trip time t to send a message and a reply between computer A and computer B is measured by repeated tests; then computer A sends its clock setting T to computer B. B sets its clock to T+t/2. The setting can be refined by repetition. The procedure is subject to inaccuracy because of contention for the use of the local network from other computers and delays in the processing the messages in the operating systems of A and B. For a local network, the accuracy is probably within 1 ms.For a large number of computers, one computer should be nominated to act as the time server and it should carry out Cristian’s protocol with all of them. The protocol can be initiated by each in turn. Additional inaccuracies arise in the Internet because messages are delayed as they pass through switches in wider area networks. For a wide area network the accuracy is probably within 5-10 ms. These answers do not take into account the need for fault-tolerance. See Chapter 10 for further details.1.3Consider the implementation strategies for massively multiplayer online games as discussed inSection 1.2.2. In particular, what advantages do you see in adopting a single server approach forrepresenting the state of the multiplayer game? What problems can you identify and how mightthey be resolved?1.3 Ans.The advantages of having a single server maintain a representation of the game are that: (1) there is a single copy and hence no need to maintain consistency of multiple copies; and (2) clients have a single place to go to discover this state. There may also be advantages to having a global view of the entire systems state.The potential problems are that this single server may fail and may also become a bottleneck affecting the performance and scalability of the approach. To handle failure, it would be necessary to introduce replication, which in turn would require a solution to maintaining consistency across replicas. There are a number of solutions to improving performance and scalability including running the server on a cluster architecture as described in Section 1.2.2, or again using replication and load balancing within the distributed environment. Alternatively, a peer-to-peer solution can be adopted. These techniques are covered throughout the book.1.4 A user arrives at a railway station that she has never visited before, carrying a PDA that is capableof wireless networking. Suggest how the user could be provided with information about the localservices and amenities at that station, without entering the station’s name or attributes. Whattechnical challenges must be overcome?1.4 Ans.The user must be able to acquire the address of locally relevant information as automatically as possible. One method is for the local wireless network to provide the URL of web pages about the locality over a local wireless network.For this to work: (1) the user must run a program on her device that listens for these URLs, and which gives the user sufficient control that she is not swamped by unwanted URLs of the places she passes through; and(2) the means of propagating the URL (e.g. infrared or an 802.11 wireless LAN) should have a reach thatcorresponds to the physical spread of the place itself.1.5Distributed systems are going through a period of significant change, which can be traced back toa number of influential trends. Can you identify what these might be?1.5 Ans.a.The emergence of pervasive networking technology.b.The emergence of ubiquitous computing coupled with the desire to support user mobility indistributed systems.c.The increasing demand for multimedia services.d.The view of distributed systems as a utility.1.6Due to the increasing maturity of distributed systems infrastructure, organizations are movingtowards viewing distributed systems as a utility. I n this model, resources are provided byappropriate service suppliers and effectively rented rather than owned by the end user. Explain thismodel with respect to physical resources and software services. Can you give examples of somecompanies that support such software services?1.6 Ans.a.Physical resources such as storage and processing can be made available to networkedcomputers removing the need to own such resources on their own.b.Software services can also be made available across the global Internet using this approach.Example of companies supporting such software services are ,.1.7 A server program written in one language (for example C++) provides the implementation of aBLOB object that is intended to be accessed by clients that may be written in a different language(for example Java). The client and server computers may have different hardware, but all of themare attached to an internet. Describe the problems due to each of the five aspects of heterogeneitythat need to be solved to make it possible for a client object to invoke a method on the serverobject.1.7 Ans.As the computers are attached to an internet, we can assume that Internet protocols deal with differences in networks.But the computers may have different hardware - therefore we have to deal with differences of representation of data items in request and reply messages from clients to objects. A common standard will be defined for each type of data item that must be transmitted between the object and its clients.The computers may run different operating systems, therefore we need to deal with different operations to send and receive messages or to express invocations. Thus at the Java/C++ level a common operation would be used which will be translated to the particular operation according to the operating system it runs on.We have two different programming languages C++ and Java, they use different representations for data structures such as strings, arrays, records. A common standard will be defined for each type of data structure that must be transmitted between the object and its clients and a way of translating between that data structure and each of the languages.We may have different implementors, e.g. one for C++ and the other for Java. They will need to agree on the common standards mentioned above and to document them.1.8What is client-server computing? Which of these roles is an active role, and which is a passiveone? Explain remote invocation in this context.1.8 Ans.Client server computing refers to a running program (a process) on a networked computer that accepts requests from programs running on other computers to perform a service and responds appropriately.Clients are active (making requests) and servers are passive.The interaction between a client and a server, from the point when the client sends its request to when it receives the server’s response, is called remote invocation.1.9Suppose that the operations of the BLOB object are separated into two categories – publicoperations that are available to all users and protected operations that are available only to certainnamed users. State all of the problems involved in ensuring that only the named users can use aprotected operation. Supposing that access to a protected operation provides information thatshould not be revealed to all users, what further problems arise?1.9 Ans.Each request to access a protected operation must include the identity of the user making the request. The problems are:•defining the identities of the users. Using these identities in the list of users who are allowed to access the protected operations at the implementation of the BLOB object. And in the request messages.•ensuring that the identity supplied comes from the user it purports to be and not some other user pretending to be that user.•preventing other users from replaying or tampering with the request messages of legitimate users.Further problems.•the information returned as the result of a protected operation must be hidden from unauthorised users.This means that the messages containing the information must be encrypted in case they are interceptedby unauthorised users.1.10The INFO service manages a potentially very large set of resources, each of which can be accessedby users throughout the Internet by means of a key (a string name). Discuss an approach to thedesign of the names of the resources that achieves the minimum loss of performance as the numberof resources in the service increases. Suggest how the INFO service can be implemented so as toavoid performance bottlenecks when the number of users becomes very large.1.10 Ans.Algorithms that use hierarchic structures scale better than those that use linear structures. Therefore the solution should suggest a hierarchic naming scheme. e.g. that each resource has an name of the form ’A.B.C’etc. where the time taken is O(log n) where there are n resources in the system.To allow for large numbers of users, the resources are partitioned amongst several servers, e.g. names starting with A at server 1, with B at server 2 and so forth. There could be more than one level of partitioning as in DNS. To avoid performance bottlenecks the algorithm for looking up a name must be decentralised. That is, the same server must not be involved in looking up every name. (A centralised solution would use a single root server that holds a location database that maps parts of the information onto particular servers). Some replication is required to avoid such centralisation. For example: i) the location database might be replicated at multiple root servers or ii) the location database might be replicated in every server. In both cases, different clients must access different servers (e.g. local ones or randomly).1.11 A distributed system is described as scalable when it remains effective when there is a significantincrease in the number of resources and the number of users. However, these systems sometimesface performance bottlenecks. How can these be avoided?1.11 Ans.Caching and replication may be used to improve the performance of the resources that are very heavily used in a distributed system.1.12 A server process maintains a shared information object such as the BLOB object of Exercise 1.7.Give arguments for and against allowing the client requests to be executed concurrently by theserver. In the case that they are executed concurrently, give an example of possible ‘interference’that can occur between the operations of different clients. Suggest how such interference may beprevented.1.12 Ans.For concurrent executions - more throughput in the server (particularly if the server has to access a disk or another service)Against - problems of interference between concurrent operationsExample:Client A’s thread reads value of variable XClient B’s thread reads value of variable XClient A’s thread adds 1 to its value and stores the result in XClient B’s thread subtracts 1 from its value and stores the result in XResult: X := X-1; imagine that X is the balance of a bank account, and clients A and B are implementing credit and debit transactions, and you can see immediately that the result is incorrect.To overcome interference use some form of concurrency control. For example, for a Java server use synchronized operations such as credit and debit.1.13The ANSA Reference Manual [ANSA 1989] identified eight forms of transparency in a distributedsystem. Which are the two most important transparencies among these?1.13 Ans.The two most important transparencies are access and location transparency; their presence or absence most strongly affects the utilization of distributed resources. They are sometimes referred to together as network transparency.1.14One of the main standard technological components of web is the HyperText Transfer Protocol(HTTP), which defines the ways in which browsers and other types of clients interact with webservers. What are the different features of the HTTP?1.14 Ans.The main features of HTTP are:a.Request-reply interactionsb.Content typesc.One resource per requestd.Simple access control1.15What are the two main functions of an HTTP URL? Explain its general form. Identify the serverDNS name, path name, query, and fragment for the URL /search?q=sabretooth.1.15 Ans.An HTTP URL has two main jobs to do: to identify which web server maintains the resource, and to identify which of the resources at that server is required.In general, HTTP URLs are of the following form:http:// servername [:port] [/pathName] [?query][ #fragment]where items in square brackets are optional. A full HTTP URL always begins with the string ‘http://’followed by a server name, expressed as a Domain Name System (DNS) name. The server’s DNS name is optionally followed by the number of the ‘port’ on which the server listens for requests.Then comes an optional path name of the server’s resource. If this is absent then the server’s default web page is required. Finally, the URL optionally ends in a query component – for example, when a user submits the entries in a form such as a search engine’s query page – and/or a fragment identifier, which identifies a component of the resource.In the URL /search?q=sabretoothThe Server DNS name is The Path name is searchThe Query is q= sabretoothThere is no Fragment.。
分布式计算原理及应用第五章部分答案
1.In the context of distributed computing,describe the client-server paradigm.Why is this paradigm especially appropriate for network services?Answer:In distributed computing,the client-server paradigm refers to a model for network applications where processes play one of two different roles:a server process,also called a server for short,if dedicated to managing access to some network service,while client processes,called clients for short,access the server to obtain a network service.The client-server model is designed for providing network services,which were,and still are,the most popular application of distributed computing.By network service we mean a service provided to allow network users to share resources.It is very easy for us to create a mechanism that a server can provide service concurrently for multiple clients,that is,one-to-many.ing the three-tier software architecture presented in this chapter,design and implement a client-server suite for the following protocol (it is not a well-known service):Each client sends a name to the server.The sever accumulates the names received from successive clients (by appending each,with a newline character,'/n',to a static string).Upon receiving a name,the server sends the names it has collected to the client.The client then displays all the names it receives from the server.Figure 5.38 below illustrates the sequence diagram of the protocol with 3 concurrent client sessions.a.Is this server a stateful server?If so,what kind of state information(global or session) does it maintain?b.Create one or more of the following suites for the protocol:i.Connectionless server and clientii.Connection-oriented,iterative server and clientiii.Connection-oriented,concurrent server and clientFor each suite,hand in:(A)program listings,and (B) a description of how the three-tier architecture is realized using separate software modules(Java classes).Name server Client1 Client2 Client3MattMattCathyMatt\nCathyJohnMatt\nCathy\nJohnFigure 5.35 A sequence diagram of the protocol showing three concurrent client sessions.A.This server is a stateful server.It maintains a global information which records all the messages by order the clients send to it,separated by the character '\n'.B.i.Connectionless server and clientClient:(1)Presentationpackage distributedComputing;//This is the presentation layer//connectionlessimport java.io.BufferedReader;import java.io.InputStreamReader;public class Client1 {static final String endMessage = ".";public static void main(String[] args){InputStreamReader is = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(is);try{System.out.println("Welcome to the client.\n"+"What is the name of the server host?");String hostName = br.readLine();if(hostName.length()==0)hostName = "localhost";System.out.println("What is the port number of the server host?");String portNum = br.readLine();if(portNum.length()==0)portNum = "13";ClientHelper1 helper =new ClientHelper1(hostName,portNum);boolean done = false;String message,echo;while(!done){System.out.println("Enter a line to receive an echo back" +"from the server,"+"or a single peroid to quit.");message = br.readLine();if((message.trim()).equals(endMessage)){done = true;helper.done();}else{echo = helper.getEcho(message); //send messages and receive responseSystem.out.println(echo);}}}catch(Exception ex){ex.printStackTrace();}}}(2)Applicationpackage distributedComputing;//this is the application layer//connectionlessimport java.io.IOException;import .InetAddress;import .SocketException;import .UnknownHostException;public class ClientHelper1 {private MyClientDatagramSocket mySocket;private InetAddress serverHost;private int serverPort;ClientHelper1(String hostName,String portNum)throws SocketException,UnknownHostException{this.serverHost = InetAddress.getByName(hostName);this.serverPort = Integer.parseInt(portNum);this.mySocket = new MyClientDatagramSocket();}public String getEcho(String message)throws SocketException,IOException{String echo = "";mySocket.sendMessage(serverHost, serverPort, message);echo = mySocket.receiveMessage();echo.replaceAll(" ", "");return echo;}public void done() throws SocketException{mySocket.close();}}(3)Servicepackage distributedComputing;//this is the service layer//connectionlessimport java.io.IOException;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import .SocketException;public class MyClientDatagramSocket extends DatagramSocket{static final int MAX_LEN = 64;MyClientDatagramSocket() throws SocketException{super();}MyClientDatagramSocket(int portNo) throws SocketException{super(portNo);}public void sendMessage(InetAddress receiverHost,int receiverPort,String message) throws IOException{byte[] sendBuffer = message.getBytes();DatagramPacket datagram =new DatagramPacket(sendBuffer,sendBuffer.length,receiverHost,receiverPort);this.send(datagram);}public String receiveMessage () throws IOException{byte[] receiveBuffer = new byte[MAX_LEN];DatagramPacket datagram =new DatagramPacket(receiveBuffer,receiveBuffer.length);this.receive(datagram);String message = new String(datagram.getData(),0,datagram.getLength());return message;}}Server:(1)presentation and applicationpackage distributedComputing;//connectionless//These are the application layer and the presentation layerimport java.util.Date;public class Server1 {private static StringBuffer sbf = new StringBuffer();public static void main(String[] args){int serverPort = 13;if(args.length==1)serverPort = Integer.parseInt(args[0]);try{MyServerDatagramSocket mySocket =new MyServerDatagramSocket(serverPort);System.out.println("server ready.");while(true){DatagramMessage request =mySocket.receiveMessageAndSender();System.out.println("Request received");String message = request.getMessage();//这里有问题if(sbf.length()==0)sbf.append(message);elsesbf.append("\\n"+message);System.out.println("message received:"+message);mySocket.sendMessage(request.getAddress(), request.getPort(), sbf.toString());}}catch(Exception ex){ex.printStackTrace();}}}(2)Servicepackage distributedComputing;//connecitonless//this is the service layerimport java.io.IOException;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import .SocketException;public class MyServerDatagramSocket extends DatagramSocket{static final int MAX_LEN = 64;MyServerDatagramSocket(int portNo) throws SocketException{super(portNo);}public void sendMessage(InetAddress receiverHost,int receiverPort,String message)throws IOException{byte[] sendBuffer = message.getBytes();DatagramPacket datagram =new DatagramPacket(sendBuffer,sendBuffer.length,receiverHost,receiverPort);this.send(datagram);}public String receiveMessage() throws IOException{byte[] receiveBuffer = new byte[MAX_LEN];DatagramPacket datagram =new DatagramPacket(receiveBuffer,receiveBuffer.length);this.receive(datagram);String message = new String(datagram.getData(),0,datagram.getLength());return message;}public DatagramMessage receiveMessageAndSender() throws IOException{byte[] receiveBuffer = new byte[MAX_LEN];DatagramPacket datagram =new DatagramPacket(receiveBuffer,receiveBuffer.length);this.receive(datagram);DatagramMessage returnV al = new DatagramMessage();returnV al.putV al(new String(datagram.getData(),0,datagram.getLength()), datagram.getAddress(), datagram.getPort());return returnV al;}}(3)package of the datagrampackage distributedComputing;//This class helps the program to package the datagramimport .InetAddress;public class DatagramMessage { private String message;private InetAddress senderAddress; private int senderPort;public void putV al(String message,InetAddress addr,int port){ this.message = message; this.senderAddress = addr; this.senderPort = port;}public String getMessage(){ return this.message; }public InetAddress getAddress(){ return this.senderAddress; }public int getPort(){ return this.senderPort;}}UML class diagram for Client1Client1DatagramPacketClientHelper1DatagramSocketMyClient DatagramSocketsendMessage() receiveMessage()Presentation logic Application logicService logicUML class diagram for Server1Running Result:Client ServerDatagramPacketDatagramMessageMyServerDatagramSocketsendMessage() receiveMessage() receiveMessageAnd Sender()Server1 DatagramSocketService logicPresentation+applicationlogicii.Connection-oriented,iterative server and clientClient:(1)Presentationpackage distributedComputing;//connection-oriented//this is the presentation layerimport java.io.BufferedReader;import java.io.InputStreamReader;public class Client2 {static final String endMessage = ".";public static void main(String[] args){InputStreamReader is = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(is);try{System.out.println("Welcome to the client.\n"+"What is the name of the server host?");String hostName = br.readLine();if(hostName.length()==0)hostName = "localhost";System.out.println("What is the port number of the server host?");String portNum = br.readLine();if(portNum.length()==0)portNum = "13";ClientHelper2 helper =new ClientHelper2(hostName,portNum);boolean done = false;String message,echo;while(!done){System.out.println("Enter a line to receive an echo back" +"from the server,"+"or a single peroid to quit.");message = br.readLine();if((message.trim()).equals(endMessage)){done = true;helper.done();}else{echo = helper.getEcho(message);System.out.println(echo);}}}catch(Exception ex){ex.printStackTrace();}}}(2)Applicationpackage distributedComputing;//connection-oriented//this is the application layerimport java.io.IOException;import .InetAddress;import .SocketException;import .UnknownHostException;public class ClientHelper2 {static final String endMessage = ".";private MyStreamSocket mySocket;private InetAddress serverHost;private int serverPort;ClientHelper2(String hostName,String portNum) throws SocketException,UnknownHostException,IOException{ this.serverHost = InetAddress.getByName(hostName);this.serverPort = Integer.parseInt(portNum);this.mySocket = new MyStreamSocket(hostName,this.serverPort);System.out.println("Connection request made");}public String getEcho(String message) throws SocketException,IOException{ String echo = "";mySocket.sendMessage(message);echo = mySocket.receiveMessage();return echo;}public void done() throws SocketException,IOException{mySocket.sendMessage(endMessage);mySocket.close();}}(3)Servicepackage distributedComputing;//connection-oriented//this is the service layerimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import .Socket;import .SocketException;public class MyStreamSocket extends Socket{private Socket socket;private BufferedReader input;private PrintWriter output;MyStreamSocket(String acceptorHost,int acceptorPort) throws SocketException, IOException{ socket = new Socket(acceptorHost,acceptorPort);setStreams();}MyStreamSocket(Socket socket) throws IOException{this.socket = socket;setStreams();}private void setStreams() throws IOException{InputStream inStream = socket.getInputStream();input =new BufferedReader(new InputStreamReader(inStream));OutputStream outStream = socket.getOutputStream();output =new PrintWriter(new OutputStreamWriter(outStream));}public void sendMessage(String message) throws IOException{ output.println(message);output.flush();}public String receiveMessage() throws IOException{String message = input.readLine();return message;}}Server:(1)presentation and applicationpackage distributedComputing;//connection-oriented//these are the presentation layer and the application layerimport .ServerSocket;public class Server2 {static final String endMessage = ".";private static StringBuffer sbf = new StringBuffer();public static void main(String[] args){int serverPort = 13;String message;if(args.length==1)serverPort = Integer.parseInt(args[0]);try{ServerSocket myConnectionSocket =new ServerSocket(serverPort);System.out.println("Waiting for a connection.");MyStreamSocket myDataSocket = new MyStreamSocket(myConnectionSocket.accept());System.out.println("connection accepted");boolean done = false;while(!done){message = myDataSocket.receiveMessage();System.out.println("message received:"+message);if(sbf.length()==0)sbf.append(message);elsesbf.append("\\n"+message);if((message.trim()).equals(endMessage)){System.out.println("Session over.");myDataSocket.close();done = true;}else{myDataSocket.sendMessage(sbf.toString());}}}catch(Exception ex){ex.printStackTrace();}}}(2)ServiceIt's the same as the Client's.UML class diagram for Client2Client2ClientHelper2 MyStreamSocketsendMessage()receiveMessage() SocketPresentation logicApplication logicService logicUML class diagram for Server2Server3Running Result:Client ServerServerSocketThreadMyStreamSocketreceiveMessage AndSender()SocketService logicPresentation and Application logiciii.Connection-oriented,concurrent server and clientIt's almost the same as the answer of the below question except that there is some differences with the server.(1)ServerThreadpackage distributedComputing;public class ServerThread implements Runnable{static final String endMessage = ".";static StringBuffer sbf = new StringBuffer();MyStreamSocket myDataSocket;ServerThread(MyStreamSocket myDataSocket){this.myDataSocket = myDataSocket;}public void run(){boolean done = false;String message;try{while(!done){message = myDataSocket.receiveMessage();System.out.println("message received:"+message);if(sbf.length()==0)sbf.append(message);elsesbf.append("\\n"+message);if((message.trim()).equals(endMessage)){System.out.println("Session over.");myDataSocket.close();done = true;}else{myDataSocket.sendMessage(sbf.toString());}}}catch(Exception ex){System.out.println("Exception caught in thread:"+ex);}}}(2)Serverpackage distributedComputing;import .ServerSocket;public class Server3 {private static StringBuffer sbf = new StringBuffer();public static void main(String[] args){int serverPort = 13;String message;if(args.length==1)serverPort = Integer.parseInt(args[0]);try{ServerSocket myConnectionSocket =new ServerSocket(serverPort);System.out.println("Server ready");while(true){System.out.println("Waiting for a connection");MyStreamSocket myDataSocket = new MyStreamSocket(myConnectionSocket.accept());System.out.println("connection accepted");Thread theThread =new Thread(new ServerThread(myDataSocket));theThread.start();}}catch(Exception ex){ex.printStackTrace();}}}Running Result:Client1 Client2These are two differentconnectionServerChapter 210.Draw a sequence diagram for the Daytime protocol.Answer :Server Client11.Is it possible for a Daytime client to be blocked indefinitely?Explain.Answer :It's possible for a Daytime client to be blocked indefinitely when the server starts its receiving service after the client's giving request.Ask for a timestampResponse with a timestampTime。
《分布式系统概念与设计》(第5版)第一章答案
Distributed Systems: Concepts and DesignEdition 5By George Coulouris, Jean Dollimore and Tim Kindberg and Gordon BlairAddison-Wesley ©Pearson Education 2012Chapter1Exercise Solutions1.1We define a distributed system as one in which hardware or software components located atnetworked computers communicate and coordinate their actions only by passing messages. Whatare the consequences of defining a distributed system in this manner?1.1 Ans.a.Concurrencyb.No global clockc.Independent failures.1.2How might the clocks in two computers that are linked by a local network be synchronized withoutreference to an external time source? What factors limit the accuracy of the procedure you havedescribed? How could the clocks in a large number of computers connected by the Internet besynchronized? Discuss the accuracy of that procedure.1.2 Ans.Several time synchronization protocols are described in Section 10.3. One of these is Cristian’s protocol.Briefly, the round trip time t to send a message and a reply between computer A and computer B is measured by repeated tests; then computer A sends its clock setting T to computer B. B sets its clock to T+t/2. The setting can be refined by repetition. The procedure is subject to inaccuracy because of contention for the use of the local network from other computers and delays in the processing the messages in the operating systems of A and B. For a local network, the accuracy is probably within 1 ms.For a large number of computers, one computer should be nominated to act as the time server and it should carry out Cristian’s protocol with all of them. The protocol can be initiated by each in turn. Additional inaccuracies arise in the Internet because messages are delayed as they pass through switches in wider area networks. For a wide area network the accuracy is probably within 5-10 ms. These answers do not take into account the need for fault-tolerance. See Chapter 10 for further details.1.3Consider the implementation strategies for massively multiplayer online games as discussed inSection 1.2.2. In particular, what advantages do you see in adopting a single server approach forrepresenting the state of the multiplayer game? What problems can you identify and how mightthey be resolved?1.3 Ans.The advantages of having a single server maintain a representation of the game are that: (1) there is a single copy and hence no need to maintain consistency of multiple copies; and (2) clients have a single place to go to discover this state. There may also be advantages to having a global view of the entire systems state.The potential problems are that this single server may fail and may also become a bottleneck affecting the performance and scalability of the approach. To handle failure, it would be necessary to introduce replication, which in turn would require a solution to maintaining consistency across replicas. There are a number of solutions to improving performance and scalability including running the server on a cluster architecture as described in Section 1.2.2, or again using replication and load balancing within the distributed environment. Alternatively, a peer-to-peer solution can be adopted. These techniques are covered throughout the book.1.4 A user arrives at a railway station that she has never visited before, carrying a PDA that is capableof wireless networking. Suggest how the user could be provided with information about the localservices and amenities at that station, without entering the station’s name or attributes. Whattechnical challenges must be overcome?1.4 Ans.The user must be able to acquire the address of locally relevant information as automatically as possible. One method is for the local wireless network to provide the URL of web pages about the locality over a local wireless network.For this to work: (1) the user must run a program on her device that listens for these URLs, and which gives the user sufficient control that she is not swamped by unwanted URLs of the places she passes through; and(2) the means of propagating the URL (e.g. infrared or an 802.11 wireless LAN) should have a reach thatcorresponds to the physical spread of the place itself.1.5Distributed systems are going through a period of significant change, which can be traced back toa number of influential trends. Can you identify what these might be?1.5 Ans.a.The emergence of pervasive networking technology.b.The emergence of ubiquitous computing coupled with the desire to support user mobility indistributed systems.c.The increasing demand for multimedia services.d.The view of distributed systems as a utility.1.6Due to the increasing maturity of distributed systems infrastructure, organizations are movingtowards viewing distributed systems as a utility. I n this model, resources are provided byappropriate service suppliers and effectively rented rather than owned by the end user. Explain thismodel with respect to physical resources and software services. Can you give examples of somecompanies that support such software services?1.6 Ans.a.Physical resources such as storage and processing can be made available to networkedcomputers removing the need to own such resources on their own.b.Software services can also be made available across the global Internet using this approach.Example of companies supporting such software services are ,.1.7 A server program written in one language (for example C++) provides the implementation of aBLOB object that is intended to be accessed by clients that may be written in a different language(for example Java). The client and server computers may have different hardware, but all of themare attached to an internet. Describe the problems due to each of the five aspects of heterogeneitythat need to be solved to make it possible for a client object to invoke a method on the serverobject.1.7 Ans.As the computers are attached to an internet, we can assume that Internet protocols deal with differences in networks.But the computers may have different hardware - therefore we have to deal with differences of representation of data items in request and reply messages from clients to objects. A common standard will be defined for each type of data item that must be transmitted between the object and its clients.The computers may run different operating systems, therefore we need to deal with different operations to send and receive messages or to express invocations. Thus at the Java/C++ level a common operation would be used which will be translated to the particular operation according to the operating system it runs on.We have two different programming languages C++ and Java, they use different representations for data structures such as strings, arrays, records. A common standard will be defined for each type of data structure that must be transmitted between the object and its clients and a way of translating between that data structure and each of the languages.We may have different implementors, e.g. one for C++ and the other for Java. They will need to agree on the common standards mentioned above and to document them.1.8What is client-server computing? Which of these roles is an active role, and which is a passiveone? Explain remote invocation in this context.1.8 Ans.Client server computing refers to a running program (a process) on a networked computer that accepts requests from programs running on other computers to perform a service and responds appropriately.Clients are active (making requests) and servers are passive.The interaction between a client and a server, from the point when the client sends its request to when it receives the server’s response, is called remote invocation.1.9Suppose that the operations of the BLOB object are separated into two categories – publicoperations that are available to all users and protected operations that are available only to certainnamed users. State all of the problems involved in ensuring that only the named users can use aprotected operation. Supposing that access to a protected operation provides information thatshould not be revealed to all users, what further problems arise?1.9 Ans.Each request to access a protected operation must include the identity of the user making the request. The problems are:•defining the identities of the users. Using these identities in the list of users who are allowed to access the protected operations at the implementation of the BLOB object. And in the request messages.•ensuring that the identity supplied comes from the user it purports to be and not some other user pretending to be that user.•preventing other users from replaying or tampering with the request messages of legitimate users.Further problems.•the information returned as the result of a protected operation must be hidden from unauthorised users.This means that the messages containing the information must be encrypted in case they are interceptedby unauthorised users.1.10The INFO service manages a potentially very large set of resources, each of which can be accessedby users throughout the Internet by means of a key (a string name). Discuss an approach to thedesign of the names of the resources that achieves the minimum loss of performance as the numberof resources in the service increases. Suggest how the INFO service can be implemented so as toavoid performance bottlenecks when the number of users becomes very large.1.10 Ans.Algorithms that use hierarchic structures scale better than those that use linear structures. Therefore the solution should suggest a hierarchic naming scheme. e.g. that each resource has an name of the form ’A.B.C’etc. where the time taken is O(log n) where there are n resources in the system.To allow for large numbers of users, the resources are partitioned amongst several servers, e.g. names starting with A at server 1, with B at server 2 and so forth. There could be more than one level of partitioning as in DNS. To avoid performance bottlenecks the algorithm for looking up a name must be decentralised. That is, the same server must not be involved in looking up every name. (A centralised solution would use a single root server that holds a location database that maps parts of the information onto particular servers). Some replication is required to avoid such centralisation. For example: i) the location database might be replicated at multiple root servers or ii) the location database might be replicated in every server. In both cases, different clients must access different servers (e.g. local ones or randomly).1.11 A distributed system is described as scalable when it remains effective when there is a significantincrease in the number of resources and the number of users. However, these systems sometimesface performance bottlenecks. How can these be avoided?1.11 Ans.Caching and replication may be used to improve the performance of the resources that are very heavily used in a distributed system.1.12 A server process maintains a shared information object such as the BLOB object of Exercise 1.7.Give arguments for and against allowing the client requests to be executed concurrently by theserver. In the case that they are executed concurrently, give an example of possible ‘interference’that can occur between the operations of different clients. Suggest how such interference may beprevented.1.12 Ans.For concurrent executions - more throughput in the server (particularly if the server has to access a disk or another service)Against - problems of interference between concurrent operationsExample:Client A’s thread reads value of variable XClient B’s thread reads value of variable XClient A’s thread adds 1 to its value and stores the result in XClient B’s thread subtracts 1 from its value and stores the result in XResult: X := X-1; imagine that X is the balance of a bank account, and clients A and B are implementing credit and debit transactions, and you can see immediately that the result is incorrect.To overcome interference use some form of concurrency control. For example, for a Java server use synchronized operations such as credit and debit.1.13The ANSA Reference Manual [ANSA 1989] identified eight forms of transparency in a distributedsystem. Which are the two most important transparencies among these?1.13 Ans.The two most important transparencies are access and location transparency; their presence or absence most strongly affects the utilization of distributed resources. They are sometimes referred to together as network transparency.1.14One of the main standard technological components of web is the HyperText Transfer Protocol(HTTP), which defines the ways in which browsers and other types of clients interact with webservers. What are the different features of the HTTP?1.14 Ans.The main features of HTTP are:a.Request-reply interactionsb.Content typesc.One resource per requestd.Simple access control1.15What are the two main functions of an HTTP URL? Explain its general form. Identify the serverDNS name, path name, query, and fragment for the URL /search?q=sabretooth.1.15 Ans.An HTTP URL has two main jobs to do: to identify which web server maintains the resource, and to identify which of the resources at that server is required.In general, HTTP URLs are of the following form:http:// servername [:port] [/pathName] [?query][ #fragment]where items in square brackets are optional. A full HTTP URL always begins with the string ‘http://’followed by a server name, expressed as a Domain Name System (DNS) name. The server’s DNS name is optionally followed by the number of the ‘port’ on which the server listens for requests.Then comes an optional path name of the server’s resource. If this is absent then the server’s default web page is required. Finally, the URL optionally ends in a query component – for example, when a user submits the entries in a form such as a search engine’s query page – and/or a fragment identifier, which identifies a component of the resource.In the URL /search?q=sabretoothThe Server DNS name is The Path name is searchThe Query is q= sabretoothThere is no Fragment.。
分布式系统概念与设计(第三版)课后习题与答案Chapter15
Chapter 15Solutions15.1Outline a system to support a distributed music rehearsal facility. Suggest suitable QoSrequirements and a hardware and software configuration that might be used.15.1 Ans..This is a particularly demanding interactive distributed multimedia application. Konstantas et al. [1997] report that a round-trip delay of less than 50 ms is required for it. Clearly, video and sound should be tightly synchronized so that the musicians can use visual cues as well as audio ones. Bandwidths should be suitable for the cameras and audio inputs used, e.g. 1.5 Mbps for video streams and 44 kbps for audio streams. Loss rates should be low, but not necessarily zero.The QoS requirements are much stricter than for conventional videoconferencing – music performance is impossible without strict synchronization. A software environment that includes QoS management with resource contracts is required. The operating systems and networks used should provide QoS guarantees. Few general-purpose OS’s provide them at present. Dedicated real-time OS’s are available but they are difficult to use for high-level application development.Current technologies that should be suitable:•ATM network.•PC’s with hardware for MPEG or MJPEG compression.•Real-time OS with support for high-level software development, e.g. in CORBA or Java.15.2The Internet does not currently offer any resource reservation or quality of service managementfacilities. How do the existing Internet-based audio and video streaming applications achieveacceptable quality? What limitations do the solutions they adopt place on multimediaapplications?15.2 Ans..There are two types of Internet-based applications:a)Media delivery systems such as music streaming, Internet radio and TV applications.b)Interactive applications such as Internet phone and video conferencing (NetMeeting, CuSeemMe).For type (a), the main technique used is traffic shaping, and more specifically, buffering at the destination.Typically, the data is played out some 5–10 seconds after its delivery at the destination. This masks the uneven latency and delivery rate (jitter) of Internet protocols and masks the delays incurred in the network and transport layers of the Internet due to store-and-forward transmission and TCP’s reliability mechanisms.For type (b), the round trip delay must be kept below 100 ms so the above technique is ruled out. Instead, stream adaptation is used. Specifically, video is transmitted with high levels of compression and reduced frame rates. Audio requires less adaptation. UDP is generally used.Overall, type (a) systems work reasonably well for audio and low-resolution video only. For type (b) the results are usually unsatisfactory unless the network routes and operating system priorities are explicitly managed.15.3Explain the distinctions between the three forms of synchronization (synchronous distributedstate, media synchronization and external synchronization) that may be required in distributedmultimedia applications. Suggest mechanisms by which each of them could be achieved, forexample in a videoconferencing application.15.3 Ans..synchronous distributed state: All users should see the same application state. For example, the results of operation on controls for a video, such as start and pause should be synchronized, so that all users see the same frame. This can be done by associating the current state (sample number) of the active multimedia streams with each state-change message. This constitutes a form of logical vector timestamp.media synchronization: Certain streams are closely coupled. E.g. the audio that accompanies a video stream.They should be synchronised using timestamps embedded in the media data.external synchronization: This is really an instance of synchronous distributed state. The messages that update shared whiteboards and other shared objects should carry vector timestamps giving the states of media streams.15.4Outline the design of a QoS manager to enable desktop computers connected by an ATM networkto support several concurrent multimedia applications. Define an API for your QoS manager,giving the main operations with their parameters and results.15.4 Ans..Each multimedia application requires a resource contract for each of its multimedia streams. Whenever a new stream is to be started, a request is made to the QoS manager specifying CPU resources, memory and network connections with their Flow Specs. The QoS manager performs an analysis similar to Figure 15.6 for each end-to-end stream. If several streams are required for a single application, there is a danger of deadlock – resources are allocated for some of the streams, but the needs of the remaining streams cannot be satisfied. When this happens, the QoS negotiation should abort and restart, but if the application is already running, this is impractical, so a negotiation takes place to reduce the resources of existing streams.API:QoSManager.QoSRequest(FlowID, FlowSpec) –> ResourceContractThe above is the basic interface to the QoS Manager. It reserves resources as specified in the FlowSpec and returns a corresponding ResourceContract.A FlowSpec is a multi-valued object, similar to Figure 15.8.A ResourceContract is a token that can be submitted to each of the resource handlers (CPU scheduler,memory manager, network driver, etc.).Application.ScaleDownCallback(FlowID, FlowSpec) -> AcceptRejectThe above is a callback from the QoS Manager to an application, requesting a change in the FlowSpec fora stream. The application can return a value indicating acceptance or rejection.15.5In order to specify the resource requirements of software components that process multimediadata, we need estimates of their processing loads. How should this information be obtained?15.5 Ans..The main issue is how to measure or otherwise evaluate the resource requirements (CPU, memory, network bandwidth, disk bandwidth) of the components that handle multimedia streams without a lot of manual testing.A test framework is required that will evaluate the resource utilization of a running component. But there isalso a need for resource requirement models of the components – so that the requirements can be extrapolated to different application contexts and stream characteristics and different hardware environments (hardware performance parameters).15.6How does the Tiger system cope with a large number of clients all requesting the same movie atrandom times?15.6 Ans..If they arrive within a few seconds of each other, then they can be placed sufficiently close together in the schedule to take advantage of caching in the cubs, so a single disk access for a block can service several clients.If they are more widely spaced, then they are placed independently (in an empty slot near the disk holding he first block of the movie at the time each request is received). There will be no conflict for resources because different blocks of the movie are stored on different disks and cubs.15.7The Tiger schedule is potentially a large data structure that changes frequently, but each cub needsan up-to-date representation of the portions it is currently handling. Suggest a mechanism for thedistribution of the schedule to the cubs.15.7 Ans..In the first implementation of Tiger the controller computer was responsible for maintaining an up-to-date version of the schedule and replicating it to all of the cubs. This does not scale well – the processing and communication loads at the controller grow linearly with the number of clients – and is likely to limit the scale of the service that Tiger can support. In a later implementation, the cubs were made collectively responsible for maintaining the schedule. Each cub holds a fragment of the schedule – just those slots that it will be playing processing in the near future. When slots have been processed they are updated to show the current viewer state and then they are passed to the next ‘downstream’ cub. Cubs retain some extra fragments for fault-tolerance purposes.When the controller needs to modify the schedule – to delete or suspend an existing entry or to insert a viewer into an empty slot – it sends a request to the cub that is currently responsible for the relevant fragment of the schedule to make the update. The cub then uses the updated schedule fragment to fulfil its responsibilities and passes it to the next downstream cub.15.8When Tiger is operating with a failed disk or cub, secondary data blocks are used in place ofmissing primaries. Secondary blocks are n times smaller than primaries (where n is the declusterfactor), how does the system accommodate this variability in block size?15.8 Ans..Whether they are large primary or smaller secondary blocks, they are always identified by a play sequence number. The cubs simply deliver the blocks to the clients in order via the ATM network. It is the clients’responsibility to assemble them in the correct sequence and then to extract the frames from the incoming sequence of blocks and play the frames according to the play schedule.。
分布式系统复习题与参考答案(答案完全版)
关于分布式系统复习题与参考答案一、填空题(每题n分,答错个扣分,全错全扣,共计m分)1.下面特征分别属于计算机网络和分布式计算机系统,请加以区别:分布式计算机是指系统内部对用户是完全透明的;系统中的计算机即合作又自治;系统可以利用多种物理和逻辑资源,可以动态地给它们分配任务。
计算机网络是指互连的计算机是分布在不同地理位置的多台独立的“自治计算机”。
2.点到点通信子网的拓扑结构主要有以下几种:星型、环型、树型、网状型,请根据其特征填写相应结构。
网状型:结点之间的连接是任意的,没有规律。
环型:节点通过点到点通信线路连接成闭合环路。
星型:节点通过点到点通信线路与中心结点相连;树型:结点按层次进行连接。
3.分布式计算系统可以分为两个子组,它们是集群计算系统和网格计算系统。
4.分布式事务处理具有4个特性,原子性:对外部来说,事务处理是不可见的;一致性:事务处理不会违反系统的不变性;独立性:并发的事务处理不会相互干扰;持久性:事务处理一旦提交,所发生的改变是永久性的。
5.网络协议有三要素组成,时序是对事件实现顺序的详细说明;语义是指需要发出何种控制信息,以及要完成的动作与作出的响应;语法是指用户数据与控制信息的结构与格式6.根据组件和连接器的不同,分布式系统体系结构最重要的有4种,它们是:分层体系结构、基于对象的体系结构、以数据为中心的体系结构、基于事件的体系结构7.在客户-服务器的体系结构中,应用分层通常分为3层,用户接口层、处理层和数据层。
8.有两种类型的分布式操作系统,多处理器操作系统和多计算机操作系统。
9.软件自适应的基本技术有3种,一是要点分离、二是计算映像、三是基于组件的设计。
10.DCE本身是由多个服务构成的,常用的有分布式文件系统、目录服务、安全服务以及分布式时间服务等。
11.TCP/IP体系结构的传输层上定义的两个传输协议为传输控制协议(TCP)和用户数据报协议(UDP)。
12.Windows NT的结构借用了层次模型和客户/服务器两种模型。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Chapter 5Exercise Solutions5.1The Election interface provides two remote methods:vote: with two parameters through which the client supplies the name of a candidate (a string) and the‘voter’s number’ (an integer used to ensure each user votes once only). The voter’s numbers areallocated sparsely from the range of integers to make them hard to guess.result: with two parameters through which the server supplies the client with the name of a candidateand the number of votes for that candidate.Which of the parameters of these two procedures are input and which are output parameters?5.1 Ans.vote: input parameters: name of candidate, voter’s number;result: output parameters: name of candidate, number of votes5.2Discuss the invocation semantics that can be achieved when the request-reply protocol isimplemented over a TCP/IP connection, which guarantees that data is delivered in the order sent,without loss or duplication. Take into account all of the conditions causing a connection to bebroken.5.2 Ans.A process is informed that a connection is broken:•when one of the processes exits or closes the connection.•when the network is congested or fails altogetherTherefore a client process cannot distinguish between network failure and failure of the server.Provided that the connection continues to exist, no messages are lost, therefore, every request will receive a corresponding reply, in which case the client knows that the method was executed exactly once.However, if the server process crashes, the client will be informed that the connection is broken and the client will know that the method was executed either once (if the server crashed after executing it) or not at all (if the server crashed before executing it).But, if the network fails the client will also be informed that the connection is broken. This may have happened either during the transmission of the request message or during the transmission of the reply message. As before the method was executed either once or not at all.Therefore we have at-most-once call semantics.5.3Define the interface to the Election service in CORBA IDL and Java RMI. Note that CORBA IDLprovides the type long for 32 bit integers. Compare the methods in the two languages forspecifying input and output arguments.5.3 Ans.CORBA IDL:interface Election {void vote(in string name, in long number);void result(out string name, out long votes);};Java RMIWe need to define a class for the result e.g.class Result {String name;int votes;}The interface is:import java.rmi.*;public interface Election extends Remote{void vote(String name, int number) throws RemoteException;Result result () throws RemoteException;};This example shows that the specification of input arguments is similar in CORBA IDL and Java RMI.This example shows that if a method returns more than one result, Java RMI is less convenient than CORBA IDL because all output arguments must be packed together into an instance of a class.5.4The Election service must ensure that a vote is recorded whenever any user thinks they have casta vote.Discuss the effect of maybe call semantics on the Election service.Would at-least-once call semantics be acceptable for the Election service or would yourecommend at-most-once call semantics?5.4 Ans.Maybe call semantics is obviously inadequate for vote! Ex 5.1 specifies that the voter’s number is used to ensure that the user only votes once. This means that the server keeps a record of who has voted. Therefore at-least-once semantics is alright, because any repeated attempts to vote are foiled by the server.5.5 A request-reply protocol is implemented over a communication service with omission failures toprovide at-least-once RMI invocation semantics. In the first case the implementor assumes anasynchronous distributed system. In the second case the implementor assumes that the maximumtime for the communication and the execution of a remote method is T. In what way does the latterassumption simplify the implementation?5.5 Ans.In the first case, the implementor assumes that if the client observes an omission failure it cannot tell whether it is due to loss of the request or reply message, to the server having crashed or having taken longer than usual.Therefore when the request is re-transmitted the client may receive late replies to the original request. The implementation must deal with this.In the second case, an omission failure observed by the client cannot be due to the server taking too long.Therefore when the request is re-transmitted after time T, it is certain that a late reply will not come from the server. There is no need to deal with late replies5.6Outline an implementation for the Election service that ensures that its records remain consistentwhen it is accessed concurrently by multiple clients.5.6 Ans.Suppose that each vote in the form {String vote, int number} is appended to a data structure such as a Java Vector. Before this is done, the voter number in the request message must be checked against every voterecorded in the Vector. Note that an array indexed by voter’s number is not a practical implementation as the numbers are allocated sparsely.The operations to access and update a Vector are synchronized, making concurrent access safe.Alternatively use any form of synchronization to ensure that multiple clients’ access and update operations do not conflict with one another.5.7The Election service must ensure that all votes are safely stored even when the server processcrashes. Explain how this can be achieved with reference to the implementation outline in youranswer to Exercise 5.6.5.7 Ans.The state of the server must be recorded in persistent storage so that it can be recovered when the server is restarted. It is essential that every successful vote is recorded in persistent storage before the client request is acknowledged.A simple method is to serialize the Vector of votes to a file after each vote is cast.A more efficient method would append the serialized votes incrementally to a file.Recovery will consist of de-serializing the file and recreating a new vector.5.8Show how to use Java reflection to construct the client proxy class for the Election interface. Givethe details of the implementation of one of the methods in this class, which should call the methoddoOperation with the following signature:byte [] doOperation (RemoteObjectRef o, Method m, byte[] arguments);Hint: an instance variable of the proxy class should hold a remote object reference (see Exercise 4.12).5.8 Ans.Use classes Class and Method. Use type RemoteObjectRef as type of instance variable. The class Class has method getMethod whose arguments give class name and an array of parameter types. The proxy’s vote method, should have the same parameters as the vote in the remote interface - that is: two parameters of type String and int. Get the object representing the vote method from the class Election and pass it as the second argument of doOperation. The two arguments of vote are converted to an array of byte and passed as the third argument of doOperation.import ng.reflect;class VoteProxy {RemoteObjectRef ref;private static Method voteMethod;private static Method resultMethod;static {try {voteMethod = Election.class.getMethod ("vote", new Class[]{ng.String.class,int.class}));resultMethod = Election.class.getMethod ("result", new Class[] {}));}catch(NoSuchMethodException){}}public void vote (String arg1, int arg2) throws RemoteException {try {byte args [] = // convert arguments arg1 and arg2 to an array of bytesbyte result = DoOperation(ref, voteMethod, args);return ;} catch (...) {}}5.9Show how to generate a client proxy class using a language such as C++ that does not supportreflection, for example from the CORBA interface definition given in your answer to Exercise 5.3.Give the details of the implementation of one of the methods in this class, which should call themethod doOperation defined in Figure 4.12.5.9 Ans.Each proxy method is generated from the signature of the method in the IDL interface,e.g.void vote(in string name, in long number);An equivalent stub method in the client language e.g. C++ is produced e.g.void vote(const char *vote, int number)Each method in the interface is given a number e.g. vote = 1, result = 2.use char args[length of string + size of int] and marshall two arguments into this array and call doOperation as follows:char * result = DoOperation(ref, 1, args);we still assume that ref is an instance variable of the proxy class. A marshalling method is generated for each argument type used.5.10Explain how to use Java reflection to construct a generic dispatcher. Give Java code for adispatcher whose signature is:public void dispatch(Object target, Method aMethod, byte[] args)The arguments supply the target object, the method to be invoked and the arguments for thatmethod in an array of bytes.5.10 Ans.Use the class Method. To invoke a method supply the object to be invoked and an array of Object containing the arguments. The arguments supplied in an array of bytes must be converted to an array of Object.public void dispatch(Object target, Method aMethod, byte[] args)throws RemoteException {Object[] arguments = // extract arguments from array of bytestry{aMethod.invoke(target, arguments);catch(...){}}5.11Exercise 5.8 required the client to convert Object arguments into an array of bytes before invokingdoOperation and Exercise 5.10 required the dispatcher to convert an array of bytes into an arrayof Object s before invoking the method. Discuss the implementation of a new version ofdoOperation with the following signature:Object [] doOperation (RemoteObjectRef o, Method m, Object[] arguments);which uses the ObjectOutputStream and ObjectInputStream classes to stream the request and replymessages between client and server over a TCP connection. How would these changes affect thedesign of the dispatcher?5.11 Ans.The method DoOperation sends the invocation to the target’s remote object reference by setting up a TCP connection (as shown in Figures 4.5 and 4.6) to the host and port specified in ref. It opens an ObjectOutputStream and uses writeObject to marshal ref, the method, m and the arguments by serializing them to an ObjectOutputStream. For the results, it opens an ObjectIntputStream and uses readObject to get the results from the stream.At the server end, the dispatcher is given a connection to the client and opens an ObjectIntputStream and uses readObject to get the arguments sent by the client. Its signature will be:public void dispatch(Object target, Method aMethod)5.12 A client makes remote procedure calls to a server. The client takes 5 milliseconds to compute thearguments for each request, and the server takes 10 milliseconds to process each request. The localoperating system processing time for each send or receive operation is 0.5 milliseconds, and thenetwork time to transmit each request or reply message is 3 milliseconds. Marshalling orunmarshalling takes 0.5 milliseconds per message.Calculate the time taken by the client to generate and return from two requests:(i)if it is single-threaded, and(ii)if it has two threads that can make requests concurrently on a single processor.You can ignore context-switching times. Is there a need for asynchronous RPC if client and serverprocesses are threaded?5.12 Ans.i) time per call = calc. args + marshal args + OS send time + message transmission +OS receive time + unmarshall args + execute server procedure+ marshall results + OS send time + message transmission +OS receive time + unmarshal args= 5 + 4*marshal/unmarshal + 4*OS send/receive + 2*message transmission + execute server procedure = 5+ 4*0.5 + 4*0.5 + +2*3 + 10 ms = 5+2+2+6+10 =25ms.Time for two calls = 50 ms.ii) threaded calls:client does calc. args + marshal args + OS send time (call 1) = 5+.5=.5 = 6then calc args + marshal args + OS send time (call 2) = 6= 12 ms then waits for reply from first callserver gets first call aftermessage transmission + OS receive time + unmarshal args = 6+ 3+.5+.5= 10 ms, takes 10+1 to execute, marshal, send at 21 msserver receives 2nd call before this, but works on it after 21 ms taking10+1, sends it at 32 ms from startclient receives it 3+1 = 4 ms later i.e. at 36 ms(message transmission + OS receive time + unmarshal args) laterTime for 2 calls = 36 ms.5.13Design a remote object table that can support distributed garbage collection as well as translatingbetween local and remote object references. Give an example involving several remote objects andproxies at various sites to illustrate the use of the table. Show what happens when an invocationcauses a new proxy to be created. Then show what happens when one of the proxies becomesunreachable.5.13 Ans..local reference remote reference holdersThe table will have three columns containing the local reference and the remote reference of a remote object and the virtual machines that currently have proxies for that remote object. There will be one row in the table for each remote object exported at the site and one row for each proxy held at the site.To illustrate its use, suppose that there are 3 sites with the following exported remote objects:S1: A1, A2, A3S2: B1, B2;S3: C1;and that proxies for A1 are held at S2 and S3; a proxy for B1 is held at S3.Then the tables hold the following information:.at S1at S2at S3local remote holders local remote holders local remote holdersa1A1S2, S3b1B1S3c1C1a2A2b2B2a1A1proxya3A3a1A1proxy b1B1proxy Now suppose that C1(at S3) invokes a method in B1 causing it to return a reference to B2. The table at S2 adds the holder S3 to the entry for B2 and the table at S3 adds a new entry for the proxy of B2.Suppose that the proxy for A1 at S3 becomes unreachable. S3 sends a message to S1 and the holder S3 is removed from A1. The proxy for A1 is removed from the table at S3.5.14 A simpler version of the distributed garbage collection algorithm described in Section 5.2.6 justinvokes addRef at the site where a remote object lives whenever a proxy is created and removeRefwhenever a proxy is deleted. Outline all the possible effects of communication and process failureson the algorithm. Suggest how to overcome each of these effects, but without using leases.5.14 Ans.AddRef message lost - the owning site doesn’t know about the client’s proxy and may delete the remote object when it is still needed. (The client does not allow for this failure).RemoveRef message lost - the owning site doesn’t know the remote object has one less user. It may continue to keep the remote object when it is no longer needed.Process holding a proxy crashes - owning site may continue to keep the remote object when it is no longer needed.Site owning a remote object crashes. Will not affects garbage collection algorithmLoss of addRef is discussed in the Section 5.2.6.When a removeRef fails, the client can repeat the call until either it succeeds or the owner’s failure has been detected.One solution to a proxy holder crashing is for the owning sites to set failure detectors on holding sites and then remove holders after they are known to have failed.5.15Discuss how to use events and notifications as described in the Jini distributed event specificationin the context of the shared whiteboard application. The RemoteEvent class is defined as followsin Arnold et al. [1999].public class RemoteEvent extends java.util.EventObject {public RemoteEvent(Object source, long eventID,long seqNum, MarshalledObject handback)public Object getSource () {…}public long getID() {…}public long getSequenceNumber() {…}public MarshalledObject getRegistrationObject() {…}}The first argument of the constructor is a remote object. Notifications inform listeners that an eventhas occurred but the listeners are responsible for obtaining further details.5.15 Ans.Event identifier,. evID s. Decided by the EventGenerator. Simplest solution is just to have one type of event -the addition of a new GraphicalObject. Other event types could for example refer to deletion of a GraphicalObject.Clients need to be notified of the remote object reference of each new GraphicalObject that is added to the server. Suppose that an object in the server is the EventGenerator. It could implement the EventGenerator interface and provide the register operation, or it could be done more simplye.g. addListener(RemoteEventListener listener, long evID)// add this listener to a vector of listenersThis would be better if Leases were used to avoid dealing with lost clients.The newShape method of shapeListServant (Figure 5.14) could be the event generator. It will notify all of the EventListeners that have registered with it, each time a new GraphicalObject is added. e.g.RemoteEvent event = new RemoteEvent(this, ADD_EVENT, version, null)for all listeners in the vectorlistener.notify(event)Each client creates an RemoteEventListener for receiving notifications of events and then registers interest in events with the server, passing the EventListener as argument.class MyListener implements RemoteEventListener {public MyListener() throws RemoteException[}public void notify(RemoteEvent event) throws UnknownEventException,RemoteException {Object source = getSource();long id = event.getID();long version = event.getSequenceNumber();// get the newly created GraphicalObject from the server}}Then to become a listener (add the following to the client program shown in Figure 5.15):sList.addListener(new MyListener(), ADD_EVENT);The client getting the newGraphicalObject needs to be able to get it directly from the version number, rather than by getting the list of Shapes and then getting the GraphicalObject. The interface to ShapeList could be amended to allow this.5.16Suggest a design for a notification mailbox service which is intended to store notifications onbehalf of multiple subscribers, allowing subscribers to specify when they require notifications tobe delivered. Explain how subscribers that are not always active can make use of the service youdescribe. How will the service deal with subscribers that crash while they have delivery turned on?5.16 Ans.The Mailbox service will provide an interface allowing a client to register interest in another object. The client will need to know the RemoteEventListener provided by the Mailbox service so that notifications may be passed from event generators to the RemoteEventListener and then on to the client. The client will also need a means of interacting with the Mailbox service so as to turn delivery on and off. Therefore define register as follows:Registration register() ...The result is a reference to a remote object whose methods enable the client to get a reference to a RemoteEventListener and to turn delivery on and off.To use the Mailbox service, the client registers with it and receives a Registration object, which it saves in a file. It registers the RemoteEventListener provided by the Mailbox service with all of the EventGenerators whose events it wants to have notification of. If the client crashes, it can restore the Registration object when it restarts. Whenever it wants to receive events it turns delivery on and when it does not want them it turns delivery off.The design should make it possible to specify a lease for each subscriber.5.17Explain how a forwarding observer may be used to enhance the reliability and performance ofobjects of interest in an event service.5.17 Ans.Reliability:The forwarding observer can retry notifications that fail at intervals of time.If the forwarding observer is on the same computer as the object of interest, then the two could not fail independently.Performance:The forwarding observer can optimize multicast protocols to subscribers.In Jini it could deal with renewing leases.5.18Suggest ways in which observers can be used to improve the reliability or performance of yoursolution to Exercise 5.13.5.18 Ans.The server can be relieved of saving information about all of the clients’ interests by creating a forwarding agent on the same computer. the forwarding agent could use a multicast protocol to send notifications to the clients. IP multicast would do since it is not crucial that every notification be received. A missed version number can be rectified as soon as another one is received.。