自己回顾一下,看看有什么问题

bigbugice 2005-01-07 05:54:16
// Copy right Big Bug, all right reserved.
// appdata.cpp
#include "appdata.h"
#include "applogger.h"
#include "iniparser.h"
#include "stdio.h"

extern AppLogger logger;
extern AppIniParser iniParser;

AppData::AppData()
{
targetNumber = 0;
topBound = 0;
bottomBound = 0;
}

AppData::~AppData()
{
}

void AppData::setData()
{
char buffer[10000];

// Get data from command line console
printf("\nExpected matched number : ");
fflush(stdin);
fgets(buffer, sizeof(buffer), stdin);
targetNumber = (float)atof(buffer);

printf("Offset value : ");
fflush(stdin);
fgets(buffer, sizeof(buffer), stdin);
topBound = (float)atof(buffer);

bottomBound = 0 - topBound;

//printf("Please input the source data : ");
printf("Please input the value : ");
fflush(stdin);
fgets(buffer, sizeof(buffer), stdin);

char tmp [100];
int j = 0;

for(int i = 0; i < (int)strlen(buffer); i++){
if(buffer[i] == ' ' || buffer[i] =='\n' || buffer[i] == '\r'){
tmp[j] = '\0';
if((int)strlen(tmp) != 0){
dataVector.push_back((float)atof(tmp));
}
tmp[0] = '\0';
j = 0;
}else{
tmp[j++] = buffer[i];
}
}

return;
}
...全文
474 48 打赏 收藏 转发到动态 举报
写回复
用AI写文章
48 条回复
切换为时间正序
请发表友善的回复…
发表回复
bugbigblog 2005-06-21
  • 打赏
  • 举报
回复
Interview series

ebay: This is my second time to join the interview of ebay because I dailed Justin directly for an interview opportunity. They didn't extend their scale in the past half year, they have 60+ people. They are focusing on how to improve the efficiency of the Chinese group.

I have joined 3 rounds of interviews totally.

1) Justin's interview: He is very high level manager of ebay China who has 13 year of working experience on IT industry
-- English test, get the excellent comments
-- Ask me to draw crystal project's architecture
-- Why we take such architecture
-- How can we announce that we have reached the "High" quality.
2) Engineer's interview
-- Introduce the J2ee project
-- What is the benifit and shortcoming for structs
-- They use servlet + xml to present the jsp. So no business logic is involved on Jsp page.
-- Use login as an example to explain the data flow
3) Stuff engineer's interview: prone to low-level question, protocol
-- What classes has learned in college
-- Comments on corba tech, response time level
-- Protocol about TCP/IP, mail system
-- Http protocol. What method has been provided.
-- Coding, Java design patterns. Singleton
4) Summary from Justin.
bigbugblog 2005-06-21
  • 打赏
  • 举报
回复
Interview series

Sybase: Sybase is a big database-solution company. It has 3000 employees totally arround the world. The China development center is in JiDian park, ZhangJiang, ShangHai.

It seems a kicking off department of Sybase in ShangHai, the opportunity is sufficient. But the employess seems not capable.

I heard that Google is also in Jidian Park. This is a interesting news.

I have 4 rounds of inverview in Sybase.
1) HR manager interview
-- He is a HongKong nees, English is pretty good
-- General talking
2) Examination
-- A little difficult
-- UDDI's stub
-- Programing: Design a structure for a graphic, caculate the shortest distance between two nodes
3) Tech interview by engineer
-- Focus on db and Java
-- Db questions
i) The properties of transaction (Automicity, Consistency, Isolation, Durability)
-- Java questions
i) All is from the internet, stupid questions, such as the difference of final, finally, finalize
4) Stuff interview
-- He is experienced
-- What design patterns have been used in J2ee framework.
-- Toolkit, The conbination of the whole development process for J2EE.
-- Web service
bigbugblog 2005-06-21
  • 打赏
  • 举报
回复
New account added to this family :)

bigbugblog
bugbigblog
bonbonice 2005-05-31
  • 打赏
  • 举报
回复
http://www.csdn.com.cn/program/program.htm
bonbonice 2005-05-26
  • 打赏
  • 举报
回复
Interview: Microsoft

1. Interview in Microsoft support Asia
Commentary: The position is destop support. There are 6 rounds of inverview. I have joined 5 rounds.
1) Tech inverview.
-- How to get the file name before word application open it
-- Page memory
-- 32 bytes system's memory range
2) Tech inverview.
-- Internet, A/B/C/D of IP address
-- Message working process in sqlserver example
-- Pure virtual method
-- Index type of database, how to manage index
3) English inverview
-- Backgound introduction and generic questions
-- what can you add to Microsoft name
-- A mail to convence customer to take your solution
-- Understanding about Microsoft support and importance
4) Manager interview
-- Generic talking
-- How to manage the conflict between two teams
5) CTO interview
-- Pure virtual method
-- How to manage the conflict between two teams
bonbonice 2005-05-23
  • 打赏
  • 举报
回复
Interview experience

Intel
Five rounds of interview. One by one, the pressure is high. Very tech oriented.
Commemts: need to know the bytes operatation
1) Write a program to parse the "\b" (reverse char) in sentence
2) -- webservice
-- Architecture of project
3) -- linktable, how to delete one item
-- how to check the "1" of a 32 long
-- Singleton, implemented with C++
-- four types of ball, find the defect
4) -- reverse the linktable
5) -- webservice

Citizen Bank
Comments: no sense, the organization isn't good. Effective C++
1) Writting interview
-- The way to implement String, copyer and operator
-- Reference of performance
2) Inteview
-- How to implement a dynamic array, vector
-- The source code of STL
-- What book is reading, what tech is learning

SAP
Comments: no comments, a simple Java program
1) -- how to get n!

HP:
I have joined HP's inverview for thripple times. The HP interview is very tech oriented. So please focus on techical issue and don't talk too much about management unless be asked.

1) First interview: dataware house
Comments: Almost no experience. Prepare for Java inheritance

2) C++ interview
Comments: be careful to all the details
-- Design pattern
-- pure virtual method in C++
-- const int define in class
-- C++ override and overload. Inheritance
-- Unit command: watch memory (prstat), watch process

3) Java interview
Comments: teck oriented, web oriented
i) Basic knowledge
-- Three aspects of Java: Socked, Swing and Container (Draw the map)
-- Exception system in Java
-- 7 layers of web structure, TCP/IP
-- webservice program
-- Singleton, design pattern
ii) J2EE knowledge
-- The status of Session bean
-- Webservice
-- The cache implementation
-- Singleton
iii) All knowledge
-- 7 layers of web structure
-- UML design, the weakless of inheritance, how to let the property shared with other project
-- webservice
-- xml parser, RCP...
-- design pattern
-- An instance of oracle
-- Test types

e2open
1)Comments: bad company
-- redirect vs forward
-- outer join and inner join
bigbugice 2005-05-17
  • 打赏
  • 举报
回复
Some teck index

http://tech.ccidnet.com/pub/article/c317_a74301_p1.html

http://www.caq.org.cn/6sigma/jingyanjiaoliu/6S_anli_5.htm
http://blog.joycode.com/moslem/archive/2003/11/18/6958.aspx
6xigema forum

http://www.cnblogs.com/whbell/archive/2004/04/16/6204.aspx
http://www.kissjava.com/doc/javamore/struts/2004-11-05/4303.php
Struts frameword and tag introduction

http://blog.csdn.net/jeke342/archive/2004/09/10/struts.aspx
struts example

http://blog.csdn.net/hampster/archive/2004/11/30/199779.aspx
Hibernate article

http://laughinger.blogchina.com/blog/article_13219.540294.html
Interview

http://www.jspcn.net/htmlnews/200150271.html
http://soft.yesky.com/SoftChannel/72342371945283584/20041214/1888509.shtml
http://www.pcdog.com/p/html/200544/4420057257_1.htm
tag

http://www.leftworld.net/online/effectivec/index.html
effective C++

http://www.oracle.com/technology/global/cn/pub/articles/maps1.html
Collection instroduction

http://www.javajia.com/pattern.php
Java design pattern
bigbugice 2005-04-27
  • 打赏
  • 举报
回复
http://www.leftworld.net/online/effectivec/

Effectivec非常好的版本
bigbugice 2005-03-31
  • 打赏
  • 举报
回复

bigbugice
冰狐
火奴鲁鲁
张廷玉
bonbonice 2005-02-03
  • 打赏
  • 举报
回复
Buy English book

www.cnforyou.com
bigbugice 2005-01-27
  • 打赏
  • 举报
回复
Memory Access in C++
Mike
Mar 9, 2004

Memory Access in C++
 C++ Advantage/Disadvantage
 Stack and heap
 new and delete
 invalid memory access
 memory leak

Advantage/Disadvantage
● C / C++ is faster
– native code , Execute ( not JIT )
– Memory garbage collect effectively in stack
● C / C ++ is dangerous
– Invalid Memory access
– Memory Leak
– Hard to find error

Stack
● Stack is limited
int a =0;
int arr[655360]; // cause stack overflow at
runtime
● Stack is auto memory colloect
{
int a = 0; // 4 bytes memory
int arr[256]; // 1024 bytes, after exit block , collect
}

Stack and heap(Cont'd)
● Heap is huge
– Expand to virtaul memory(harddisk)
● Heap is slow than stack
● Heap need to be allocated and deallocated
int *arr = new int[655360];
...
delete [] arr;
● Invalid access and leak happened in heap
char *szChar = new char[128];
char *szAlias = szChar;
......
delete []szChar; //szAlias will be invalid

Stack and heap(Cont'd)
● Mixed use stack and heap
CBitmap * pBmp[N];
for ( int i = 0 ; i < N; i ++ )
{
pBmp[i] = new CBitmap();
... do some operations
}// later
for ( int i = 0 ; i < N; i ++ ) delete pBmp[i] ;
array pBmp is allocated in stack, array item is
allacated in heap

Stack and heap(Cont'd)
● full use heap
CBitmap ** pBmp = new CBitmap*[N];
for ( int i = 0 ; i < N; i ++ )
{
pBmp[i] = new CBitmap();
... do some operations
}// later
for ( int i = 0 ; i < N; i ++ ) delete pBmp[i] ;
delete pBmp;
Note: Cbitmap must have constructor without
parameters

new and delete
● New|delete are C++ feature.
Easy to use , no need type conversion
long * data = new long(200);
delete data;
long * dataArr = new long[200];
...
delete [] dataArr;
● Malloc , calloc, realloc vs free
must do type conversion
long *buffer = (long *)calloc( 40, sizeof( long ) );
free (buffer);

new and delete (cont'd)
● After new, remember to delete it.
● Do not delete a pointer 2 more time b4 it assigned
to NULL
{
int * b = new int;
*b = 2;
delete b;
delete b; // danger
}
{
int * b = new int;
*b = 2;
delete b;
b = NULL;
delete b; // safe
delete b; // safe
}

new and delete (cont'd)
● Good habbit
{
int * b = new int;
*b = 2;
.....
if ( b ) delete b;
b = NULL;
}
● Delete reference
int & aRef = new int(20);
......later
delete & aRef;

new and delete (cont'd)
● Keep the handle
int getMemory()
{
char * pChar = new char[256];
if ( pChar != null )return 0;
else return -1;
}.
..........
{
int nSuccess = getMemory();
}
// lose the memory handle

new and delete (cont'd)
● Keep the handle
int getMemory(char *& pCHar)
{
pChar = new char[256];
if ( pChar != null )return 0;
else return -1;
}.
..........
{
char * pChar = null;
int nSuccess = getMemory(pChar);
...
delete pChar;
}

new and delete (cont'd)
● Triangle matrix
int **pMtx = new *int[N];
for ( int i = 0 ; I < N; ++i)
{
pMtx[i] = new int[i+1];

}
…. Later delete this matrix
for ( int i = 0 ; I < N; ++i)
delete pMtx[i[i+1];
delete [] pMtx;

Invalid memory access
● Delete 2 times
● Class(struct) constructor
in constructor, if new a pointer, then delete in destructor
but often cause problems
● copy constructor
X::X(X &);
deep copy , not shared copy
happned in assignment, init, or function

Invalid memory access
(cont'd)
string::string(string & a)
{
str =
new char[strlen(a.str)
+1];str(str, a.str);
}
void main(){
string s1 ("Beijing");
string s2(s1);
int n = foo(s1);
}
class string
{
public:
char * str;
string (char * s){
str = new char[strlen(str) + 1];
strcpy(str, s );
}
~string() { delete str; }
};
void main(){
string s1 ("Beijing");
string s2 (s1):
}

Invalid memory access
(cont'd)

Memory Leak
● Very common
- in window (Patch)
- in Linux
- in component ( COM, VCL)
- in DataBase
● Difficult to find
– With help with tools
● Rational purify
● ZeroFault (AIX)
● Memdebug
● ParaSoft Insure++

Memory Leak(cont’d)
● Why
Most leaks are caused by forgetting free
memory
poor class design
● How to
remember to delete after use
class design—copy constructor
-- operator overriding
smart pointer
before assign a pointer, judge and delete
choose C++ (esp STL) other than C

Memory Leak(cont’d)
string::string(string & a)
{
str =
new char[strlen(a.str)
+1];str(str, a.str);
}
class string
{
public:
char * str;
string (char * s){
str = new char[strlen(str) + 1];
strcpy(str, s );
}
~string() { delete str; }
};
void main(){
string str1 ("Beijing");
string str2 (“Shanghia");
string str1 = str2;
}

Memory Leak(cont’d)

Memory Leak(cont’d)
string::string(string & a)
{
str = new char[strlen
(a.str)+1];
str(str, a.str);
}
class string
{
public:
char * str;
string (char * s){
str = new char[strlen(str) + 1];
strcpy(str, s );
}
~string() { delete str; }
};
void main(){
string str1 ("Beijing");
string str2 (“Shanghia");
string str1 = str2;
}
string & string::operator = (const string &s )
{
if (this == s ) return * this;
delete str;
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
return *this;
}

Memory Leak(cont’d)
● Smart Pointer
a class that behaves like a pointer
very common in CORBA
C++ lib , auto_ptr
COM , _com_ptr_t

Reference
● Scott Meyers. Effective C++.
● http://www.linuxdevcenter.com/
● http://www-306.ibm.com/
software/awdtools/purifyplus/
● http://www.zerofault.com/

bigbugice 2005-01-27
  • 打赏
  • 举报
回复

21
Example: Travel Agency
What is J2EE?

22
How to use J2EE ?
. Using J2EE SDK 1.4 to Design, Develop,
Assemble and Deploy Applications
How to use J2EE?

23
How to run a J2EE application
on J2EE SDK 1.4
. Preparation – Environment setup & Configuration
. Write and compile codes
<Start J2EE SDK> to Assemble, Deploy, and Run the application
. Packaging
– Creating the J2EE Application (.ear)
– Creating the Enterprise Bean (.jar)
– Creating the Web Client (.war)
. Deploying
. Running

24
Creating Web Component
When a web client such as browser
communicates with a J2EE application, it does so
through server-side objects called Web
components
. Writes and compiles the source code
. Bundles the .class's, .jsp's, and .html files into
WAR file

25
An enterprise bean is a server-side component
that contains the business logic of an
application
. Write and compile the source code
. Package the bean’s classes into EJB JAR file
– Remote Interface
– Home Interface
– Enterprise Bean Class
Creating Enterprise Bean
Remote
Client
Remote
Interface
Home
Interface
EJ
B

26
Remote Interface
. WebAddressAccount.java
– defines the business methods (signatures) that a client
may/can call. The business methods are implemented
in the enterprise bean code
public interface WebAddressAccount extends EJBObject {
public String getUrlName();
public String getUrlDescript();
}

27
Home Interface
. WebAddressAccountHome.java
– defines the methods that allow a client to create,
find, or remove an enterprise bean (life cycle
methods)
public interface WebAddressAccountHome extends EJBHome {
public WebAddressAccount create(String urlName, String
urlDescript);
public WebAddressAccount findByPrimaryKey(String urlName) ;
}

28
Enterprise Bean Class
. WebAddressAccountBean.java
– implements the business methods
public class WebAddressAccountBean implements EntityBean {
public String getUrlName() { return urlName; }
public String getUrlDescript() { return urlDescript; }
public String ejbCreate( String urlName, String urlDescript) {
insertRow( urlName, urlDescript);
}
public String ejbFindByPrimaryKey(String primaryKey) {
result = selectByPrimaryKey(primaryKey);
}

29
Packaging
. Create an Enterprise Archive (EAR) file
– ProjectApp.ear
. Add Java Archive (JAR) files and Web
Archive (WAR) files to the EAR
– WebAddressAccountJAR: contains the enterprise
bean files and related files
– ProjectWAR: contains the Web Component files and
related files

30
Example: BonusApp
. Objective:
To calculate bonus for
an employee
. 3-Tier Example using
Session Bean

31
3 Tier Example: using session bean
1. Create HTML page
2. Create Servlet
3. Create the Session Bean
4. Compile the Session Bean and Servlet
5. Start the J2EE Application Server
6. Start the Deploy tool
7. Assemble the J2EE application
8. Specify JNDI Name and Root Context
9. Verify and Deploy the J2EE application
10. Run the J2EE application

32
3 Tier Example: using session bean
. 3-tier
– Html page
– Servlet
– Session Bean

33
bonus.html
<HTML>
<BODY BGCOLOR = "WHITE">
<BLOCKQUOTE>
<H3>Bonus Calculation</H3>
<FORM METHOD="GET"
ACTION="BonusAlias">
<P>
Enter social security Number:
<P>
<INPUT TYPE="TEXT" NAME="SOCSEC"></INPUT>
<P>
Enter Multiplier:
<P>
<INPUT TYPE="TEXT" NAME="MULTIPLIER"></INPUT>
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET">
</FORM>
</BLOCKQUOTE>
</BODY>
</HTML>

34
BonusServlet.java

35
Create Session Bean: CalcHome,
Calc, CalcBean

36
CalcHome.Java (Home
Interface)
BonusServlet does not/cannot work directly with the session
bean, but creates an instance of its home interface. The home
interface extends EJBHome and has a create method for creating
the session bean in its container. It returns a remote object
reference viz., “Calc”.

37
Calc.java (Remote Interface)
The remote interface extends EJBObject and declares
the calcBonus method for calculating the bonus value.
This method is required to throw
javax.rmi.RemoteException, and is implemented by the
CalcBean class.

38
CalcBean.java (Session bean)
The session bean class implements the SessionBean interface and
provides the behavior/action for the calcBonus method. The
setSessionContext and ejbCreate methods are called in that order by
the container after BonusServlet calls the create method in
CalcHome.

39
Assemble the J2EE Application
1. Create a new J2EE application (BonusApp.ear).
2. Create a new enterprise bean (CalcBean.jar).
3. Create a new web component (Bonus.war).
4. Specify JNDI name for the enterprise bean
(calcs).
5. Specify the Root Context for the J2EE application
(BonusRoot).

40
JNDI Names and Resource
References
. JNDI: Java Naming and Directory Interface
. J2EE components locate objects by invoking the
JNDI lookup method
. The JNDI name of a resource and the name of
the resource reference are not the same
. This approach to naming requires that you map
the two names before deployment

41
Run the application
In the browser, type
http://localhost:8000/BonusRoot/bonus.html
. Fill in a social security number
. Fill in a multiplier
. Click the Submit button. BonusServlet processes your data
and returns an HTML page with the bonus calculation on it.
BonusRoot is the root
context

42
Conclusion : Summary
. Need for server-side/enterprise
processing with enhanceability,
reusability, and scalability
. J2EE as a web-based, component-based
multi-tiered client/server architecture
. Designing, developing, assembling, and
deploying java applications using a
common platform

43
Questions ?

44
Thanks from Team Inquira
Have a Good Day!

45
bigbugice 2005-01-27
  • 打赏
  • 举报
回复
1
J2EETM : An Introduction

Earnest A Thomas

2
Objectives
. Why J2EE?
. What is J2EE?
. How to use J2EE?

3
Motivation for J2EE
. The J2EE framework today provides the
standard platform for distributed applications.
. It creates a standard in which application
components can be distributed and reused.
. Simplification of the development process
. Faster maintenance due to smaller units of code
. Better performance through load-balancing and
distribution of components
. Higher scalability of the application
Why J2EE?

4
CGI-based Web Client/Server
. Interaction of two-tier architecture
. Client: uses service requiring 2ndary storage
. Server: manipulates forms, Database
updates, (primitive) electronic commerce
. Fat Server/ Thin Client
Why J2EE?

5
Two-tier Client/Server
Architecture
But what is the problem with this architecture?
Client Server
. Important processing needs to be run on the server
. Then, Java needs to run on the server too to be more useful . enterprise
. The server is almost like what CGI-programming does
. Client: data access applying business logic and presentation of data
. Server: serves only as a service-database server, not application server or
a web server
Why J2EE?

6
Drawbacks of
two tier application architecture
. Easy to deploy, but difficult to enhance or
upgrade
. Reusability of business and presentation
logic is difficult
. Not scalable
Why J2EE?

7
J2EE-Separation of Business logic
from Presentation logic
. Presentation logic: Display
. Business logic: What the company wants to do
Example: Distribution of different sales figures by
different departments (business logic) can be
represented in many different ways (pie chart, bar
graph, ...etc)
Why J2EE?

8
Why J2EE?
. Simplifies the complexity of a building
n-tier application(s)
. Standardizes an API between
components and application server
container
. J2EE Application Server and Containers
provide the framework services such as
Security, transaction management, Java
Naming and Directory Interface (JNDI)
lookups, remote connectivity, ...etc.

9
What is J2EE?
. Defines the standard for developing multi tier
enterprise applications
. Simplifies enterprise applications by:
– Basing them on standardized, modular components
– Providing a complete set of services to those
components
– Handling many details of application behavior
automatically, without complex programming

10
J2EE Tiers
. Client Presentation
. HTML or Java applets
deployed in Browser
. XML documents
transmitted over HTTP
. Java clients running in
Client Java Virtual Machine
(JVM)
. Presentation Logic
. Servlets or JavaServer
Pages running on the web
server
. Application Logic
. Enterprise JavaBeans
running in Server

11
J2EE Components & Services
. Components
- Java Servlets
- JavaServer Pages (JSP)
- Enterprise JavaBeans (EJB)
. Standard services & supporting technologies
- Java database connectivity(JDBC) data access API
- Java Messaging Service (JMS)
(Remote Method Invocations (RMI))
- Extensible Markup Languages(XML)
- JavaIDL (Interface Description Language)
- JavaMail
- Java Security
- CORBA technology
- Design Patterns -
http://www.onjava.com/pub/a/onjava/2002/
01/16/patterns.html

12
Advantages of Multi-tiers
. Tiers separate functionality:
– Presentation Logic, Business Logic, Data
Schema
. Easier upgrades since one tier can be
changed/worked on without changing the
rest
. Lower deployment and maintenance cost
. More flexible, more extensible

13
The Big Picture What is J2EE?

14
4-Tier Model
Client Tier Web Tier
Business
Tier
EIS Tier
What is J2EE?
Tier 1 Tier 2
Tier 3
Tier 4

15
Commercial Platforms
. J2EE SDK 1.4 (Sun) http://java.sun.com/j2ee/
. WebLogic 8.1(BEA Systems)
http://www.bea.com/products/weblogic/server/
. WebSphere 5.1(IBM) http://www.ibm.com/websphere
. Oracle Application Server 10g (Oracle)
http://www.oracle.com/appserver/
. JBoss 3.2.3(Open source) http://www.jboss.org
What is J2EE?

16
What is an Application Server ?
.Application servers enable the development of
multi-tiered distributed applications. They are
also known as “middleware”
.An application server acts as the interface
between the database(s), the web servers and
the client browsers
What is J2EE?

17
Application Server: Key Services

18
Enterprise Java Beans (EJBs)
. Entity Beans
. Represent persistent business Entities
. Persisted in storage system (usually Database)
. Session Beans
. Perform work for individual clients on the server
. Encapsulate complex business logic
. Can coordinate transactional work on multiple entity
beans
What is J2EE?

19
States and Persistence
. Session beans can be
– Stateless- belong/available to the client for the duration
of a method call
– Stateful- belong/available to the client for the duration
of the client conversation
. Entity beans can have
– Bean-managed persistence- The developer writes SQL
code to retrieve,store and update database
– Container managed persistence- The developer
provides database mapping information that allows the
container to manage the persistence
What is J2EE?

20
Example of EJB Application
. It consists of number of clients accessing Session
beans and Entity beans
. Each Session bean provides specialized
processing on behalf of client
e.g. A travel agent session bean makes travel reservations while
flight scheduler session bean schedules air planes to fly on various
routes
. Each Entity Bean represents a different type of
business entity.
e.g. Passengers, seats, planes, flights are entity beans
What is J2EE?

bonbonice 2005-01-27
  • 打赏
  • 举报
回复
Database: IBM DB2
Samuel Yi
2004/03/03

Agenda
● How DB2 organizes data?
● How DB2 manages data?
● Performance Tuning in DB2

How Data is organized in DB2
● Node
● Instance
● Database
● TableSpace
● Container, Extent and DataPage

NODE(A Computer)
INSTANCE A
(Database Manager)
INSTANCE B
(Database Manager)
INSTANCE ...
(Database Manager)
How Data is organized in DB2
DATABASE A
(db cfg)
DATABASE B
(db cfg)
DATABASE ...
(db cfg)
TableSpace(s)
with tables,
Views
StoredProcedure
... ...
... ...

NODE
● Can be treat as a computer or a DB2 Server Env.
● A NODE can contain one or more INSTANCEs
● Several INSTANCEs share some of the memory
or code
● Parameters related to Node
– get/reset/update admin cfg

INSTANCE
● An Instance is a database manager
● An Instance can contains one or more database
● Instance administration commands
– Create an instance: db2icrt
– List instance(s): db2ilist
– Drop instance: db2idrop
● Parameters related to an instance
– get/reset/update dbm cfg

DB2 Administration Server (DAS)
● Special DB2 instance to perform administration
tasks
● Created and configured at installation time
● Executes locally all remote administration tasks
requested by a client
● Collects information for DB2 Discovery
● Enables remote monitoring
● Maintenance of DAS
– db2admin create/start/stop/drop

TableSpace
● Table spaces are a logical layer created within
database
● Tables are created within table spaces
● Table can across serveral table spaces.
– Eg, regular data and BLOB data can be saved to different
tablespaces for better perf.
● Two kinds of tablespace: DMS and SMS

DMS vs SMS
● DMS: DB Manager manged storage
– pre-allocated file or raw disk
– manual administration
– cache once
– high perf
– Used for User Data usually.
● SMS: System managed storage
– Directory
– grow/shrink on demand, easy to use and extend
– cache twice
– perf lower than DMS

Some commands related to
Tablespace
● Get tablespace information
– db2 connect to database user username using password
– db2 list tablespaces[ show detail]
– db2 list tablespaces for x [ show detail], “x” stands for
tablespace-id
● Add tablespace by adding a container
– alter tablespace tablespacename add {file|device}
● Increase the size of the existed tablespace
– alter tablespace tablespacename {extend|resize} ...

Container, Extent & Datapage
● Container is an Allocation of Physical Space
● Tablespace must be specified to one or more
container
● Container is composed of extents
● The default size of extent is 32 datapages
● The default size of datapage is 4K

How DB2 manages data?
● Processes in DB2 Server
– Coordinator agents: performs most SQL processing on
behalf of app
– Subagents: a set of subagents can be assigned to
process the client app request.
– Prefetcher: retrieve data from disk and move it into the
buffer pool before applications need the data.
– Page cleaner: move data from the buffer pool back out
to disk.
– Deadlock detector
– Logger


● Multipage file allocation
– Allocate pages faster by allocating extent instead of
datapage.
– Use command "db2empfa <databasename>"
(disconnect all connections first)
– Applicable when
● Tablespace type is SMS
● Want to insert lots of lines into a table
– Refer to parameter: Multi-page file allocation enabled in
"db2 get db cfg for <dbname>"
Performance tuning - insert perf

Insert Performance tuning(cont'd)
● Increase size of Bufferpool
– Default is 250 pages(4K) on windows, 1000 pages on
unix
– Alter bufferpool <bpname> size <newsize>
– Consideration
● Reducing CHNGPGS_THRESH for more "dirty page"
writing
● Increase LOGFILSIZ/LOGPRIMARY to avoid secondary
log allocation caused by increased insert speed
● Increase NUM_IOCLEANERS

Insert Performance tuning(cont'd)
● Place log to separate disk
– Insert, update, delete need write log for rollback
● Performance of import: log & bufferpool
– Insert line by line
– Commit at last
● Performance of load: utility heap and sortheap
– Building indexes costs time

Delete performance tuning
● Delete all data in a table
– If you're sure that you want to delete all the data in a
table with lots of records, you can
● Drop and re-create table
● "Alter table <tablename> activate not logged initially with
empty table" to avoid logging
– Considerations: not recoverable

Performance tuning tools
● Runstats, reorg & rebind
– db2 runstats on table schema.tablename for indexes all
– db2 reorg table tablename
● Configuration advisor
– Need you to answer some questions such as memory
size, disk speed, connections etc and the tool can give
suggestion on configuration
● Index advisor
– Input your business SQL statements and the tool can
give you suggestion about creating what kinds of
indexes.

Application perf tuning
● Stored procedure
– Precompiled SQL statements
– Reduce network communication
– Calculation executed on server
● Compound SQL
– Serveral SQL statements execute in a single block
– Reduce network communication
– Limitations: static SQL statements only, can only be
embedded in code

Application perf tuning(cont'd)
● Effiency select statement
– Specify only columns needed instead of using "*"
– Avoid data type conversions if possible
– Using simple datatype if possible
● Char instead of varchar for simple character column
● Integer instead of float and decimal
● Datetime instead of char
● Numberic instead of char
– Don't use "distinct" or "order by" if not required
– Use join instead of subquery
– Create indexes on join columns

Some tips in using DB2
● quit, terminate, connect reset are different in DB2
command line utility
– quit won't disconnect from the DB2 server if connected
– terminate will disconnect from DB2 and quit from DB2
– connect reset will disconnect if connected and won't
quit from command line utility
● "db2look" to display the DDL of table(s) or the
whole database
– "db2look -d dbname -e -i userID -w password" to
display DDL for whole database
– "db2look -d dbname -e -i userID -w password -t
tablename" to display DDL for specified table

Online Resources
● DB2 RedBooks
– http://publib-b.boulder.ibm.com/redbooks.nsf/portals/Data
● DB2 Trial version download
– http://www14.software.ibm.com/webapp/download/product.jsp?● DB2 Patch download

bigbugice 2005-01-27
  • 打赏
  • 举报
回复

19
Mem Mgmt Tips in C++
Wrap the dynamic memory operation into class
Constructor allocates, destructor de-allocates
Shallow copy, deep copy
Reference counting: ties dynamic lifetime to a
group of references
Copy-on-write: allows more efficient
management of multiple aliasing

20
Constructor, Destructor
#ifndef IntArray_H
#define IntArray_H
class IntArray {
public:
IntArray(const int
size);
~IntArray();
private:
int m_size;
int *m_values;
};
#endif
. Resources allocated by an object
need to be freed
. Constructor, destructor offer
good start/end points
. Fixed size array
– Can store integer values
– Can access elements
– Size may differ for each object
– Once set, array size is fixed

21
Constructor, Destructor(Cont'd)
#include “IntArray.h"
IntArray::IntArray(int s)
:m_size(s), m_values(NULL) {
if (m_size > 0) {
m_values = new int[m_size];
if (m_values == NULL) {
m_size = 0;
}
}
}
IntArray::~IntArray() {
delete [] m_values;
}
. IntArray initialization
– Sets m_size
– NULLs out the pointer
. Only allocate if length is
greater than zero
. What does new do?
– Allocates memory
– Calls constructor(s)
. What does delete do?
– Calls destructor(s)
– Frees memory
. Difference “new” vs “new []"
and “delete" vs "delete[]"

22
Shallow copy
Two ways to “copy”
Shallow: aliases existing resources
Deep: makes a complete and separate copy
Following code shows shallow copy
IntArray::IntArray(const IntArray &a)
:m_size(a.m_size), m_values(a.m_values) {
}
Efficient
But may be risky. Why?
What’s unchanged?
m_size, m_values

23
Deep copy
Version to left shows deep
copy
Safe: no aliasing
But may not be very efficient
Note trade-offs with arrays
Allocate memory once
More efficient than multiple
calls to new (heap search)
Constructor and assignment
called on each array element
Less efficient than block
copy
But sometimes more correct
IntArray::IntArray(const IntArray &a)
:m_size(a.m_size), m_values(NULL) {
if (m_size > 0) {
m_values = int[m_size];
if (m_values == NULL) {
m_size = 0;
}
for(int i = 0; i < m_size; ++i) {
m_values[i] = a.m_values[i];
}
}
}

24
Reference counting
Resource
counter == 3
reference
reference
reference
Basic Problem
Resource sharing is efficient
But hard to tell when done
Must avoid early deletion
Must avoid leaks
Solution
Share resource and a counter
Each new reference
increments the counter
When a reference is done, it
decrements the counter
When count drops to zero,
delete resource and counter

25
Copy on write
Resource
counter == 2
reference
reference
reference
Resource 2
counter == 1
write()
Basic Problem
Reference counting enables
safe and efficient sharing
But what about modifications?
May want logically separate
copies of resource
Solution
Start with reference counting
Writer checks for count > 1
. Copies reference & counter
. Updates both counters
. Performs the write
Readers all share a copy,
each writer can get its own

26
Tips summary
Know what goes where in memory
Understand mechanics of stack and dynamic allocation
Watch for simple lifetime errors
Consider more subtle scope/lifetime issues
Pay attention to aliasing (draw a picture)
Think about shallow versus deep copying trade-offs
Master useful tips for C++ memory management
Learn how they work
Understand when to apply them
Look for ways to apply them in the labs and beyond
Avoid pointers when you can
Encapsulate them within classes

27
Useful tools to facilitate C++ programming
Microsoft .net
Rational Purify
ZeroFault(Aix)
Memdebug
ParaSoft Insure++

28
Detect memory leak using .net
Define a symbol to turn on a special debug
version of the heap functions that manage
memory allocation
#define CRTDBG_MAP_ALLOC
Include a non-Standard header that declares
some Windows-specific diagnostic functions
#include <crtdbg.h>
Call a diagnostic function to report any detected
leaks
_CrtDumpMemoryLeaks();

29
Detect memory leak using .net sample
// testmemoryleak.cpp : Entry point of console application
#include "stdafx.h"
#include <iostream>
#include <new>
using namespace std;
#define CRTDBG_MAP_ALLOC // selects debug version of heap functions
#include <stdlib.h>
#include <crtdbg.h> // non-Standard header for memory diagnostics
void F() {
int* p = new int[100]; // allocate 100 * sizeof(int) bytes
}
int _tmain(int argc, _TCHAR* argv[]) {
int* p = new int[1000]; // allocate 1000 * sizeof(int) bytes
F();
return _CrtDumpMemoryLeaks();
}
Call diagnostic func here in order to
make sure that all relevant destructors
have been executed first.

30
Detect Memory Leak in .Net: Result
Compile and run the sample in debug mode
Result:
'testmemoryleak.exe': Loaded
'D:\Temp\testmemoryleak\Debug\testmemoryleak.exe', Symbols loaded.
'testmemoryleak.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', No symbols
loaded.
'testmemoryleak.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll', No symbols
loaded.
Detected memory leaks!
Dumping objects ->
{60} normal block at 0x00370FF0, 400 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{59} normal block at 0x00373EE8, 4000 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
The program '[2296] testmemoryleak.exe: Native' has exited with code 1 (0x1).

31
IBM Rational Purify
A runtime analysis tool
Can verify applications written in C/C++, Java,
and all VS.net languages such as c#, VB.net
Crucial Functionalities:
Memory leak detection
Memory corruption detection
Memory access error detection
Java Garbage Collection issue detection
COM related error detection
Pointer/Windows API/Handle related error detection

32

33
ZeroFault(www.zerofault.com)
An commercial AIX specific memory error and
leak detection tool
Detects a comprehensive set of memory errors
Reads/writes of unallocated stack, heap, and static
memory
Reads/writes of freed heap memory
Reads of uninitialized stack, heap, and static
memory
Attempts to free or realloc unallocated memory
Several types of memory leaks

34
ZeroFault(Cont'd)
Works on any existing AIX 32-bit executable
Uses run-time emulator(virtual machine), no
recompilation or relinking
Checks shared libraries and dynamically loaded
modules, including 3rd-party libraries
Works on all apps (including “ tool-killers”) tried so far
ZeroFault limitations
Slow-down the app by 8~40times, cost 2times of mem
Instruction-set dependent
. use -qarch=604 to pickcompatible instruction set

35
Other tools
Memdebug
Operate at library level
Intercept calls to memory management
routines
Insure++(www.parasoft.com)
Source code level tool: rewrite the source
code of the app
Re-compile, re-link needed

36
Insure++
Detect errors like
Memory corruption due to reading or writing beyond the valid
areas of global, local, shared, and dynamically allocated
objects.
Operations on uninitialized, NULL, or "wild" pointers.
Memory leaks.
Errors allocating and freeing dynamic memory.
String manipulation errors.
Operations on pointers to unrelated data blocks.
Invalid pointer operations.
Incompatible variable declarations.
Mismatched variable types in printf and scanf argument lists.
bigbugice 2005-01-27
  • 打赏
  • 举报
回复
Memory Management
Practice in C++
Augmentum – Shanghai
June 19, 2004

2
Agenda
Overview
Memory issues in C++
Memory management tips in C++
Useful tools

Overview
4 major memory segments
Global: variables outside stack,
heap
Code (a.k.a. text): the compiled
program
Heap: dynamically allocated
variables
Stack: parameters, automatic
and temporary variables
stack
heap
code
global

4
Overview(Cont'd)
Code and global use is fixed
Code segment is “read-only”
Heap and stack use varies dynamically
Key differences from Java
Destructor of automatic variables called when stack
frame pops
No garbage collection: program must explicitly free
dynamic memory

5
Illustrating C++ Memory
int g_default_value = 1;
int main (int argc, char **argv) {
Foo *f = new Foo;
f->setValue(g_default_value);
delete f;
return 0;
}
void Foo::setValue(int v) {
m_value = v;
}
stack
heap
code
global g_default_value
Foo *f
Foo *this
int v
m_value

6
Memory Allocation
Stack vs. heap
Stack grows down
Heap grows up
Static Memory
Size fixed during compilation
Has scope
Allocated on stack
Dynamic Memory
Variable size – created at run time
Allocated on heap using new
Alive until deallocated using delete
...
0xFF
Heap
0xFD
0xFC
0x03
0x02
0x01
0x00
0xFE
Stack

7
Stack Memory
Stack is limited(Following test is in Linux 8.0)
#include <stdio.h>
int main(int argc, char** argv) {
int arr[1024*1024*2]; // cause stack overflow at runtime
// 1024*2047 will be ok
memset(arr, 0x00, sizeof(arr));
return 0;
}
Execution result: Memory fault
Different OS has different limitation

8
Stack Memory(Cont'd)
Stack is automatically recycled if out of scope
using namespace std;
{
string str("Hello wold"); // Object
int arr[128]; // Array
...
}
// The memory allocated for str and arr will be recycled
automatically after the scope

9
Heap Memory
Heap is huge
can be expanded to Virtual Memory
Heap is slower than Stack
Heap need to be allocated and deallocated
manually
int *arr = new int[1024*1024*2];
...
delete [] arr;

10
Allocate and free dynamic memory
new vs delete
new features in c++ compare to c language
easy to use, no need to do type conversion
malloc, calloc, realloc vs free
Prototype
. void *malloc(size_t size);
. void *calloc(size_t nmemb, size_t size);
. void *realloc(void *ptr, size_t size);
. void free(void *ptr);
Must do type conversion
. long *buffer = (long *)calloc(40, sizeof(long));
. free(buffer)

11
Memory issues in C++
Memory initialization – Programmer's responsibility
Memory life cycle issue
Dangling pointers
Pointers to memory that has already been deallocated
Result in: segment fault (core dump)... or worse....
Invalid memory access
Memory Leak
Losing pointers to dynamically allocated memory
Substantial problem in many commercial products
. Even in Windows 98

12
Memory initialization issue
int main(int argc, char **argv)
{
Foo *f;
cout << f->value() << endl;
for (int i; i < argc; ++i)
cout << argv [i] << endl;
return 0;
}
. Heap and stack memory is not
initialized for us in C++
– Get whatever was out in
memory
– Unless we initialize it ourselves
– So we should always do so
. What happens when we
dereference pointer f?
– If we’re lucky, a program crash
– If not, we get bad output
– Or worse, a local over-write,
leading to problems later
. Is there anything else wrong
with this code?

13
Memory life cycle issue
Foo *bad() {
Foo f;
return &f;
}
Foo &alsoBad() {
Foo f;
return f;
}
Foo mediocre() {
Foo f;
return f;
}
Foo *better() {
Foo *f = new Foo;
return f;
}
. Automatic variables
– Are destroyed on function return
– But in bad, we return a pointer to a
variable that no longer exists
– Reference from also_bad similar
– Like an un-initialized pointer
. What if we returned a copy?
– Ok, we avoid the bad pointer, and end up
with an actual object
– But we do twice the work (why?)
– And, it’s a temporary variable (more on this
next)
. We really want dynamic allocation here

14
Memory life cycle issue(Cont'd)
int main() {
Foo *f = &mediocre();
cout << good()->value() <<
endl;
return 0;
}
Foo mediocre() {
Foo f;
return f;
}
Foo *good() {
return new Calculator;
}
. Dynamically allocated variables
– Are not garbage collected
– But are lost if no one refers to
them: called a “memory leak”
. Temporary variables
– Are destroyed at end of statement
– Similar to problems w/ automatics
. Can you find 2 problems?
– One with a temporary variable
– One with dynamic allocation
. Important intuition
– Incorrect use is the real problem
here
– Need to understand the details

15
Dangling pointer sample: Aliasing
int main (int argc, char **argv) {
Foo f;
Foo *g = &f;
Foo &h = f;
delete g;
return 0;
}
. Multiple aliases for same object
– f is a simple alias, the object itself
– g is a variable holding a pointer
– h is a variable holding a reference
. What happens when we call delete
on g?
– Destroy a stack variable (may get a
bus error there if we’re lucky)
– If not, we may crash in destructor of f
at function exit
– Or worse, a local stack corruption
that may lead to problems later
. Problem: object destroyed but
another alias to it was then used
Foo *g
Foo &h
Foo f

16
Invalid memory access
int main (int argc, char **argv) {
Foo *f = new Foo();
...
delete f;
...
delete f;
return 0;
}
. Similar failure to the previous
sample
– Invalid memory access
– Or, Access violation
. Not easy to find if deallocation
spreads in different place of a
project
. Good habit to avoid multi-deletion
if( f ) delete f;
f = NULL;
. It's safe to delete NULL pointer
multi-times

17
Memory leak examples
int main(){
int *myNum = new int(12);
myNum = new int(10);
delete myNum;
return 0;
}
How many bytes of memory is leaked in the
following 2 sample code respectively?
int main(){
int *myNum = new int[12];
myNum = new int[10];
delete myNum;
return 0;
}
int[10]
...
Heap
...
int[12]
...
0x01
0x00
myNum

18
“new” in C++ vs Java
Similar “new” code has different result in C++
vs Java
The following C++ code has memory leak
using namespace std;
string *strHello = new string("hello");
string *strWorld = new string("world");
strWorld = strHello;
The following Java code has no memory leak
String strHello = new String("hello");
String strWorld = new String("world");
strWorld = strHello;

bonbonice 2005-01-27
  • 打赏
  • 举报
回复
Single Byte and Double Byte
Encoding
Single Byte Encoding
Each character is one byte
.US ASCII
.ISO-Latin-n (IS0-8859-n)
–N ranges from 1 to 9
Double Byte Encoding
Each character is 2 bytes
.GB2312, EUC_CN
.Big 5, EUC_TW
.Shift JIS, EUC_JP

Double Byte Encoding
Most Double Byte Encodings are really
variable byte encoding
Definition includes the us 7 bit ASCII (0 –
127) range
No difference if only 7 bit ASCII is used
Can be one or 2 bytes
UCS –2 (2 byte Unicode)
True double byte encoding

Internationalization in Java
Java uses Unicode
All software written in Java is
Internationalized –WRONG
Using Unicode is a step forward
There are still a few things to do

Simple Program to Demonstrate the
problem
public static void main(String[] args) {
String s1 = “\ue565”; // character 日
byte[] ba= s1.getBytes();
System.out.println("numberof bytes: " + ba.length);
String s2 = new String(ba);
// is s1 same as s2?
}
What is the output of this program?

Implicit code conversion
IO methods
Converts Unicode to local encoding on
output
Converts local encoding to Unicode on
input
String manipulation methods
getBytes(String)
String(byte[])

Java IO/String Manipulation
Methods
IO
Force to read in specific encoding
fis= new FileInputStream(INPUTFILE);
isr= new InputStreamReader(fis, charsetName);
br= new BufferedReader(isr);
String s = br.readline();
Force to write in specific encoding
fos= new FileOutputStream(OUTPUTFILE);
osw= new OutputStreamWriter(fos, charsetName);
bw= new BufferedWriter(osw);
bw.write(s, 0, s.length()):
String Manipulation
getBytes(s, charsetName)

Exercise
Write a program that takes a file
encoded in one encoding to another
encoding
Program takes 4 parameters
Input file name
Input file encoding
Output file name
Output file encoding

Java Resource Bundle
All Strings that needs to be localized should
be stored in resource bundle
Should I see hard coded Strings in the code
anymore?
Built-in Java facility to locate the appropriate
bundle
You need to follow the naming convention
Java will load the appropriate bundle for you
Can have a default bundle to cover locales that
have no bundle

XML Document
Self describing
No need to specify externally the encoding of the document
Have encoding=“….”in the header to tell you the encoding of
the document
Specification defines how you can extract the encoding
information and switch encoding to read the rest of the
document
Typical way
Read first 200 bytes as byte[]
Locate encoding =
Switch encoding accordingly
Why need to read as byte array?
How do you deal with EBCDIC encoding

How to handle XML Document?
If you do not have to look at content
Keep as byte[]
Avoid using Java String (i.e. Unicode)
After conversion to Unicode, technically the
document is “corrupted”
Encoding should be Unicode in the header
If you switch, you do not have information to
switch it back to original encoding
Most parser will ignore the encoding= if the input
is String rather than byte[]

C++/C
Strings that need localization should be in
equivalent of resource bundle
Char versus wchar
Manipulating routines are available to handle wide
char type just like char
If you handle wcharwith char or as bytes you
need to be careful
.Byte Ordering is important
String and wstring
Similar to char and wchar

C++/C
Software that deals with multi-byte characters are
less portable across platform
Different compilers has different classes and method
They are not 100% compatible with each other
Most likely need to use #ifdeffor individual platform
Most application vendors has classes to encapsulate
all manipulation routines
To facilitate porting
Provided classes work the same on all platforms
Programmer does not have to know
Need to store Strings as Unicode
Cannot store string as local encoding

UI Consideration
Labels
Alignment
Tabs
Fixed size vsvariable size
Edit Box
Height and width
Many more

HTML Form Input
How can you write code to accept any
language for Form Get/Post
Only the browser knows the current locale
Transport data in Unicode or UTF-8
IE Browser setting to send URL with UTF-8
encoded
Is there any difference between get and
post

Exercise
Create a HTML Form
Use English locale
Input Chinese Character
Can you get the Chinese Character?
Can you write code so that you can run
on any locale and get double byte or
single byte character back correctly?

Summary
Internal only work on one encoding
UTF-8 or Unicode
Encoding conversion should be done at input/output
to/from system
Keep data as byte[] if you do not have to touch it
You would not be able to convert to string inside the system
You need to know the encoding before you can construct
the string correctly
Strings that need localization should not be part of
the code
Use resource string/bundle
bonbonice 2005-01-27
  • 打赏
  • 举报
回复
Internationalization and
Localization of Software
Victor To

Agenda
Definition of terms
Encoding
XML Document Handling
I18n programming with Java/C++

Internationalization (I18n)
Internationalization
A process or work to make software be
able to operate in different language
environment
.Can process data in different languages
.Can adapt to multiple locales thru localization
Some time known as I18n or globalization
Traditionally, software was design and
develop to run in US English environment

Internationalization
Typical work
Externalization of strings, icons and graphics with
text
Selecting code page and defining code page
conversions (if needed)
Modifying all the text manipulation functions to be
aware of the code pageChangingthe logic of all
the formatting functions (date, time, currency,
numeric etc.)
Changing the logic in collation/sorting functions

Localization (L10n)
Sometime known as L10n
Process of adapting software to a
particular locale
Typical work
Translation
.Document
.UI text display
.Error messages

Differences between I18n and L10n
Is there any difference between I18n or
L10n?
Which step do you need to do first?
I18n or L10n
For example, after the software is localized to
Simplified Chinese, do you expect code
change in order to support Traditional
Chinese?
What about Japanese?

Locale
Definition
A set of information that corresponds to a given language and
country
A locale affects the language of predefined programming terms
and locale-specific settings
What are affected by the locale settings:
Decimal and list separators
Time and Date formats
Character sorting order
Error messages
System locale affects the setting of the system
Application should be able to run in different locales
How do you set the locale on Windows and Unix?

When do we Internationalize an
application?
We should have i18n from the very
beginning
All software runs in different
environment
Installed in US but process data from China
Retrofitting is a costly exercise

Character Encoding
Code page
Defines the mapping of characters to their respective numeric
value
Same character is mapped to different numeric values in different
code pages
.日character
–E565 in Unicode
–4053 in GB
–A4E9 in Big 5 (Traditional Chinese)
–E697A5 in UTF 8
Code Plane
Chinese language cannot be represented by one single double bytecode page (< 7000 chars)
Multiple PLANES are required to defined the entire language
For most practical use, only one plane is used
CNS defines 12 planes

Popular Encoding
Simplified Chinese
GB 2312, GBK, EUC_CN, GB 18030, CP936
(Microsoft variant of GBK)
Traditional
Big 5, EUC_TW, CNS 11643, CP950 (Microsoft
variant of Big 5)
Japanese
Shift JIS, EUC_JP, MS930, CP930 (variant of SJIS
by Microsoft)

Unicode
Attempt to define all existing characters into a single
code page
Provide a unique numeric value to each and every
character
UCS-2 (2 bytes Unicode)
UCS-4 (4 bytes Unicode)
UTF-8 (Unicode Transformation Format)
www.unicode.orghas a lot of good information
Current version is 4.0
No all characters are defined
Possible duplicates (same characters appears twice in
the definition for v3.0)

Various Unicode Encoding

Unicode Transformation Format
(UTF)
UTF
UTF-8
.Store in 8 bit units
UTF-16
.Store in 16 bit units
UTF-32
.Store in 32 bit units

UTF -8
Scalar Value
1st Byte
2nd Byte
3rd Byte
4th Byte
00000000 0xxxxxxx
0xxxxxxx
00000yyy yyxxxxxx
110yyyyy
10xxxxxx
zzzzyyyyyyxxxxxx
1110zzzz
10yyyyyy
10xxxxxx
000uuuuu zzzzyyyyyyxxxxxx
11110uuu
10uuzzzz
10yyyyyy
10xxxxxx

Characteristics of UTF-8
Each character is represented by one to four
bytes
No byte ordering
Each unit (i.e. 1 byte to 4 bytes) has unique
bits in each byte
Can detect illegal byte ordering
More popular then UTF-16 and UTF-32
UTF-16 and UTF-32 has similar properties


bigbugice 2005-01-27
  • 打赏
  • 举报
回复

Writing Multi-Threaded Programs
Need to understand the perils
Race condition, Deadlock and Starvation
Need to understand the solutions
Mutual Exclusion and Deadlock Avoidance
Need to understand the design patterns
Thread pools, consumer/producer, etc.

Mutual Exclusion
Certain code blocks cannot be
interrupted once begun; i.e., they
execute to completion.
public synchronizedvoid run() {
if (isZero())
incr();
}

Deadlock Avoidance
Prevent deadlocks from ever happening i.e.
prevent a cyclic wait on shared resources
Acquire locks in a well-defined order
public void m1() {
synchronized(lck1) {
doM1();
synchronized(lck2) {
….
}
}
}
public void m2() {
synchronized(lck1){
doM2();
synchronized(lck2){
….
}
}
}

Writing Multi-Threaded Programs
Need to understand the perils
Race condition, Deadlock and Starvation
Need to understand the solutions
Mutual Exclusion and Deadlock Avoidance
Need to understand the design patterns
Thread pools, consumer/producer, etc

Thread Pools
Creating threads is expensive. Creating
and destroying threads for short
durations is expensive
Create a “pool”of threads and reuse
them

Thread Pools –Common Errors
Deadlock
Thread pool is not large enough. A task is
waiting, but the task that can resume it
does not have a thread to run
Leakage
A thread is never returned to the pool

Thread Pool -Leakage
while (true) {
synchronized(queue) {
while (queue.isEmpty()) {
queue.wait();
}
r = (Runnable)queue.removeFirst();
}
r.run();
}
Need to catch RuntimeException

Thread Pool Size
On CPU bound tasks, you generally
achieve best CPU utilization using N
threads
On others, it should be around N*(1 +
WT/ST) where WT is wait time and ST
is service time

Consumers/Producers
Some threads produces data (e.g. some
work that needs to be done), and other
threads consumes that data
A bufferis shared between the threads
to exchange data
Common usage is when a producer
does not want to wait while the work is
being done

Consumers/Producers –Common Error
public synchronized void enqueueBuffer(Bufferb) {
if (buffers.size() == 0)
notify();
buffers.add(b);
}
public synchronized Buffer dequeueBuffer() {
if (buffers.size() == 0)
wait();
Buffer firstBuffer=
(Buffer)buffers.remove(0);
return firstBuffer;
}
while loop

Task #1 –How to fix the deadlock in
Dining Philosophers?

Task #2 –What is the Error here?
public void enQueue(Stringvalue) {
QueueItemnewOne= new QueueItem(value);
QueueItemoldTail= tail;
tail = newOne;
oldTail.nextItem(newOne);
}
tail

Task #3 –What is the Error here?
public class Sum {
public synchronized void getPartialResults() {return localResults;}
public synchronized void run() {
localResults= …
System.out.println(“Total:”+ (localResults+ peer.getPartialResults()));
}
public static void main() {
Sum c1 = new Sum(“1..20”);
Sum c2 = new Sum(“21..40”);
c1.setPeer(c2);
c2.setPeer(c1);

}

Task #4 –What is the Error here?
public void func() throws IOException{
lock();
doReadFile();
unlock();
}
public void doReadFile() throws IOException{…}

Task #5 –Implement a Counting
Semaphore
Allows at most nthreads to execute a
function

Stack Trace
Java stack trace is a user-friendly
snapshot of the threads and monitors in
a Java Virtual Machine (JVM)
Extremely useful in determining what is
going on –what each thread is doing, if
there is a deadlock, infinite loop,
starvation, etc

Generating a Stack Trace
Send a signal to the JVM
On UNIX platforms, you can send a signal to a
program by using the kill command. This is the
quit signal, which is handled by the JVM.
Alternatively you can enter the key sequence
<ctrl>\in the window where the Java program
was started.
On Windows, enter the key sequence
<ctrl><break>in the window where the Java
program is running

A Example Stack Trace
Full thread dump Java HotSpot(TM) Client VM (1.4.1_05-b01 mixedmode):
"DestroyJavaVM" prio=5 tid=0x00034760 nid=0xf68 waiting on condition [0..7fadc]
"Thread-2" prio=5tid=0x00A0E078 nid=0xf38 waiting for monitor entry[ac9f000..ac9fd8c]
at ComputePrime.getPrimes(ComputePrime.java:15)
-waiting to lock <02A9D3B0>(a ComputePrime)
at ComputePrime.getAllPrimes(ComputePrime.java:20)
-locked <02A9D688>(a ComputePrime)
at ComputePrime.run(ComputePrime.java:24)
"Thread-1" prio=5 tid=0x00A0E480 nid=0xe78 waiting for monitor entry[ac5f000..ac5fd8c]
at ComputePrime.getPrimes(ComputePrime.java:15)
-waiting to lock <02A9D688>(a ComputePrime)
at ComputePrime.getAllPrimes(ComputePrime.java:20)
-locked <02A9D3B0>(a ComputePrime)
at ComputePrime.run(ComputePrime.java:24)
"Signal Dispatcher" daemon prio=10 tid=0x009E7F38 nid=0xcc0 waiting on condition[0..0]

Example Stack Trace (continued)
Found one Java-level deadlock:
=============================
"Thread-2":
waiting to lock monitor 0x3dca4 (object 0x2a9d3b0, a ComputePrime),
which is held by "Thread-1"
"Thread-1":
waiting to lock monitor 0x3dc84 (object 0x2a9d688, a ComputePrime),
which is held by "Thread-2"

Stack Traces are Extremely Useful
For hanging, deadlocked or frozen programs:
If you think your program is hanging,
generate a stack trace and examine the
threads.
For busy programs: The best course of action
you can take for busy programs is to
generate frequent stack traces. This will
narrow down the code path that is causing
the errors, and you can then start your
investigation from there.
bigbugice 2005-01-27
  • 打赏
  • 举报
回复
Training
March 6, 2004
Multi-threading in Java

Agenda
-Highlights from Gilbert’s Porting session
-Multi-threading in Java –What, Why,
-How and How not
-Workshop –Programming Exercises

Porting Highlights
-“Translating”software to run on a different computer and/or operating system
-Same binaries cannot run on different platforms
-Different system services on different platforms
-Compiler differences
-Common Porting Issues
-Initialization order of globals
-Non-portable code. E.g. size of primitives
-Memory Errors
-Porting tips
-Modularize platform dependent code
-Follow the C/C++ standards faithfully
-Cross check against other platforms
-Scheduling
-Only 10% complete when the code compiles and links
-Testing and debugging are the most time consuming tasks

Agenda
Highlights from Gilbert’s Porting session
Multi-threading in Java –What, Why,
How and How not
Workshop –Programming Exercises

What is Multi-Threading in Java?
-Allows a Java program to have multiple “Threads”
-Sequences of executionwithin the same program that share the same codeand data address space. Each Thread has its own stackto make method calls and store local variables

A Multi-threaded Java Program
public class MultiThreadedimplements Runnable{
private String name= “MultiThreaded”;
public void run() {
intnumber= rand();
for (inti= 0; i < 5; i++)
System.out.println(Thread.currentThread() +
“Number:“+ (number+i) +
“Program: “+ name);
}
public static void main(String[] args) {
MultiThreadedt = new MultiThreaded();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);

}
Share codeMultiple StacksShare data

Program Output
Thread[Thread-1,5,main] Number:1108874836Program: MultiThreaded
Thread[Thread-1,5,main] Number:1108874837 Program: MultiThreaded
Thread[Thread-1,5,main] Number:1108874838 Program: MultiThreaded
Thread[Thread-1,5,main] Number:1108874839 Program: MultiThreaded
Thread[Thread-1,5,main] Number:1108874840 Program: MultiThreaded
Thread[Thread-2,5,main] Number:1033792848Program: MultiThreaded
Thread[Thread-2,5,main] Number:1033792849 Program: MultiThreaded
Thread[Thread-2,5,main] Number:1033792850 Program: MultiThreaded
Thread[Thread-2,5,main] Number:1033792851 Program: MultiThreaded
Thread[Thread-2,5,main] Number:1033792852 Program: MultiThreaded

Multi-threading is Inherent in Java!
-You cannot write a program that is not multi-threaded!
-Even a “single”threaded program has other threads created by the JVM
-Garbage collector
-Signal handler
-…
-A “single”treaded program has one user thread, and rest system threads

Multi-threading Does Not Imply “Parallel”
-On a single CPU machine, only onethread can be active at any time.
-However, different threads can run at different times based on
-Time slicing –each thread gets to execute for some amount of time
-Priority –a “runnable”higher priority thread will always execute before a runnablelower priority thread
-Multi-CPU machines, however, can have multiplethreads running at the same time.

Thread Scheduling Example #1
public void run() {
for (inti = 0; i < 40; i++) {
System.out.println("name=" +
name);
}
}
public static void main(){
t1 one = new t1("one");
t1 two = new t1("two");

}
name =onename =onename =onename =onename =onename =onename =onename =onename =twoname =twoname =twoname =twoname =twoname =twoname =twoname =onename =one…

Thread Scheduling Example #2
public void run() {
for (inti = 0; i < 40; i++) {
System.out.println("name=" +
name);
sleep(10);
}
}
public static void main(){
t1 one = new t1("one");
t1 two = new t1("two");

}
name =onename =twoname =onename =twoname =onename =twoname =onename =twoname =onename =twoname =onename =twoname =one…

Thread Scheduling Example #3
public void run() {
for (inti = 0; i < 40; i++) {
System.out.println("name=" +
name);
sleep(10);
}
}
public static void main() {
t1 one = new t1("one");
t1 two = new t1("two");
one.setPriority(10);
two.setPriority(1);

}
name =onename =onename =onename =onename =onename =onename =one……
name =twoname =twoname =twoname =twoname =twoname =two…

Agenda
Highlights from Gilbert’s Porting session
Multi-threading in Java–What, Why,
How and How not
Workshop –Programming Exercises

Why Use Theads?
-Programs can run faster on multi-CPU machines
-Programs can run faster –evenon single-CPU machines
-E.g. a program that needs to block for I/O
-Results in simpler code
-E.g. a Cancelbutton on a GUI

Agenda
Highlights from Gilbert’s Porting session
Multi-threading in Java –What, Why,
How and How not
Workshop –Programming Exercises

Writing Multi-Threaded Programs
Need to understand the perils
Race condition, Deadlock and Starvation
Need to understand the solutions
Mutual Exclusion and Deadlock Avoidance
Need to understand the design patterns
Thread pools, consumer/producer, etc.

What is Wrong Here?
private intcount;
public synchronized booleanisZero() {
return (count == 0);
}
public synchronized void incr() {
count++;
}
public void run() {
if (isZero())
incr();
}
Thread1: isZero()
Thread2: isZero()
Thread2: incr()
Thread1: incr()

Race Condition
Multiple threads updating the same
data at the same time
Different runs may produce different
results

What is Wrong Here?
public void m1() {
synchronized(lck1) {
doM1();
synchronized(lck2) {
….
}
}
}
public void m2() {
synchronized(lck2) {
doM2();
synchronized(lck1) {
….
}
}
}
Thread1: doM1()
Thread2: doM2()

Deadlock
Cyclic wait among two or more threads to
acquire two or more shared resources
Dining
Philosophers

Starvation
One or more threads never get a
chance to run
Can happen if there are threads with
different priorities
Higher priority threads never yield the
CPU –common problem in earlier
versions of the JDK with the garbage
collector
加载更多回复(28)

3,423

社区成员

发帖
与我相关
我的任务
社区描述
其他开发语言 其他开发语言
社区管理员
  • 其他开发语言社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧