Kenyth’s BizTech Blog

迷途难返!Do the best with what god gave you!

SWT Programming Tutorials

Resources

  1. SWT Programming with Eclipse
  2. What exactly is the “Event Dispatch” thread (aka “AWT” Thread)?
  3. When exactly is the AWT thread started?
  4. Getting started with SWT
  5. Getting Started with Eclipse 2.1 and the SWT

上海EDGE/EGPRS商用5.17(世界电信日)

听说/看见

详见新闻,其实内环线以内可能早就有了,有人4月份就发现了(里面还包括了详细的技术参数)。这里说的EDGE在5.17商用可能是在上海全境覆盖。我是看了这条新闻才昨天在自己的手机上注意到以前显示信号的那个G (GPRS)变成了E(EDGE/EGPRS),但还是会时常在G和E之间跳动,不知道是为什么,大概还在测试吧。

总体感觉在网速上还没有多明显的变化,和以前感觉差不多,其实上海GPRS网络不稳定(跟上海移动的客服反应过,没有明确答复,叫我重启机器重新搜索网络),就我的使用经验来说,GPRS的速度都还可以容忍,所以比较赞成这位朋友的看法,注重用户体验,虽然他是从资费的角度来讲的。

对两者的网速有些说法。首先理论峰值,GPRS:171.2kbps,EDGE:473.6kbps;稳定(不在高速移动的情况下)的时候实际值,GPRS:57.6kbps,相当于56k的猫,EDGE:190kbps。所以EDGE的速度是GPRS的2~4倍。

另外,CDMA1X的理论峰值307.2kbps,实际稳定值有153.6kbps,几乎是GPRS的4倍。

要注意的是换成字节的速度(B, Byte)都要除以8。

实测

我用手机上的operaMini上网在这里测了一下速度,一共测了三次,前两次的结果差不多都是:

240kbps communications

29.8kBps storage

39s 1MB file download

第三次的测试结果为(信号显示又变回了G,但是199.8kbps也超出了GPRS的理论值,confusing):

199.8kbps communications

24.4kBps storage

42s 1MB file download

测试结果项目的解释见这里,有这么快么,感觉没这么快啊,怀疑ing。

现在市面上的手机应该有很多都支持EDGE的。

BUZZ

别人的体验和评论:12345

引述别人的一个评论泼一下冷水:

别吹了,当年中国移吹的gprs能达到171.2k.而实际有多少,人少的时候能达到2-3k,人多时就只有那200个字节左右.远比1x差远了,现在又造出什么EGPRS,号称470k,也就gprs的2.5倍 ,本人没用过,但按2.5倍算,充其量就是最大7k.小500字节,中国移动的东西大大打折扣,你们别信它 .这就是广东推EGPRS半年多,也没几个人用,人们还去买1x的原因.

Difference among Swing, AWT, SWT and JFace

Introduction

I know questions like telling the differences among Swing, awt, SWT and JFace or some of them are frequently asked in an interview for Java programmers. I don’t use them very often and extensively, nor do I know too much about those four things, especially from the implementation perspective or the guru’s best practice perspective. But I do read some materials and figure out some conceptual difference between those four things that I think would suffice answering such questions in an interview.

AWT and Swing

-AWT

AWT stands for abastract window toolkit which comes with an early release of the Java Programming Language ( about 1.1 ). AWT components are  referred to as heavyweight components. It is implemented as having “peer” native code for every widget you create. Most of the significant logics (including the core event handling logic) of the toolkit are written in C/C++, for which via JNI (Java Native Interface) your GUI program may directly calls those “peer” native code. It means all of the drawings of your GUI are done directly by the graphic API of the underlying operating system. This implementation underlies several limitations:

  • Not all the operating system support the same set of native widgets, so a “least common denominator” philosophy is used when shipping the AWT library, that is only a basic set of components are provided as library via which you write your GUI. So no complex components such as slider, tree and table can be found in AWT components, which you have to build yourself either through directly writing native code as AWT is implemented, or through writing Java codes which wraps AWT ( this is the way Swing is implemented).
  • Because the core logic are hided from you in the native code, debugging your GUI program can be annoying.

This kind of implementation also results in your GUI implemented with AWT always having the same look and feel as the underlying OS.

-Swing

In contrast,  Swing components are known as lightweight components, because Swing doesn’t implement the underlying drawing and event handling logic which are delegated to the toolkit in this case AWT, on which it is built on. As mentioned above, Swing is implemented by pure Java codes. So it is conceivable that Swing has the portability that AWT doesn’t have, and that Swing has almost all the nontrivial complex components. Swing can also have the same look and feel on all OS, and can also be switched to another style of look and feel at runtime regardless of the underlying OS. It is said that Swing has a better performance than AWT, however, from the implementation logic so far I’ve known, I can’t tell why. Swing seems well known for its good design and architecture.

-Never intermix AWT and Swing

I know a lot has been said and written about this subject. The first item in the resources section is a good example of that.

SWT and JFace

-SWT

SWT, short for standard widget tookit, is originally introduced by IBM, as a substitute of AWT. SWT now is as part of the eclipse platform based on which the eclipse GUIs are implemented. SWT is very similar to AWT conceptually, however, the underlying implementation is a little different. Different from implementing all the core logic in “peer” logic in native code, SWT bears a thin JNI layer which is used for directly call the GUI API of each underlying platform. All the significant logics are written in pure Java codes in which the thin JNI layer is used. So almost all the limitations AWT has are elimintated in SWT. Other than this, better performance are gained, for which I don’t know the specific reason. As of AWT, SWT has a consisten look and feel as the underlying OS.

Disadvantages of using SWT:

  • Reuire a native library (This also holds true for AWT).
  • Low level of abstraction (This also holds true for AWT).

-JFace

JFace is conceputally similar to Swing. The relationship between JFace and SWT is very similar to the relationship between Swing and AWT. It works above the level of raw widgets, in this case, SWT. JFace has a rich set of complex widgets.

Resources

  1. Why You Shouldn’t  Mix AWT and Swing
  2. What is the difference between AWT and SWT
  3. what is difference between swing and awt
Technorati tags: , , , , , ,

Exception as Non-Exception

Introduction

Quotes: One of the unexpected benefits of exception handling is better performance because many errors can be processed centrally instead of after each function call. - by Bruce Eckel, the author of Thinking in Java.

-First, what is exception?

In JVM SPEC, an exception is defined to be an error that JVM would signal to a program if a program violates the semantic constrains of the Java programming language. But that’s not the complete fact, more generally, causing an exception is considered to be an exceptional condition or abnormal state that a program is in. So besides violating the semantic constrains of a programming language, which may be a critical and unrecoverable condition, breaking the assumption on the logic functionality of a program can also be considered to be exceptions. From a more formal perspective, every statement, method or generally, module are expected to fullfill some implicit or explicit contract, and an exception indicates the inability to fullfill the contract. Regardeless of the context of the specific programming languge (such as Java) exception handling mechanism, exception and error are interchangeablely used.

-Second, what is exception handling?

Informally speaking, exception handling is what you do about the exceptional condition. However, though an agreement on the defintion of exception are generally achieved, exception handling mechanisms are from time to time debated on. Generally, three techinques / mechanisms / notions are concerning with exception handling. First, exceptions can be identified by returning distinguished error values and handling exceptions is immediately done based on the error values. This is the most conventional way of identifying and handling exceptions. Many large system written in C or most conventional procedure languages utilize this way. Second, exceptions identifying and handling are distinguished from other features that a porgramming language provides. This can be found in many modern OO language such as C++ and Java. An Exception class (or method ?) is  and can be designated for each kind of exceptional condition, and special satements with special keywords are introduced to notify ( or throw ) the condition and then handle the condition, usually at different places in your program. Third, exceptions are covered or at least not emphasized based on the assumption that a module and the client of a module take clearly divided responsiblities. This is mainly concerning an OO design principle called design by contract, DBC for short.

Old-fashioned style by returning distinguished error values

When encountering an error, return distinguished error values that are not considered normal return values. For example, a method that is to calculate the square root of a number doesn’t consider a negative number as a normal return value, so returning -1 / -2 / -3 indicates an error. The client code can distinguish a normal return value from error return values, so the client programmer can write code to cope with each exceptional condition according to returned error values, each of which indicate a kind of exceptional condition. E.g.,

int sqrt( int num )

{

   if ( .. ) return -1;

   else if ( … )

   {

       …

       return -2;

    }

}

-pros and cons

pros:  Both notifying and handling exceptions are light weight. 1) No extra mechanisms are needed to notify and handle exceptional condition, which means codes notifying and handling exceptional conditions are executed in exactly the same way other codes that solving the core problems runs. 2) This will not introduce any extra runtime overhead for exception handling.

cons: 1) This idiom tend to cause spaghetti codes. It will complexicate your method codes by having to place many error checking codes. 2) Agreements on what each error value means must be established between the author and the user of the method. And if the same meaning of an error value must be used among more than one method, the global agreement is hard to be established. For instance:

return -1, if the passed in argument < 0, -2, if …, -3 if …

3) For the client code, it is not enforced to handle any exceptional conditions. In other words, it’s completely up to the client programmer whether or not to handle any exceptional conditions. 4) In addition, even exceptional conditions are to be handled, duplicate codes must be written for each call of the mehod, that is, several calls to the same method requires several times of handling several same kind of exceptional conditions which means codes for handing exceptional conditions can’t be centralized and thus be reused. 5) More worse, handling exceptions must usually be followed immediately after recieving the error values, regardless of whether or not the then’s current context can provide enough information to handle the exceptions. That is, it is hard to propagate the exception to the right level of abstraction only on which such exceptions can be properly handled.

Exception handling style

Utilize dedicated constructs, such as Exception types, to represent the exceptions and collect information about the exceptional conditions, and handle exceptions based on information wrapped in such constructs.

-pros and cons

pros: 1) Exceptions and their handling are standardized as part of the features of a programming language that are distinguished from other features of that language. Handling some kinds of exceptions are enforced by the compiler, which means the learning curve are to some degree flattened. It less depends on the experiences, but are forced to be done. 2) Agreements on what exception means are easily established by the kind of dedicated constructs. And global reuse of these agreements needs no extra effort. 3) Though, it will stil cause spaghetti codes, it is alleviated by exception handling mechanism enabling that some exceptional conditions (such as access members on a null reference) are automatically notified in the standard way which means less error checking codes are needed. 4) Exceptions notifying and handling are loosely coupled, that is, identifying exceptions and handling them can be at two point far away from each othe in the control flow. This also means it is easy to propagate exceptions to the right level of abstraction on which such exceptions can be properly handled. 5) Due to easily propagating exceptions, handling the same kind of exceptions can be centralized, for which someone argues that unexpected performance benefits will be get as opposed to old-fashioned error values way.

cons: 1) Extra runtime overhead are needed to notify and handle exceptions for which at the implementation level, extra transfer of control is needed.  2) Client codes are complicated by exceptions handler codes which are more obvious if exceptions notifying are misued and/or overused.

Design by contract

A contract is established, explicitly or implicitly, between a module and the user (client code) of the module. Any side must comform to the contract at any time, under any circumstance. The contract consists of precondition, invariant and postcondition. Whenever wherever the module is called (used) the precondition must be met, and after executing the module, the postcondition must be met. In the whole process the invariant must always be met. Obligations and benefits for both parties are specified. It is the obligation of the client to ensure the precondition is met before calling the module, and that of the module to ensure the invariant and postcondition are met. So any party is committed to its obligation regardless of the other party’s obligation.

More specificly, the client will check and ensure the precondition is met before it calling the module, so on most occassions, no exception mechanism is needed.  Because if the contract is always conformed to, no exceptions are foreseen. But, usually, extra mechanism, such as assertion, is needed to help tell and/or check whether or not the contract is conformed to. However, even no such extra mechanism is provided, the idea behind DBC can also be used to prevent from overusing exceptions which may be caused by defensive programming. In general, DBC is sometimes considered to be a formal method.

p.s., the DBC community considers returning error values and exception handling two rivals :)

Defensive programming

The philosophy of defensive programming can be summed up as: Better to check too much, or check redundantly, than to check little. This is in contrast to DBC which advocates guaranteeing more by checking less. It is conceivable that defensive programming is caused because the contract in DBC is not established at all. Actually, defensive programming goes to another extreme. It assumes that the other party never burden its obligation, such as ensuring the precondition, so the module will itself burden others’ obligations, such as checking for the precondition. This is mainly responsible for complexity and obscureness of codes. For instances, we have a module:

int sqrt( int num )

{

   if precondition is met then

    solve the problem; return …

    else return …

}

and we have a snippet of client codes to call that module:

if preondition for sqrt( .. ) is met then

call sqrt( .. );

Pseudocodes in bold are caused by defensive programming. This way of programming are extensively common.

Exception handling in Java

When an exception is thrown, the JVM will transfer the control from the point where the exception occur to the point that can be specified by the programmer. During the process, the JVM abruptly completes, one by one, any expressions, statements, method and constructor invocations, static initializers, and field initialization expressions that have begun but not yet completed the execution in the current thread. The process continues until a handler for the thrown exception is found. If no such handler is found, then the method uncaughtException is invoked for the ThreadGroup that is the parent of the current thread.

If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.

If a method throws an exception, it must assume that exception is “caught” and dealt with. One of the advantages of Java exception handling is that it allows you to concentrate on the problem you’re trying to solve in one place, and then deal with errors from that code in another place.

Goal of exception handling

Make your program more reliable, robust and error-tolerant. Usually, it provides measures for you to be notified of the exceptional condition and recover from that condition.

Best practices in Exception handling

Below are some best practices in exception handling citing from the book “Effective Java”.

-Use exceptions only for exceptional condition

Prevent from overusing exception.

-Use checked exceptions for recoverable conditions and runtime exceptons for programming errors

Three kinds of exceptions: checked exception, unchecked exception and errors. By convention, errors must be used only by JVM. Programming errors may be considered to fail to fullfill the contract and are generally unrecoverable.

-Avoid unnecessary use of checked exceptions

Two reasons: first, exceptions handling needs extra runtime overhead; second, checked exceptions are forced to be caught which would complexicate your client code. This to some degree conforms to DBC by advocating the client code calls state-testing methods which actually is to ensure the precondition.

-Prefer standard exceptions over user-defined exceptions

For learning curve about your codes,  understanability and portability of your codes.

-Throw exceptions appropriate to the abstraction

Exception translation, Exception chain.

-Document all exceptions thrown by each method

Javadoc style, or declaration using the keyword throws which is also called the exception specification.

Exceptions as a part of the specification of a method.

-Include failure-capture information in detail message

Refers to the goal of exception handling

-Strive for failure atomicity

Refers to the goal of exception handling

-Don’t ignore exceptions

No empty catch block.

Other guidelines

-User visible error message should not be the same as the failure message wrapped in the exception object (needs further investigation). The latter are only for programmer to debug the program.

-Don’t assume the way which the client codes burden their obligation and/or the degree to which they burden their obligations. However, unfortunately, defensive programming is often needed, though you should try your best to avoid.

Resources

  1. Chapter 8 Exceptions, Effective Java.
  2. 2.16 Exceptions, Java Virtual Machine Spec.
  3. Chapter 10 Error Handling with Exceptions, Thinking in Java 2nd version.
  4. Building bug-free O-O software: An introduction to Design by Contract(TM)
  5. Design By Contract
  6. Design By Contract (DBC)

Java基础复习

Introduction

基本上是按照网上流传甚广的一套Java的面试题目来的,一个一个问题回答。

谈谈final、finally、finalize的区别

 其实除了名字类似,是不沾边的三个东西。

final

Final is a keyword that can be used for classes, methods and data ( field / arguments ). It means what it modifies can’t be changed anymore. For final classes, they can’t be extended or derived; for final methods, the method’s behavior can’t be changed by overridden; for final data, they can only be initialized once and not be assigned values any more. But remember there’re two reasons for preventing change: design or efficiency.

> final methods

There’re two reasons why you make a method final: 1) quite small final method can be inlined when they’re called which is more efficiently; 2) you don’t want a method to be explicitly overridden.

Private methods are considered to be implicitly final, because in whatever cases, you can’t access or override a private method.

> final data

A misconception ( maybe it’s only mine : ) is that declaring data to be final doesn’t necessarily mean that its value is known at compile-time. The value can be run-time determinable. And data can also be declared to be final without any initialization value. In this case the final datum is called blank final field which has to be initialized in constructor or static initializer, or somewhere before use.

> final classes

Defining classes as final simply prevents inheritance — nothing more. Since a class declared to be final can’t be inherited, all its methods are implicitly final and the complier can opt to bring efficiency for you as with other explicitly final methods.

finally

Finally is to do with Exception handling which can introduce a piece of code that you want to execute whether or not an exception is thrown within a try blok or catched in a catch block.

finalize

Finalize which is the name of a method of Object is to do with garbage collection, that is to do with memory release. Garbage collection in java is a two-pass process. In the first pass in which case the object is eligible for garbage-collected, garbage collector will call finalize(), and in the second pass in which case the running programm may reach the point of runing out memory, garbage collector may physically release memeory of eligible objects. So the storage of a finalized object isn’t necessarily get released.

Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)

The answer is yes for both cases.

Inner class constructors get passed a hidden parameter, a reference to the outer class object that created them. static nested classes don’t have this hidden parameter. This is analogous to the way instance methods have hidden this parameter, where static methods do not.

Inner classes are not permitted to have static methods or fields. That is not quite true. They are allowed static final compile time constants, which are treated as if there were literals. If inner classes need statics, they have to get the outer class to hold them, or you have to use static nested classes or you have to inherit the static fields. Oddly, inner classes are permitted to extend classes that do have static methods and fields.

Anonymous inner class can’t define constructors. An anonymous inner class implements an interface, say, ITest, by:

new ITest() { .. }

and extends a class, say, Test, by:

new Test( name) { .. }

where Test( String name ) is an non-default constructor of Test, and default constructor can’t be used here!

For which kind of classes an anonymous class can extend / implement, refer to nested classes : Java Glossary.

Static Nested Class 和 Inner Class的不同

Differs in creating instance of them, and linking with the outter class /instance.

&和&&的区别

& is bitwise AND ( 位与) operator,  while && is logical AND (逻辑与) operator.

Shift operators

The left-shift operator( << ) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator( inserting zeroes at the lower-order bits ). The signed right-shift operator( >> ) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator( inserting zeroes / ones at the higher-order bits ). There’s an unsigned right-shift operator( >>> ) will produces results inserting zeroes at the higher-order bits regardless of the sign. 

Shift operators can be combined with equl sign, such as, <<=, >>=, and >>>=.

Talk about collection framwork in Java 2

Main interfaces: Collection, List, Set, Map. There’re actually only three collections List, Set and Map, and only two or three implementations of each one. And Map is not derived from Collection. The reason putting it the collection framwork is because a Map can produce collections from its key set and value list. Refer to chaper 9 of Thinking in Java 2nd version and Sun’s Java library for full details.

All collection implementation requires type checking ( especially with generic feature in Java 5 ) or bounds checking, or both.

Vector is synchronized, which means it’s thread-safe.

ArrayList is much like an array except it is variant-sized which brings extra run-time overhead.

The List interface provides four methods for positional (indexed) access to list elements. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

For the Set interface, a speicial case of prohibition is that it is not permissible for a set to contain itself as an element.

 

Diff between Collection and Collections

First Collections is the name of a conceptual framework coined by the designers of Java to represent a collection of interfaces and / or classes that enables an object holding a group of objects and variaous operations on it. It is generally called the collections framework ( or container classes before Java 2 ).

Collection as a type name is the name of an interface which is the root of the collecitons framework hierarchy and is located at package java.util. While it is the root of the collection hierarchy, there’re some collection classes that aren’t rooted from it, such as Map.

While Collections is a class also located in the package java.util which consists of a variety of static methods that operate on or return collections. This is common technique used to organize a bunch of related PO paradigm interfaces* ( may be not types, but methods ) into one module supported by OOP paradigm to improve the modularity and/or accessability of such interfaces*. In some cases, this is called the facade design pattern. Similar classes examplifying this techinque are Arrays, Math, etc.

Diff between HashMap and HashTable

String, StringBuffer, and StringBuilder

String class represents character strings. All string literals ( e.g., “Kenyth” ) in Java program are implemented as instances of String class. Strings are constant, namely immutable, as opposed to mutable StringBuffers. Their values can’t be changed after they’re created, which makes they can be shared ( refer to a compiler theory book about handling of constants ). And any modification to a String will produce a new instance of String, explicitly or implicitly. Concatenation of String is implemented as operations on StringBuffer( see the class file bytecode ), and conversions from an object to String is facilitated by the toString() method defined in Object class.

StringBuffer class represents a sequence of characters. It is mutable. It allows for data being appended to and inserted into it. It is thread-safe.

StringBuilder is like StringBuffer, but is not intended to be used by multi threads, that is not synchronized, or not thread-safe. It is introduced as of Java 5.

When to use assert

( Actually I’ve never used this keyword in my programming ) For the full details refer to Sun’s official document Programming With Assertions.

Simply speaking, assert in Java provides you a debugging facility similar to macros in C/C++. You can enable/disable your assertions when starting your program by passing in JVM command-line arguments ea/da. However, by default assertions are disabled at run-time.

There’s one guideline for deciding where/when to use assert that you should never use it for what your programming code do, such as method contract enforcement. Because since it is just a helper tool for debugging / observing your program and can be disabled, you must not depend the functionalities of your program on it.

more are coming soon…

Resources

  1. Thinking in java version 2.
  2. JAVA面试题目(去了两家公司,都是这样的题目) :一个很好的问题导向的复习提纲。
  3. 初识Java内部类:关于内部类的好处,静态内部类以及非静态内部类。 
  4. `final’ variables and inner classes: explains why access from anonymous inner class to non-final outter variables is not allowed. 
  5. nested classes : Java Glossary: contains very detailed explanation of the terms nested  / inner class and their usages.
  6. Programming With Assertions
     

Technorati : , ,
Del.icio.us : , ,

Next Page »