Morgan Stanley(摩根斯坦利)笔试加电面试题大全

1经历了两次网上测试和两次电面,发现网上测试和电面题目都是不变的,电面题目相当固定,具体试题如下:

(当时精心准备了所有的电面试题,整理出了两个word文档,有很多图片辅助理解,现在将重要内容写到这里,图片就不贴上来了,有需要的可以回复)

电面分若干小题与一道设计大题,小题都是考一些小知识点,如面向对象编程基础,大题两次电面都是一个题目,会议室预定的数据库设计,每个表包含哪些属性等,比较基础

电面试题

1.Index

Data structure,stores the valueof specific colum in table,pointer to the row in table,allow for fasterretreaval of data in database,speed up search query.

Hash index,not orderd,compare for equalitybut not for inequality.

B-tree, allows logarithmic selections,insertions, and deletions in the worst case scenario. And unlike hash indexesit stores the data in an ordered way, allowing for faster row retrieval whenthe selection conditions include things like inequalities or prefixes.

2.stack vs heap

Stack:static;compile time;LIFO order;memorymanagement automatically;access fast;

Know how much data before compile,not toomuch;

Heap:dynamic;run time;slower;size Islimited on virtual memory;allocat and free at any time;

3.thread vs process

Thread:run in shared memory space;easier tocreate and terminate;lightweight;faster task-switching;data sharing with otherthread;care synchronization overhead of shared data;

Process:separate memory space;independentof each other;consist of mutipule thread

4.Garbage Collection (GC)

Mark:reffrence counting and reachability analysis;

Clean up:sweep(hace fragment,old),coping(no fragment,eden),compact(nofragment,difficult to concurrent)

Gennerational:(young:coping,old:mark-sweep/compact,permenant:class,const,staticvariable,method)

CMS: Initial Mark, Concurrent Mark, Remark, Concurrent Sweep

5. Interface Vs Abstract method

Abstract method:constants,members,methodstubs,defined method;any visibility;single class;chile class, with the same orless restrictive visibility

Interface:const,methodstubs;public;multipul interface;child interface,same visibility;

6.sql join

INNER JOIN: Returns all rows when there isat least one match in BOTH tables

LEFT JOIN: Return all rows from the lefttable, and the matched rows from the right table

RIGHT JOIN: Return all rows from the righttable, and the matched rows from the left table

FULL JOIN: Return all rows when there is amatch in ONE of the tables

7. virtual method and inheritance

Inheritance allows us to define a class in terms of another class, which makesit easier to create and maintain an application. This also provides anopportunity to reuse the code functionality and fast implementation time.

8. Primary key and foreign key

PK:duplicated values not allowed;notnull;only one in a table;

FK:duplicated;null;one or more in a table;

9. copy constructor and assignment operator

copy constructor :Initialize a previous un-initialized object with the data of otherexist object;

assignment operator: replace the data of a previously initialized object with some otherobject's data

 

 

10.pointer and reference

Pointer:1.can bere-assign many times;2.can point to null;3.has its own memory address and sizeon stack;4.can have pointer to pointers to pointers offering extra levels ofindirection

Reference;1.can’t bere-seated after binding;2.always refer to an object;3.share the same memoryspace with origin object;4.only one level indirection

11.polymorphsim

Polymorphism is when you can treat anobject as a generic version of something, but when you access it, the codedetermines which exact type it is and calls the associated code

 polymorphism is the ability (in programming)to present the same interface for differing underlying forms (data types).

12. what is staticmethod? 

A static method is amethod that can be called on a class and usually does not require the class tobe instantiated.

13.what's thedifference between TCP and UDP?

Reliability: TCP is connection-orientedprotocol.   

Reliability: UDP is connectionlessprotocol.

Ordered: don’t have to worry about dataarriving in the wrong order. 

Ordered: If you send two messages out, youdon’t know what order they’ll arrive in i.e. no ordered

Heavyweight:

Lightweight: No ordering of messages, notracking connections,

Streaming: Data is read as a “stream,” withnothing distinguishing where one packet ends and Datagrams: Packets are sentindividually and are guaranteed to be whole if they arrive. One packet

14. Smart pointer

A smart pointer is a class that wraps a'raw' (or 'bare') C++ pointer, to manage the lifetime of the object beingpointed to

Reference counted pointers are very usefulwhen the lifetime of your object is much more complicated, and is not tieddirectly to a particular section of code or to another object.

15.Exception and Error

Errors tend to signal the end of yourapplication as you know it. It typically cannot be recovered from and shouldcause your VM to exit. Catching them should not be done except to possibly logor display and appropriate message before exiting.

Example: OutOfMemoryError - Not much you can do as your program can no longer run.

Exceptions are often recoverable and evenwhen not, they generally just mean an attempted operation failed, but yourprogram can still carry on.

Example: IllegalArgumentException - Passed invalid data to a method so that method call failed, but itdoes not affect future operations.

16. Sleep() VS wait()

Sleep:Thread类的静态方法,虽然休眠,但是锁并未释放,是当前线程进入停滞状态,让出cpu

Wait:object类的方法,进入等待池中,释放对象的锁;使用notify或notify all 唤醒等待池中的线程。Wait必须放在synchronize Blocking中,否则runtime 抛出illegalMonitorStateException。

 

 

17.C++ vs C

1C is a structural or proceduralprogramming language.

C++ is an object oriented programminglanguage.

2Functions are the fundamental buildingblocks.

Objects are the fundamental buildingblocks.

3In C, the data is not secured.

Data is hidden and can’t be accessed byexternal functions.

4C uses scanf() and printf() function forstandard input and output.

C++ uses cin>> and cout<< forstandard input and output.

5. C doesn’t support exception handlingdirectly. Can be done by using some other functions.

C++ supports exception handling. Done byusing try and catch block.

6. Features like function overloading andoperator overloading is not present.

C++ supports function overloading andoperator overloading.

18. diffrence between Java and C++

Garbage collection/delete

1.Everything must be in a class. There areno global functions or global data. If you want the equivalent of globals, makestatic methods andstatic data within a class. There are no structs orenumerations or unions, only classes.

2.Write once, run anywhere, but it's stillmuch easier than writing a C++ cross-platform code.

3.C++ supports multiple class inheritance,while Java only gives you a single class inheritance, but solves themultiplicity via interfaces.

4.C++ has got a pointers, and can directlymanipulate/violate the memory addresses.

5.At compilation time Java Source codeconverts into byte code .The interpreter execute this byte code at run time andgives output .Java is interpreted for the most part and hence platformindependent. C++ run and compile using compiler which converts source code intomachine level languages so c++ is plate from dependents

Java uses compiler and interpreter both andin c++ their is only compiler

C++ supports operator overloading multipleinheritance but java does not.

C++ is more nearer to hardware then Java

Everything (except fundamental types) is anobject in Java (Single root hierarchy as everything gets derived fromjava.lang.Object).

Java does is a similar to C++ but not haveall the complicated aspects of C++ (ex: Pointers, templates, unions, operatoroverloading, structures etc..) Java does not support conditional compile(#ifdef/#ifndef type).

Thread support is built-in Java but not inC++. C++11, the most recent iteration of the C++ programming language does haveThread support though.

Internet support is built-in Java but notin C++. However c++ has support for socket programming which can be used.

Java does not support header file, includelibrary files just like C++ .Java use import to include different Classes andmethods.

Java does not support default argumentslike C++.

There is no scope resolution operator :: inJava. It has . using which we can qualify classes with the namespace they camefrom.

There is no goto statement in Java.

Exception and Auto Garbage Collectorhandling in Java is different because there are no destructors into Java.

Java has method overloading, but nooperator overloading just like c++.

The String class does use the + and +=operators to concatenate strings and String expressions use automatic typeconversion,

Java is pass-by-value.

Java does not support unsigned integer

19.privateconstructor:

1.    The constructor can only be accessedfrom static factory method inside the class itself.Singleton can also belong to this category.

2.    A utility class, that only contains static methods.

Protected constructor

When a class is (intended as) an abstractclass, a protected constructor is exactly right. In that situation you don'twant objects to be instantiated from the class but only use it to inherit from.

There are other uses cases, like when acertain set of construction parameters should be limited to derived classes.

20sql注入injection

submit a database SQL command that is executed by a webapplication,exposing the back-end database. A SQL injection attack can occurwhen a web applicationutilizes user-supplied data without proper validation orencoding as part of a command or query

·        when data entered by users issent to the SQL interpreter as a part of a SQL query.

·        Attackers provide speciallycrafted input data to the SQL interpreter and trick the interpreter to executeunintended commands.

·        A SQL injection attack exploitssecurity vulnerabilities at the database layer. By exploiting the SQL injectionflaw, attackers can create, read, modify or delete sensitive data.

Preventing SQL Injection

·        Youcan prevent SQL injection if you adopt aninput validation technique in which user input isauthenticated against a set of defined rules for length, type and syntax and also against businessrules.

Youshould ensure that userswith the permission to access the database have the least privileges.

·        Usestrongly typed parameterized query APIs with placeholder substitution markers, even when calling storedprocedures.

21.Multithread designpattern(多线程设计模式)

Single Threaded Execution: 只允许单个线程执行对象的某个方法,以保护对象的多个状态。

实现时需用synchronized修饰引用受保护的状态的方法,这样就只能有单个线程访问该方法,其它线程由于不能获取锁而等待。但是用synchronized保护变量也带来了性能问题,因为获取锁需要时间,并且如果多个线程竞争锁的话,会让某些线程进入这个锁的条件队列,暂停执行,这样会降低性能。

Immutable: 如果状态根本不会发生变化,就不需要用锁保护,这就是Immutable模式。

Person类用final修饰,防止被继承。_name_address都用final修饰,防止被修改,只能在定义时初始化,或者在构造器里初始化,Person类也只提供了对这些状态字段的get方法,

Guarded Suspension:

当我们调用对象某个的某个方法时,可能对象当前状态并不满足执行的条件,于是需要等待,这就是GuardedSuspension模式。只有当警戒条件满足时,才执行,否则等待,另外对象必须有改变其状态的方法。

Balking: Balking模式与Guarded Suspension模式相似,都是在对象状态不符合要求时需要进行一些处理,不过Guared Suspension在状态不满足要求时,会等待并阻塞线程,而Balking模式是直接返回,并不等待。调用者可暂时先做别的工作,稍后再来调用该对象的方法。

不想等待警戒条件成立时,适合使用Balking模式。

警戒条件只有第一次成立时,适合使用Balking模式。

Producer-Consumer: 在该模式里可能有多个生产者,多个消费者,生产者和消费者都有独立的线程。其中最关键的是放置数据的缓冲区,生产者和消费者在操作缓冲区时都必须同步,生产者往缓冲区放置数据时,如果发现缓冲区已满则等待,消费者从缓冲区取数据时如果发现缓冲区没有数据,也必须等待。当程序里有多个生产者角色或者多个消费者角色操作同一个共享数据时,适合用生产者消费者模式。比如下载模块,通常会有多个下载任务线程(消费者角色),用户点击下载按钮时产生下载任务(生产者角色),它们会共享任务队列。

Read-WriteLock: 先前的几个多线程设计模式里,操作共享数据时,不管如何操作数据一律采取互斥的策略(除了Immutable模式),即只允许一个线程执行同步方法,其它线程在共享数据的条件队列里等待,只有执行同步方法的线程执行完同步方法后被阻塞的线程才可在获得同步锁后继续执行。

这样效率其实有点低,因为读操作和读操作之间并不需要互斥,两个读线程可以同时操作共享数据,读线程和写线程同时操作共享数据会有冲突,两个写线程同时操作数据也会有冲突。

Deadlock

Mutualexclusion - Each resource is either currentlyallocated to exactly one process or it is available. (Two processes cannotsimultaneously control the same resource or be in their critical section).

Holdand Wait - processes currently holding resourcescan request new resources.

Nopreemption - Once a process holds a resource, itcannot be taken away by another process or the kernel.

Circularwait - Each process is waiting to obtain a resourcewhich is held by another process.

22.Desing pattern

FactoryMethod:

The Factory Method Pattern defines aninterface for creating an object, but lets subclasses decide which class toinstantiate. Factory Method lets a class defer instantiation to subclasses.

 

0. Programming

Index

Indexing is a way of sorting anumber of records on multiple fields. Creating an index on a field in a tablecreates another data structure which holds the field value, and pointer to therecord it relates to. This index structure is then sorted, allowing BinarySearches to be performed on it.

The downside to indexingis that these indexes require additional space on the disk,since the indexes are stored together in a table using the MyISAM engine, thisfile can quickly reach the size limits of the underlying file system if manyfields within the same table are indexed.

, the cardinality or uniqueness of the data isimportant. 

With such a low cardinality the effectivenessis reduced to a linear sort, and the query optimizer will avoid using the indexif the cardinality is less than 30% of the record number, effectively makingthe index a waste of space.

1.  Stack VS Heap 

Stack :

Static memory allocation

Don’t need to Manage the memory by ourselves, variable canbe allocated automaticlly

Access fast

Space is effient used,not fragment

Heap:

Dynamic memory allocation

Must manage the memory,in charge of allocating and freeingthe variables,or it maybe lead to memory leak.

Access slow

Space is not edffient

 

 

GarbageCollection

http://www.cnblogs.com/zhguang/p/3257367.html

http://blog.csdn.net/u014536596/article/details/49824659

Mark

引用计数算法(ReferenceCounting

可达性分析算法(ReachabilityAnalysis

  • 可以作为GC Roots的对象包括以下几类:
    • 虚拟机栈中引用的对象
    • 方法区中类静态属性引用的对象
    • 方法区中常量引用的对象
    • Native方法引用的对象

Clean Up

清理阶段。将Mark阶段标记出的不可用对象清除,释放其所占用的内存空间。主要有以下几种实现方式。

·        清除(Sweep

算法思想:遍历堆空间,将Mark阶段标记不可用的对象清除。
不足:效率不高;空间问题,多次清除之后会产生大量的内存碎片。
适用场景:对象寿命长的内存区域。

·        复制(Copying

算法思想:将内存划分为两个区域(大小比例可调整),每次只用其中一块,当此块内存用完时,就将存活对象复制到另一块内存中,并对当前块进行内存回收。
优点:解决了内存碎片问题;内存分配效率提高。每次复制后对象在堆中都是线性排列的,因此内存分配时只需移动堆顶指针即可。
不足:如果对象的存活率较高,大量的复制操作会显著的降低效率;内存空间浪费,每次都只能使用堆空间的一部分,代价高昂。

·        整理(Compacting

算法思想:将标记的所有可用对象向内存一端移动,然后直接清理边界以外的内存区域即可。
优点:类似于复制算法,解决了内存碎片问题,内存分配效率提高;消除了复制算法对内存空间的浪费。
不足:难以做到并行。

分代回收(Generational

前面所述的Mark-Clean算法都是针对整个堆区域的,每一次GC运行都需要对堆中所有的对象进行遍历。因此,随着堆中对象数量的增多,GC的效率就会随之下降。于是,GC对程序运行做出如下假设:

  • 大多数对象都会在创建后不久死亡
  • 如果对象已存活一段时间,那它很可能会继续存活一段时间

 

 

GC过程

1. new objects allocated eden space. Both survivor spaces startout empty.

2. When the eden space fills up, a minor garbage collection istriggered.

3. Referencedobjects are moved to the first survivor space. Unreferenced objects are deletedwhen the eden space is cleared.

4. At the next minor GC, the same thing happens for the edenspace. Unreferenced objects are deleted and referenced objects are moved to asurvivor space. However, in this case, they are moved to the second survivorspace (S1). In addition, objects from the last minor GC on the first survivorspace (S0) have their age incremented and get moved to S1. Once all survivingobjects have been moved to S1, both S0 and eden are cleared. Notice we now havedifferently aged object in the survivor space.

5. At the next minor GC, the same process repeats. However thistime the survivor spaces switch. Referenced objects are moved to S0. Survivingobjects are aged. Eden and S1 are cleared.

6. This slide demonstrates promotion. After a minor GC, when agedobjects reach a certain age threshold (15 in this example) they are promotedfrom young generation to old generation.

7. As minorGCs continue to occure objects will continue to be promoted to the oldgeneration space.

8. So that pretty much covers the entire process with the younggeneration. Eventually, a major GC will be performed on the old generationwhich cleans up and compacts that space.

两个最基本的java回收算法:复制算法和标记清理算法

复制算法:两个区域A和B,初始对象在A,继续存活的对象被转移到B。此为新生代最常用的算法

标记清理:一块区域,标记要回收的对象,然后回收,一定会出现碎片,那么引出

标记-整理算法:多了碎片整理,整理出更大的内存放更大的对象

两个概念:新生代和年老代

新生代:初始对象,生命周期短的

永久代:长时间存在的对象

整个java的垃圾回收是新生代和年老代的协作,这种叫做分代回收。

P.S:Serial New收集器是针对新生代的收集器,采用的是复制算法

        Parallel New(并行)收集器,新生代采用复制算法,老年代采用标记整理

        Parallel  Scavenge(并行)收集器,针对新生代,采用复制收集算法

       Serial Old(串行)收集器,新生代采用复制,老年代采用标记清理

        Parallel   Old(并行)收集器,针对老年代,标记整理

       CMS收集器,基于标记清理

       G1收集器:整体上是基于标记清理,局部采用复制

 

综上:新生代基本采用复制算法,老年代采用标记整理算法。cms采用标记清理。

 

优缺点:

The intention of GC is to reduce the difficulty in memory management and avoid sometypical memory related errors, i.e. ssegment fault, memory leak.

you can callGC.collect() to notify the GC to work, but there's no guarantee that the memorywill be recycled immediately. It alldepends on the complicated algorithm of GC, butunfortunately it is non-deterministic.

So, in anapplication which needs to manage memory very efficiently such as aserver using Gigabytes of memory,it should be able to allocate and releasememory in a deterministic manner,in this case GChurts. The common OOM issue in languages with GC is partly because unreferencedobjects pending for being collected still take a lot of memory, finally thesystem runs into OOM at a point. When OOM happens, it's even harder to resolvethan resolving memory issues in languages like C/C++.

GC also bringsnon-deterministic in latency.In real-time systemssuch as a stock trading system, latency is usually considered much moreimportant than throughput. The system should keep latency as lowas possible, butthe timing of GC is non-deterministic, it's notcontrolled by programmers too. When GC is executing, the latency canbe several orders of magnitude higher than that when it's idle. This kind ofbehavioris not acceptable in real-time systems because it needs to respond torequests with low and deterministic latency.

GC tuning into two.

  1. One is to minimize the number of objects passed to the old area;
  2. and the other is to decrease Full GC execution time.

 

3.Interface Vs Abstract method

The key technical differences betweenan abstractclass and an interface are:

·        Abstract classes can have constants, members, method stubs (methodswithout a body) and defined methods, whereas interfaces can only have constants and methods stubs.

·        Methods and members of an abstract classcan be defined with any visibility, whereas all methods of an interface must be definedas public (they are defined public by default).

·        When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an anabstract class can extend another abstract class and abstract methods from theparent class don't have to be defined.

·        Similarly, an interface extending another interfaceis not responsible for implementing methodsfrom the parentinterface. This is because interfaces cannot define any implementation.

·        A child class can only extend a single class (abstractor concrete), whereas an interface can extend or a class can implement multiple other interfaces.

·        A child class can define abstract methodswith the same or less restrictive visibility,whereas a class implementing an interface must define the methods with theexact same visibility (public).

 

3.   SQL JOIN

INNER JOIN: Returns all rows when there isat least one match in BOTH tables

LEFT JOIN: Return all rows from the lefttable, and the matched rows from the right table

RIGHT JOIN: Return all rows from the righttable, and the matched rows from the left table

FULL JOIN: Return all rows when there is amatch in ONE of the tables

 

4.   virtual method and inheritance

Inheritanceallows us to define a class in terms of another class, which makes it easier tocreate and maintain an application. This also provides an opportunity to reusethe code functionality and fast implementation time.

5.      Primary key and foreign key

copy constructor and assignment operator

Acopy constructor is used to initialize a previously uninitialized object fromsome other object's data.

Anassignment operator is used to replace the data of a previously initialized objectwith some other object's data.

7.Thread vs Process

Both processes and threads are independentsequences of execution. The main difference is thatthreads(of the same process) run in a shared memory space, while processes run inseparate memory spaces.

1.Threads are easierto create than processes since they don't require a separate addressspace.                             

2.Multithreading requires careful programming since threads share data strucuresthat should only be modified by one thread at a time.  Unlike threads, processes don't share thesame address space.

3.  Threads areconsidered lightweight because they use far less resources than processes.

4.  Processes areindependent of each other.  Threads, since they share the same addressspace are interdependent, so caution must be takenso that differentthreads don't step on each other.  Thisis really another way of stating #2 above.

5.  A process can consistof multiple threads.

Thread

Advantages:

·        Much quicker to create a thread than a process.

·        Much quicker to switch between threads than to switchbetween processes.

·        Threads share data easily

Consider few disadvantages too:

·        No security between threads.

·        One thread can stomp on another thread's data.

·        If one thread blocks, all threads in task block.

  • Doing background processing: Some tasks may not be time critical, but need to execute continuously.
  • Doing I/O work: I/O to disk or to network can have unpredictable delays.Threads allow you to ensure that I/O latency does not delay unrelated parts of your application.

 

Less overhead to establish and terminate vs.a process:because verylittle memory copying is required (just the thread stack), threads are fasterto start than processes. To start a process, the whole process area must beduplicated for the new process copy to start. While some operating systems onlycopy memory once it is modified (copy-on-write), this is not universallyguaranteed.

Faster task-switching: in many cases, it is faster for an operating systemto switch between threads for the active CPU task than it is to switch betweendifferent processes. The CPU caches and program context can be maintainedbetween threads in a process, rather than being reloaded as in the case ofswitching a CPU to a different process.

Data sharing with other threads in aprocess: for tasks thatrequire sharing large amounts of data, the fact that threads all share aprocess’s memory pool is very beneficial. Not having separate copies means thatdifferent threads can read and modify a shared pool of memory easily. Whiledata sharing is possible with separate processes through shared memory andinter-process communication, this sharing is of an arms-length nature and isnot inherently built into the process model.

Disadvantage

  • Synchronization overhead of shared data:shared data that is modified requires special handling in the form of locks, mutexes and other primitives to ensure that data is not being read while written, nor written by multiple threads at the same time.
  • Shared process memory space:all threads in a process share the same memory space. If something goes wrong in one thread and causes data corruption or an access violation, then this affects and corrupts all the threads in that process. This is a special concern for cross-language environments where it is very easy to have subtle ABI interaction problems, such as Java-based web servers calling upon native libraries via the JNI (Java Native Interface) ABI.
  • Program debugging: multi-threaded programs present difficulties in finding and resolving bugs over and beyond the normal difficulties of debugging programs. Synchronization issues, non-deterministic timing and accidental data corruption all conspire to make debugging multi-threaded programs an order of magnitude more difficult than single-threaded programs.

 multipleprocesses in a browser

 

8. pointer and reference

1.    A pointer can be re-assigned any numberof times while a reference can not be re-seated after binding.

2.    Pointers can point nowhere (NULL), whereas reference always refer to anobject.

3.    You can't take the address of areference like you can with pointers.

4.    There's no "referencearithmetics" (but you can take the address of an object pointed by areference and do pointer arithmetics on it as in &obj + 5).

5.A pointer has its own memory address and size onthe stack (4 bytes on x86), whereas a reference shares the same memory address(with the original variable)but also takesup some space on the stack.

6.You can have pointers to pointers to pointersoffering extra levels of indirection. Whereas references only offer one levelof indirection.

7 Pointers can iterate over an array, you can use ++ to go tothe next item that a pointer is pointing to, and + 4 to go to the 5th element.This is no matter what size the object is that the pointer points to.

8.A pointer needs to be dereferenced with * toaccess the memory location it points to, whereas a reference can be useddirectly. A pointer to a class/struct uses -> to access it's members whereasa reference uses a ..

9. A pointer is a variable that holds a memory address.Regardless of how a reference is implemented, a reference has the same memoryaddress as the item it references.

1

what is virtual method? inheritance ? 

2

what's the difference between primary keyand foreign key? 

3

what's the difference between copyconstructor and assignment operator?

4

what's the difference between process andthread ?

5

what's the difference between pointer andreference? 

6

what is polymorphism(多态

virtual table,

Polymorphism is when you can treat an object asa generic version of something, but when you access it, the code determineswhich exact type it is and calls the associated code

 polymorphism isthe ability (in programming) to present the same interface for differingunderlying forms (data types).

面试官会追着问的很细,看你是否真的了解

7

what is static method? 

A static variable is avariable that is shared across all instances of a class.

 

A static method is amethod that can be called on a class and usually does not require the class tobe instantiated.

8

what's the difference between TCP and UDP?

Reliability: TCP is connection-oriented protocol.When a file or message send it will get delivered unless connections fails. Ifconnection lost, the server will request the lost part. There is no corruptionwhile transferring a message.       Reliability: UDP is connectionless protocol.When youa send a data or message, you don’t know if it’ll get there, it could get loston the way. There may be corruption while transferring a message.

Ordered: If you send twomessages along a connection, one after the other, youknow the first message will get there first. You don’t have to worry about dataarriving in the wrong order.  Ordered: If you send two messages out, you don’t know whatorder they’ll arrive in i.e. no ordered

Heavyweight: – when the low level parts of the TCP “stream” arrive in the wrongorder, resend requests have to be sent, and all the out of sequence parts haveto be put back together, so requires a bit of work to piece together.    Lightweight:No ordering of messages, no tracking connections, etc. It’s just fire andforget! This means it’s a lot quicker, and the network card / OS have to dovery little work to translate the data back from the packets.

Streaming: Data is readas a “stream,” with nothing distinguishing where onepacket ends and another begins. There may be multiple packets per read call.        Datagrams:Packets are sent individually and are guaranteed to be whole if theyarrive. One packet per one read call.

10

what is singleton?

11

Do you know quick sort?

 

Smart pointer 

A smart pointer is a class that wraps a'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointedto

Reference counted pointersare very useful when the lifetime of your object is much more complicated, andis not tied directly to a particular section of code or to another object.

Drawback

the possibility of creating a dangling reference:

Another possibility is creating circularreferences:

·        Use std::unique_ptr when you're not planning multiplereferences to the same object. For example, for a pointer which gets allocatedon entering some scope and de-allocated on exiting the scope.

·        Use std::shared_ptr when you do want to refer to yourobject from multiple places - and do not want it to be de-allocated until allthese references are themselves gone.

·        Use std::weak_ptr when you do want to refer to your object frommultiple places - for those references for which it's ok to ignore anddeallocate (so they'll just note the object is gone when you try todereference).

 

Oneof the simple smart-pointer type is std::auto_ptr (chapter20.4.5 of C++ standard), which allows to deallocate memory automatically whenit out of scope and which is more robust than simple pointer usage whenexceptions are thrown, although less flexible.

Anotherconvenient type is boost::shared_ptr whichimplements reference counting and automatically deallocates memory when noreferences to object remains. This helps avoiding memory leaks and is easy touse to implement RAII.

 

Exception and Error

Errors tend to signal theend of your application as you know it. It typically cannot be recovered fromand should cause your VM to exit. Catching them should not be done except topossibly log or display and appropriate message before exiting.

Example:OutOfMemoryError -Not much you can do as your program can no longer run.

Exceptions are oftenrecoverable and even when not, they generally just mean an attempted operationfailed, but your program can still carry on.

Example:IllegalArgumentException -Passed invalid data to a method so that method call failed, but it does notaffect future operations.

Hashcode() and equals()

对象的hashcode再从Hash表中取这个对象。这样做的目的是提高取对象的效率。具体过程是这样:
1.new Object(),JVM根据这个对象的Hashcode,放入到对应的Hash表对应的Key,如果不同的对象确产生了相同的hash,也就是发生了Hash key相同导致冲突的情况,那么就在这个Hash key的地方产生一个链表,将所有产生相同hashcode的对象放到这个单链表上去,串在一起。
2.比较两个对象的时候,首先根据他们的hashcodehash表中找他的对象,当两个对象的hashcode相同,那么就是说他们这两个对象放在Hash表中的同一个key,那么他们一定在这个key上的链表上。那么此时就只能根据Objectequal方法来比较这个对象是否equal。当两个对象的hashcode不同的话,肯定他们不能equal.

实现一个自己的Map,首先考虑的是如何优化Hash算法,因为自己的Map应该会对应具体的类,可以根据自己类的属性,找出一种能提高查询效率的方法.如上一个例子.相当于 hashcode能为数组提供8个链路,这样速度大大提升.紧记0~8存储例子。

HashMap的数据结构是数组和链表的结合,所以我们当然希望这个HashMap里面的 元素位置尽量的分布均匀些,尽量使得每个位置上的元素数量只有一个,那么当我们用hash算法求得这个位置的时候,马上就可以知道对应位置的元素就是我们要的,而不用再去遍历链表,这样就大大优化了查询的效率。

 

HashMap

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls

Sleep() VS wait()

sleep()方法

sleep()使当前线程进入停滞状态(阻塞当前线程),让出CUP的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会;
sleep()Thread类的Static(静态)的方法;因此他不能改变对象的机锁,所以当在一个Synchronized块中调用Sleep()方法是,线程虽然休眠了,但是对象的机锁并木有被释放,其他线程无法访问这个对象(即使睡着也持有对象锁)。
  在sleep()休眠时间期满后,该线程不一定会立即执行,这是因为其它线程可能正在运行而且没有被调度为放弃执行,除非此线程具有更高的优先级。 
 

wait()方法

wait()方法是Object类里的方法;当一个线程执行到wait()方法时,它就进入到一个和该对象相关的等待池中,同时失去(释放)了对象的机锁(暂时失去机锁,wait(long timeout)超时时间到后还需要返还对象锁);其他线程可以访问;
wait()使用notify或者notifyAlll或者指定睡眠时间来唤醒当前等待池中的线程。
wiat()必须放在synchronized block中,否则会在program runtime时扔出”java.lang.IllegalMonitorStateException“异常。

difference btween C and C++ 

1C is a structuralor procedural programming language.

C++ is an objectoriented programming language.

2Functions are thefundamental building blocks.

Objects are thefundamental building blocks.

3In C, the data isnot secured.

Data is hidden andcan’t be accessed by external functions.

4C uses scanf()and printf() function for standard input and output.

C++ usescin>> and cout<< for standard input and output.

5. C doesn’tsupport exception handling directly. Can be done by using some other functions.

C++ supportsexception handling. Done by using try and catch block.

6. Features likefunction overloading and operator overloading is not present.

C++ supportsfunction overloading and operator overloading.

6.     mallocand free vs newand delete;

diffrence between Java and C++

Everything must be in a class. There are no global functions orglobal data. If you want the equivalent of globals, make static methods andstatic data within a class. There are nostructs or enumerations or unions, only classes.

Write once, run anywhere, butit's still much easier than writing a C++ cross-platform code.

C++ supports multiple class inheritance, while Java only givesyou a single class inheritance, but solves the multiplicity via interfaces.

C++ has got a pointers, and can directly manipulate/violate thememory addresses.

At compilation time JavaSource code converts into byte code .The interpreter execute this byte code atrun timeand gives output .Java is interpreted for themost part and hence platform independent. C++ run and compile using compilerwhich converts source code into machine level languages so c++ is plate fromdependents

Java is platform independent language butc++ is depends upon operating system machine etc. C++ source can be platform independent(and can work on a lot more, especially embedeed, platforms), although thegenerated objects are generally platofrom dependent but there is clang forllvmwhich doesn't have this restriction.

Java uses compiler andinterpreter both and in c++ their is only compiler

C++ supports operatoroverloading multiple inheritance but java does not.

C++ is more nearer to hardware then Java

Everything (except fundamental types) is anobject in Java (Single root hierarchy as everything gets derived from java.lang.Object).

Java does is a similar to C++ but not haveall the complicated aspects of C++ (ex: Pointers, templates, unions, operatoroverloading, structures etc..) Java does not support conditional compile(#ifdef/#ifndef type).

Thread support is built-in Java but not inC++. C++11, the most recent iteration of the C++ programming language does haveThread support though.

Internet support is built-in Java but notin C++. However c++ has support for socket programming which can be used.

Java does not support header file, includelibrary files just like C++ .Java use import to include different Classes andmethods.

Java does not support default argumentslike C++.

There is no scoperesolution operator :: in Java. It has . using which we can qualify classes withthe namespace they came from.

There is no goto statement in Java.

Exception and Auto Garbage Collector handling in Javais different because there are no destructors into Java.

Java has methodoverloading, but no operator overloading just like c++.

The String class does use the + and +=operators to concatenate strings and String expressions use automatic typeconversion,

Java is pass-by-value.

Java does not supportunsigned integer

 

private constructor:

1.    The constructor can only be accessedfrom static factory method inside the class itself.Singleton can also belong to this category.

2.    A utility class, that only contains static methods.

Protected constructor

A subclass only access a protected membersof its parent class, if it involves implementation of its parent. Therefore ,you can not instantiate a parent object in a child class, if parent constructoris protected and it is in different package

 


 

 

抽象类与接口

含有abstract修饰符的class即为抽象类,abstract类不能创建的实例对象。含有abstract方法的类必须定义为abstract class,abstract class类中的方法不必是抽象的。abstract class

类中定义抽象方法必须在具体

(Concrete)子类中实现,所以,不能有抽象构造方法或抽象静态方法。如果的子类没有实现抽象父类中的所有抽象方法,那么子类也必须定义为abstract类型。

接口(interface)可以说成是抽象类的一种特例,接口中的所有方法都必须是抽象的。接口中的方法定义默认为public abstract类型,接口中的成员变量类型默认为public static final。

下面比较一下两者的语法区别:

1.抽象类可以有构造方法,接口中不能有构造方法。

2.抽象类中可以有普通成员变量,接口中没有普通成员变量

3.抽象类中可以包含非抽象的普通方法,接口中的所有方法必须都是抽象的,不能有非抽象的普通方法。

4. 抽象类中的抽象方法的访问类型可以是public,protected和(默认类型,虽然

eclipse下不报错,但应该也不行),但接口中的抽象方法只能是public类型的,并且默认即为public abstract类型。

5. 抽象类中可以包含静态方法,接口中不能包含静态方法

6. 抽象类和接口中都可以包含静态成员变量,抽象类中的静态成员变量的访问类型可以任意,但接口中定义的变量只能是public static final类型,并且默认即为public static final类型。

HashTableHashMap区别

①继承不同。

public class Hashtable extends Dictionaryimplements Map public class HashMap extends AbstractMap implements Map

Hashtable 中的方法是同步的,而HashMap中的方法在缺省情况下是非同步的。在多线程并发的环境下,可以直接使用Hashtable,但是要使用HashMap的话就要自己增加同步处理了。

Hashtable中,key和value都不允许出现null值。

在HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示 HashMap中没有该键,也可以表示该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键,而应该用containsKey()方法来判断。

④两个遍历方式的内部实现上不同。

Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。

哈希值的使用不同,HashTable直接使用对象的hashCode。而HashMap重新计算hash值。

Hashtable和HashMap它们两个内部实现方式的数组的初始大小和扩容的方式。HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。

SQL injection sql注入

SQL injection is a type of web application security vulnerability in which an attacker is able tosubmit a databaseSQL command that is executed by a web application,exposing the back-end database. A SQLinjection attack can occur when a web applicationutilizes user-supplied data withoutproper validation or encoding as part of a command or query

·        SQL injection is a softwarevulnerability that occurs when data entered by users is sent to the SQLinterpreter as a part of a SQL query.

·        Attackers provide speciallycrafted input data to the SQL interpreter and trick the interpreter to executeunintended commands.

·        Attackers utilize thisvulnerability by providing specially crafted input data to the SQL interpreterin such a manner that the interpreter is not able to distinguish between theintended commands and the attacker’s specially crafted data. The interpreter istricked into executing unintended commands.

·        A SQL injection attack exploitssecurity vulnerabilities at the database layer. By exploiting the SQL injectionflaw, attackers can create, read, modify or delete sensitive data.

Preventing SQL Injection

·        Youcan prevent SQL injection if you adopt aninput validation technique in which user input isauthenticated against a set of defined rules for length, type and syntax and also against businessrules.

·        Youshouldensure that userswith the permission to access the database have the least privileges. Additionally, do not use systemadministrator accounts like “sa” for web applications. Also, you should alwaysmake sure that a database user is created only for a specific application andthis user is not able to access other applications. Another method forpreventing SQL injection attacks is to remove all stored procedures that arenot in use.

·        Usestrongly typed parameterized query APIs with placeholder substitution markers, even when calling storedprocedures.

·        Showcare when using stored procedures since they are generally safe from injection.However, be careful as they can be injectable (such as via the use of exec() orconcatenating arguments within the stored procedure).

 

Multithread design pattern(多线程设计模式

1)Single Threaded Execution

只允许单个线程执行对象的某个方法,以保护对象的多个状态。

实现时需用synchronized修饰引用受保护的状态的方法,这样就只能有单个线程访问该方法,其它线程由于不能获取锁而等待,因为只有一个线程去访问受保护状态变量,故此不需要担心该状态变量被别的线程修改。

也可以用synchronized修饰代码块来保护状态字段。

2)Immutable

single threaded executetion这个模式里我们使用了synchronized来保护需要保护的状态变量,因为这些状态可能会变化,如果不保护的话,可能会破坏对象。但是用synchronized保护变量也带来了性能问题,因为获取锁需要时间,并且如果多个线程竞争锁的话,会让某些线程进入这个锁的条件队列,暂停执行,这样会降低性能。

如果状态根本不会发生变化,就不需要用锁保护,这就是Immutable模式。

Person类用final修饰,防止被继承。

_name_address都用final修饰,防止被修改,只能在定义时初始化,或者在构造器里初始化,Person类也只提供了对这些状态字段的get方法,故此外界调用该类的实例时无法修改这些状态。

适用场景:

对于那些不会变化的状态可用Immutable类进行封装,这样可避免用锁同步,从而提高性能。

注意事项:

String就是一个Immutable类,与之相对应的StringBuilder或者StringBuffermuttable类。我们在设计类时,针对那些需要共享并且访问很频繁的实例,可将其设置为Immutalbe类,如果在少数情况下它的状态也可能会变化,可为之设计相对应的muttable类,像StringStringBuffer的关系一样。

StringBuilder是非线程安全的,StringBuffer是线程安全的,String也是线程安全的,因为它是immutable类。

java里的包装器类全是immutable类。

3)Guarded Suspension

当我们调用对象某个的某个方法时,可能对象当前状态并不满足执行的条件,于是需要等待,这就是GuardedSuspension模式。只有当警戒条件满足时,才执行,否则等待,另外对象必须有改变其状态的方法。

_queue.size()>0便是警戒条件,只有当_queue.size()>0才能调用_queue.removeFirst(),当警戒条件不满足时,需要wait

putRequest方法可以改变RequestQueue的状态,使getRequest方法里的警戒条件满足。

适用场景:

某个调用者的方法在执行时如果希望当状态不满足时等待状态满足后再执行,如果状态满足,则立即执行,可考虑使用GuardedSuspension模式。

注意事项:

Guarded Suspension里的警戒方法(等待状态成立才执行的方法)是同步阻塞的,状态不满足时,调用该方法的线程会阻塞。

GuardedSuspension里的状态变更方法里须记得在状态变更后,调用notifyAll,使得调用警戒方法的线程可恢复执行。

4)Balking

Balking模式与Guarded Suspension模式相似,都是在对象状态不符合要求时需要进行一些处理,不过GuaredSuspension在状态不满足要求时,会等待并阻塞线程,而Balking模式是直接返回,并不等待。调用者可暂时先做别的工作,稍后再来调用该对象的方法。

save方法里首先检测字符串是否有变化,如果没有变化则立即返回,否则才保存字符串,这样可避免不必要的IO,提高性能。

上述实例中的警戒条件是_changedtrue

适用场景:

不想等待警戒条件成立时,适合使用Balking模式。

警戒条件只有第一次成立时,适合使用Balking模式。

注意事项:

该模式并不会等待警戒条件成立,当警戒条件不成立时直接返回了,故此改变状态的方法也就不需要调用notifyAll方法。

另外注意不管是警戒条件方法还是改变状态的方法都需要用synchronized同步,因为这里封装了多个数据,一个用于判断警戒条件的状态,还有真实数据。

5)Producer-Consumer

生产者消费者问题是操作系统里非常经典的同步问题,生产者生产好数据后,放到缓冲区,消费者从缓冲区取出数据。但是当缓冲区满了的时候,生产者不可再将生产好的数据放到缓冲区,当缓冲区没有数据的时候消费者不可再从缓冲区里取出数据。

解决生产者消费者问题的方案称之为生产者消费者模式,在该模式里可能有多个生产者,多个消费者,生产者和消费者都有独立的线程。其中最关键的是放置数据的缓冲区,生产者和消费者在操作缓冲区时都必须同步,生产者往缓冲区放置数据时,如果发现缓冲区已满则等待,消费者从缓冲区取数据时如果发现缓冲区没有数据,也必须等待。

这里table扮演的便是数据缓冲区的角色,当消费者调用take取数据时,如果发现数据数目少于0时,便会等待,当生产者调用put放数据时,如果发现数据数目大于缓冲区大小时,也会等待。

适用场景:

当程序里有多个生产者角色或者多个消费者角色操作同一个共享数据时,适合用生产者消费者模式。比如下载模块,通常会有多个下载任务线程(消费者角色),用户点击下载按钮时产生下载任务(生产者角色),它们会共享任务队列。

注意事项:

不管是生产方法还是消费方法,当警戒条件不满足时,一定要等待,警戒条件满足后执行完放置数据逻辑或者取出数据逻辑后一定要调用notifyAll方法,使得其它线程恢复运行。

6)Read-Write Lock

先前的几个多线程设计模式里,操作共享数据时,不管如何操作数据一律采取互斥的策略(除了Immutable模式),即只允许一个线程执行同步方法,其它线程在共享数据的条件队列里等待,只有执行同步方法的线程执行完同步方法后被阻塞的线程才可在获得同步锁后继续执行。

这样效率其实有点低,因为读操作和读操作之间并不需要互斥,两个读线程可以同时操作共享数据,读线程和写线程同时操作共享数据会有冲突,两个写线程同时操作数据也会有冲突。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

设计模式

1.  创建型

1.  Factory Method

The Factory Method Pattern defines aninterface for creating an object, but lets subclasses decide which class toinstantiate. Factory Method lets a class defer instantiation to subclasses.

2.  Abstract Factory Pattern

The Abstract Factory Pattern provides aninterface for creating families of related or dependent objects withoutspecifying their concrete classes.

3.  Builder

Use the Builder Pattern to encapsulate theconstruction of a product and allow it to be constructed in steps.

Builder Benefi

ß Encapsulates the waya complex object is constructed.

ß Allows objects to beconstructed in a multistep and varying process (as opposed to one stepfactories).

ß Hides the internalrepresentation of the product from the client.

ß Productimplementations can be swapped in and out because the client only sees anabstract interface.

4.  Prototype

Use the Prototype Pattern when creating aninstance of a given class is either expensive or complicated.

Prototype Benefits

ß Hides the complexities of making newinstances from the client.

ß Provides the option for the client togenerate objects whose type is not known.

ß In some circumstances, copying an object canbe more efficient than creating a new object.

Prototype Uses and Drawbacks

Prototypeshould be considered when a system must

create newobjects of many types in a complex class

hierarchy.

A drawbackto using the Prototype is that making a

copy of anobject can sometimes be complicated.

5.  Singleton

The Singleton Pattern ensures a class hasonly one instance, and provides a global point of access to it.

考虑多线程问题

2结构型

6.  Adapter

The Adapter Patternconverts the interface of a class into another interface the clients expect.Adapter lets classes work together that couldn’t otherwise because ofincompatible interfaces.

 

 

 

 

 

 

 

7.  bridge

Use the Bridge Pattern to vary not only your implementations, butalso your abstractions.

8.      Compisite

The Composite Pattern allows you to composeobjects into tree structures to represent part-whole hierarchies. Composite letsclients treat individual objects and compositions of objects uniformly.

The Composite Pattern allows us to buildstructures of objects in the form of trees that contain both compositions ofobjects and individual objects as nodes.

Using a composite structure, we can applythe same operations over both composites and individual objects. In otherwords, in most cases we can ignore the differences betweencompositions of objects and individual objects.

9.Decorator

The Decorator Pattern attaches additional responsibilities to an object dynamically.

Decorators provide a flexible alternative to subclassing for extending functionality.

在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。

处理那些可以撤消的职责。

当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

 

10.Facade

The Facade Pattern provides a unifiedinterface to a set of interfaces in a subsytem. Facade defines a higherlevel interfacethat makes the subsystem easier to use.

11.Flyweight

12.Proxy

The Proxy Pattern provides a surrogate or placeholderfor another object to control access to it.

Smart Reference Proxy

provides additional actions whenever asubject is referenced,such as counting

the number of references to an object.

Protection Proxy

 

13. Interpreter

14. Template Method

The Template Method Pattern definesthe skeleton ofan algorithm in a method, deferring some steps to subclasses.Template Method lets subclasses redefine

certain steps of an algorithm without changing the algorithm’s structure.

15. Chain of Responsibility(责任链)

 

16. Command

The Command Pattern encapsulates a requestas an

object, thereby letting you parameterizeother objects

with different requests, queue or logrequests, and support

undoable operations.

17. Iterator

18. Mediator

19. Memento

20. Observer

The Observer Pattern definesa one-to-many

dependencybetween objects so that when one

objectchanges state, all of its dependents are

notified and updated automatically.

21. State

22. Strategy

The Strategy Pattern definesa family of algorithms,

encapsulateseach one, and makes them interchangeable.

Strategylets the algorithm vary independently from

clients that use it.

23. Visitor

24.MVC(model-view-controller)

Model

A model is an object representing data oreven activity, e.g. a database table or even some plant-floorproduction-machine process.

The model manages the behavior and data ofthe application domain, responds to requests for information about its stateand responds to instructions to change state.

The model represents enterprise data andthe business rules that govern access to and updates of this data. Often themodel serves as a software approximation to a real-world process, so simplereal-world modeling techniques apply when defining the model.

The model is the piece that represents thestate and low-level behavior of the component. It manages the state andconducts all transformations on that state. The model has no specific knowledgeof either its controllers or its views. The view is the piece that manages thevisual display of the state represented by the model. A model can have morethan one view.

Note that the model may not necessarilyhave a persistent data store (database), but if it does it may access itthrough a separate Data Access Object (DAO).

 

View

 

A view is some form of visualisation of thestate of the model.

The view manages the graphical and/ortextual output to the portion of the bitmapped display that is allocated to itsapplication. Instead of a bitmapped display the view may generate HTML or PDFoutput.

The view renders the contents of a model.It accesses enterprise data through the model and specifies how that datashould be presented.

The view is responsible for mappinggraphics onto a device. A view typically has a one to one correspondence with adisplay surface and knows how to render to it. A view attaches to a model andrenders its contents to the display surface.

 

Controller

 

A controller offers facilities to changethe state of the model. The controller interprets the mouse and keyboard inputsfrom the user, commanding the model and/or the view to change as appropriate.

A controller is the means by which the userinteracts with the application. A controller accepts input from the user andinstructs the model and view to perform actions based on that input. In effect,the controller is responsible for mapping end-user action to applicationresponse.

The controller translates interactions withthe view into actions to be performed by the model. In a stand-alone GUIclient, user interactions could be button clicks or menu selections, whereas ina Web application they appear as HTTP GET and POST requests. The actionsperformed by the model include activating business processes or changing thestate of the model. Based on the user interactions and the outcome of the modelactions, the controller responds by selecting an appropriate view.

The controller is the piece that managesuser interaction with the model. It provides the mechanism by which changes aremade to the state of the model.

 

In the Java language the MVC Design Patternis described as having the following components:

 

An application model withits data representation and business logic.

Views that provide datapresentation and user input.

A controller to dispatchrequests and control flow.

The purpose of the MVC pattern is to separate the model fromthe view so that changes to the view can be implemented, or even additionalviews created, without having to refactor the model.

Whatis MVC (Model view controller)?

·        The View is responsible for the look and feel.

·        Model represents the real world object and provides datato the View.

·        The Controller is responsible for taking the end userrequest and loading the appropriate Model and View

Whatare the benefits of using MVC?

develop flexible and loosely coupled web applications.The MVC pattern results in separating the differentaspects of the application (input logic, business logic, and UI logic), whileproviding a loose coupling between model, view and controller parts ofapplication. Spring framework provides lots of advantages over other MVCframeworks

Powerful and straightforward configuration of both framework andapplication classes as JavaBeans.

Reusable business code – no need for duplication. You can use existingbusiness objects as command or form objects instead of mirroring them in orderto extend a particular framework base class.

Customizable binding and validation

Customizable handler mapping and view resolution

Customizable locale and theme resolutio

并发编程

1.原子性2.加锁synchronize、volatile、ReentrantLock3.线程封闭

Volatile通常定义标志量,只能确保可见性

线程封闭:1.栈封闭,局部变量,发布逃逸2.ThreadLocal类:ThreadLocal会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突

不可变对象(Immutable object)

并发容器:提高伸缩性和降低风险

ConcurrentHaspMap:分段锁

CopyOnWriteArrayList

BlockingQueue:生产者-消费者


 

2.Mutex VS Semaphore

Mutex:
Is a key to a toilet. One person can have the key - occupy the toilet - at thetime. When finished, the person gives (frees) the key to the next person in thequeue.
Officially: "Mutexes are typically used to serialise access to a sectionof  re-entrant code that cannot be executed concurrently by more than onethread. A mutex object only allows one thread into a controlled section,forcing other threads which attempt to gain access to that section to waituntil the first thread has exited from that section."

Semaphore:
Is the number of free identical toilet keys. Example, say we have four toiletswith identical locks and keys. The semaphore count - the count of keys - is setto 4 at beginning (all four toilets are free), then the count value isdecremented as people are coming in. If all toilets are full, ie. there are nofree keys left, the semaphore count is 0. Now, when eq. one person leaves thetoilet, semaphore is increased to 1 (one free key), and given to the nextperson in the queue.

Officially: "A semaphore restricts the number of simultaneous users of ashared resource up to a maximum number. Threads can request access to theresource (decrementing the semaphore), and can signal that they have finishedusing the resource (incrementing the semaphore)."

 

Thus, a mutex can only be used to maintainatomicity whereas a semaphore can be used for both ordering and atomicity.

Misconception:

There is an ambiguity between binary semaphore and mutex.We might have come across that a mutex is binary semaphore. But they are not! The purposeof mutex and semaphore are different. May be, due to similarity in theirimplementation a mutex would be referred as binary semaphore.

Strictly speaking, a mutex is locking mechanism used to synchronize access to aresource. Only one task (can be a thread or process based on OS abstraction)can acquire the mutex. It means there is ownership associated with mutex, andonly the owner can release the lock (mutex).

Semaphore is signaling mechanism (“I am done, you can carry on” kind ofsignal). For example, if you are listening songs (assume it as one task) on yourmobile and at the same time your friend calls you, an interrupt is triggeredupon which an interrupt service routine (ISR) signals the call processing taskto wakeup.

Mutex is meant for mutual exclusion while Binary semaphore ismeant for event notification and mutual exclusion. A binary semaphore is asimple "true/false" (locked/unlocked) flag that controls access to asingle resource. Mutex can be released only by the thread that acquired itwhile semaphore can be released by any thread.

 

 

 


 

4.Database

1.Nomalization VS Denomalization

·        First Normal Form – The information is stored in arelational table and each column contains atomic values, and there are notrepeating groups of columns.

·        Second Normal Form – The table is in first normalform and all the columns depend on the table’s primary key.

·        partialdependency, which is not allowed in Second Normal Form

·        Third Normal Form – the table is in second normalform and all of its columns are not transitively dependent on the primary key

  • transitive dependency.
  •  
  • To bring this relation into third normal form, we break the relation into two relations as follows −

 

NomalizationPurpose

Eliminating reduntant(useless) data

Ensuring data dependencies make senseafd

1NF

Arelation is in first normal form if and only if the domain of each attributecontains only atomic (indivisible) values, and the value of each attributecontains only a single value from that domain

2NF

atable is in 2NF if it is in 1NF and every non-prime attribute of the table isdependent on the whole of every candidate key

3NF

(1)the entity is in second normal form, and (2) all the attributes in a table are determinedonly by the candidate keys of that table and not by any non-prime attributes

DenomalizationPurpose

What Is Denormalization?

Normalization usually comes at a cost: speed of retrieval.

 query optimization, improved indexing, and databasesystem tuning

Denormalization is a strategy used on apreviously-normalized database to increase performance. The idea behind it isto add redundant data where we think it will help us the most. We can use extraattributes in an existing table, add new tables, or even create instances ofexisting tables. The usual goal is to decrease the running time of select queries bymaking data more accessible to the queries or by generating summarized reportsin separate tables.

Whenand Why to Use Denormalization

Maintaininghistory: Data can change during time, and we needto store values that were valid when a record was created. What kind of changesdo we mean? Well, a person’s first and last name can change; a client also canchange their business name or any other data. Task details should containvalues that were actual at the moment a task was generated. We wouldn’t be ableto recreate past data correctly if this didn’t happen. We could solve thisproblem by adding a table containing the history of these changes. In thatcase, a select query returning the task and a valid client name would becomemore complicated. Maybe an extra table isn’t the best solution.

Improvingquery performance: Some of the queries may usemultiple tables to access data that we frequently need.

Speedingup reporting: A reporting table is usually used asa data cache - a place to store amalgamated or semi-amalgamated data for fastaccess, which reduces demand on the main location where the data are stored ina raw state.

 

 

 


 

Question 143: Differencebetween array and linked list?  

Inarray we follow static memory allocation.
i.e we assign memory to the particular element in advance.
in linked list -> dynamic memory allocation.
i.e we assign memory to the particular element at run-time..
hence we reserve only the amount of memory which is
required.
here is no problem of memory shortage or wastage, in
linked list. which we very frequently come accross in the
arrays.. 

Question 141: Can youfind the height of a binary tree without recursion?

1.    Approach is quite sim­i­lar to Level Order Tra­ver­sal which uses Queue.

2.    Take int height =0.

3.    Here we will use NULL as amarker at every level, so when­ever we encounter null, we will incre­ment theheight by 1.

4.    First add root to the Queue and add NULL as wellas its marker.

5.    Extract a node from Queue.

6.    Check it is NULL, it meanseither we have reached to the end of a level OR entiretree is traversed.

7.    So before adding null as marker forthe next level, check if queue is empty, which means we have trav­eled all thelev­els and if not empty then add NULL asmarker and increase the height by 1.

8.    If Extracted node in Step 6, is NOT NULL add thechil­dren of extracted node to the Queue.

9.    Repeat Steps from 5 to 8 until Queueis Empty.

 

 

 

 

 

 

Database transaction

A transaction is a unit of work that you wantto treat as "a whole". It has to either happen in full, or not atall.

·        Atomic (if the change is committed, it happens in onefell swoop; you can never see "half a change")

·        Consistent (the change can only happen if the new stateof the system will be valid; any attempt to commit an invalid change will fail,leaving the system in its previous valid state)

·        Isolated (no-one else sees any part of the transactionuntil it's committed)

·        Durable (once the change has happened - if the systemsays the transaction has been committed, the client doesn't need to worry about"flushing" the system to make the change "stick")

 

1、饥饿和死锁有什么区别。

这道题是比较经典的一个题目,也看的比较多了,我回答是死锁是因为临界资源调度出现问题,导致系统出现环形结构,造成系统崩溃。而饥饿是因为调度算法的问题,导致有进程一直无法取得资源。本质上区别就是死锁是破坏性的,而饥饿只是某些进程始终无法取得资源。

2、为什么基类要定义虚析构函数。

这个也是比较经典的问题。涉及到多态的问题。什么是多态这里就不再细讲了,感兴趣的同学可以查看一下本版块的其他文章,里面有关于C++多态的详细解释。如果基类不定义虚函数会怎么样?如果没有把基类的析构函数定义为虚析构函数,那么在基类指针指向子类对象的时候,调用析构函数的时候,仅仅会调用基类的析构函数,会释放基类的资源,而不会释放子类的资源。如果子类采用了new生成的空间,那么不会得到释放,因此需要把基类的析构函数定义成为虚析构函数。

3、多态有什么用。

这个是C++的基本概念,我表示我之前也不怎么了解。C++多态我的理解,就是同一类物品,有其本身的特殊属性。多态是用于在对同一个类进行继承的时候,根据继承的类的不同特性,延伸出不同的方法。

举个例子来说,狗和猫都继承自动物,并且都能叫,但是叫声不同,狗有自己的汪汪,猫有自己的喵喵。那么这个就是一种多态概念。

4、什么是内存泄露。

内存泄露就是手工申请了内存,但是没有手工释放。在高级语言JAVAC#中,本身就有回收机制,也就是你只要使用对象就可以了,什么时候释放不用程序员管。但是在CC++中,支持程序员手工申请空间,但是如果是手工申请空间,必须要在某一个地方手工释放空间。如果在程序任何一个地方都没有释放空间,就会导致内存泄露。在C中申请内存的函数是malloc,在C++中申请内存的关键字是new

5、栈和队列有什么区别。

这个也是经典题,当然也是比较简单的。

最主要的特点是队列先进先出,栈先进后出。

6、如何判断C++的返回值是0还是错误。

我回答可以采用两个方法,一个是返回值,一个是全局变量。为什么要用两个,单单用一个返回值不行吗?不行,比如如果只用返回值,如何表示返回的是结果,还是错误?如果返回的都是0,那么如何知道,这个0是程序执行正确返回的0,还是表示失败,产生错误?解决方案就是在设置一个全局变量,当全局变量为1的时候,表示程序执行正确,返回值就是程序正确的返回结果。如果全局变量为0的时候,就表示程序出错,程序返回的任何值都没有意义。

我们只要在可能发生错误的地方,改变全局变量的值就可以了。

但是面试官和我说,为什么会用这个方案,我说我看到微软都是这样的机制,然后他笑笑说,其实微软也不一定是对的。

7、递归是什么

递归就是自身调用自身。

Recursion in computer science is a method where the solution to a problemdepends on solutions to smaller instances of the same problem (as opposed to iteration).[1] 

8、数据库的normaliztion是什么。

normaliztion就是规范化处理,也就是把数据规范成为符合关系型数据库的三个范式。可以用于规范化数据,节省空间。

9、线程和进程有什么区别。

线程轻量级,进程重量级。

线程拥有少量的资源,进程拥有更多的资源。

线程调度开销小,进程调度开销大。

10、快排怎么选择基准。

我开始还没有听懂他说的英语单词的基准,我只能说i am sorry,ididnt hear it clearly,can you repeat it again?他又重复了一下,我还是没有听懂。

但是我猜到了应该是什么,就回答说,randomly ororderly。哈哈,这个是万能药。实际上就是如何找一个划分基准。一般有两种方法,一个是每次找第一个,另外一个是每次取随机一个数作为划分基准。其中采用随机划分效果会更好。

1、给定一个数组和整数S,求得a+b=S

2、根据上述题目给出用例。

这个题目我回答错了。我开始回答分别从中间取两个数,然后判断这两个数的和与S的的大小,然后相应的移动指针。(我后面发现我这个算法是错的,应该分别从首位取两个数来进行判断)。他提示我,数组是无序的,我想,如果是无序的话,就先进行一个排序,排序的时间复杂度是O(nlog n),然后再使用我上面的算法,时间复杂度是O(n+nlog n)=O(nlog n)。他问我有没有更好的算法,我说没有了。


 

 


你可能感兴趣的:(校招)