Anda di halaman 1dari 70

Threads Monitors and Resource Contention

Page 1
Copyright 2001 Hewlett-Packard Company

Threads Monitors Contention

Learning objectives

At the end of this session you will be able to: Recognize and explain:
The correct usage of threads in Java How to recognize contention The best way to avoid contention

Use a simple method to obtain a full thread dump


Detect a thread deadlock

Discuss the different data structures available Determine the optimal number of threads required

Page 2
2001 Hewlett-Packard Company

Threads Monitors Contention

Glance/gpm System Level View of Threads

I/O CPU

Scheduling

Page 3
2001 Hewlett-Packard Company

Threads Monitors Contention

HPjmeter Java Process View of Threads


Thread 31

4 5 6

CPU GC

Thread 0

CPU

7
Page 4
2001 Hewlett-Packard Company

Threads Monitors Contention

HPjmeter Thread Call Graph

Page 5
2001 Hewlett-Packard Company

Threads Monitors Contention

JVM Thread Stack Trace

Generate with: kill s SIGQUIT <pid> Dumps stack trace of every Java thread
Includes monitor information
waiting on locked

Includes operating system thread id


Maps between Java and Glance

Easy to read, but much information

Page 6
2001 Hewlett-Packard Company

Threads Monitors Contention

Tools Available JVM Thread Stack Trace: locking

"Worker Thread 17" prio=9 tid=0x1310b70 nid=41 lwp_id=14165 suspended [0x1194d000..0x11948478]


at fields.FieldPropertiesLibraryLoader.forClass(FieldPropertiesLibraryLoader.java:67)

- waiting to lock <0x3ca45848> (a java.lang.Object)


at fields.FieldsServiceImpl.getFpl(FieldsServiceImpl.java:75) at fields.FieldsServiceImpl.getFpl(FieldsServiceImpl.java:64) at base.core.BaseObject.getFpl(BaseObject.java:2930) at base.core.BaseObject.getFieldProperties(BaseObject.java:2661) at core.BaseObject.getFieldProperties(BaseObject.java:2670) at fields.FieldProperties.getFieldsInGroup(FieldProperties.java:1157) at fields.FieldProperties.getFieldsInGroup(FieldProperties.java:1107)

Page 7
2001 Hewlett-Packard Company

Threads Monitors Contention

Tools Available JVM Thread Stack Trace: waiting

"Reader Thread 12" prio=10 tid=0x135c290 nid=85 lwp_id=14212 waiting on monitor [0xed1c000..0xed1c478]
at java.lang.Object.wait(Native Method)

- waiting on <0x3df92650> (a rpc.server.ClientReader)


at java.lang.Object.wait(Object.java:424) at server.ClientReader.run(ClientAcceptLoop.java:145)

- locked <0x3df92650> (a rpc.server.ClientReader)


at java.lang.Thread.run(Thread.java:479)

Page 8
2001 Hewlett-Packard Company

Threads Monitors Contention

JVM Threads in Hotspot

Signal Dispatcher daemon


Handles signals that java threads would not handle, such as SIGQUIT to do a java stack trace

Finalizer daemon
Runs java class finalizers

Reference Handler daemon


Mananges the soft and weak references available in java 2

VM Thread
Does all the hard work of the runtime, such as compiling, doing GCs, and so on

VM Periodic Task
Simulates timer interrupts Some tasks are scheduled to execute when the timer fires
Page 9
2001 Hewlett-Packard Company

Threads Monitors Contention

Java Programs
CPU CPU CPU

Disk

Easy to write

Memory

Cache

Multi-threaded applications Network applications No explicit memory management

Consequences
Contention for shared resources Java Sockets API requires many threads
2001 Hewlett-Packard Company

Page 10

Threads Monitors Contention

Contention

Control access to shared resources


thread 1 thread 2 thread 3 Shared Resource

Java monitors control access


Monitor thread 1 thread 2 thread 3 Shared Resource

Page 11
2001 Hewlett-Packard Company

Threads Monitors Contention

Solution to Contention: Java Monitors

Obtaining a monitor in Java


Synchronized methods/blocks SysMonitorEnter
Implemented in Classic JVM using the OS library pthread mutex calls

Implemented in HotSpot JVM using fast lock


Reverts to use of pthread mutex if contented

Page 12
2001 Hewlett-Packard Company

Threads Monitors Contention

HotSpot JVM Object Model

Efficient and low overhead Class header Object header non-static fields C++ vtable method table ptr static fields GC maps
Page 13
2001 Hewlett-Packard Company

Threads Monitors Contention

HotSpot JVM Object Header

Age (7 bits) Hash (23 bits) Lock (2 bits)


Age lock unlock pthread mutex used (inflated) used by mark/sweep Hash Lock

Page 14
2001 Hewlett-Packard Company

Threads Monitors Contention

HotSpot JVM Efficient, Low-Overhead Locking


L header U

header L

non-static fields Stack

Object

If another thread tries to obtain the same monitor: Lock inflation (uses a pthread mutex)
Page 15
2001 Hewlett-Packard Company

Threads Monitors Contention

How Does a pthread mutex Work?


Has 2 Waiters
thread 1 thread 3 Monitor/Mutex Mutex Lock thread 2

Try to get lock immediately If fail, be optimistic:

Monitor/Mutex

Enter queue and wait Repeat: spin, sched_yield Next waiter given lock

th r

ad

re

th

Monitor/Mutex

th

re

thread 1

thread 3

ad

re

thread 1

ad

Mutex Lock thread 3

Until: not optimistic


ksleep

th

Monitor/Mutex thread 1

z z z

2001 Hewlett-Packard Company

M Lou ctk ex

Monitor/Mutex

th r

thread 1

thread 3

ea

ea

th r th r th r

th r

ea ea

ea

d1 d1

d3

th r

ea

ea

d3

d1

Page 16

Threads Monitors Contention

Contention: System Impact

Monitors
Implemented using a single word in memory that serves as the lock word

On a system with multiple CPUs:


All of the caches on the individual CPUs must be updated during the spin-sched_yield() cycle

Consequences:
Threads time is spent accessing one word spinning

Result: High CPU usage with little application work


Machine spends all of its time maintaining cache coherency!! More threads yield lower performance!
Page 17
2001 Hewlett-Packard Company

Threads Monitors Contention

Monitor/Mutex

Contention: System Impact


thread 1 thread 3 Monitor/Mutex

Mutex Lock thread 2

th r

thread 7

thread 1

ncy e her CPU Co 1 e ch aCache C


CPU 2 Cache CPU 3 Cache CPU 4 Cache

ad

re

th

Monitor/Mutex

th

re

thread 1

thread 3

ad

re

thread 1

ad

Mutex Lock thread 3

thread 6

thread 3

th

Memory

Monitor/Mutex thread 1

z z z

thread 8

thread 4

thread 5

2001 Hewlett-Packard Company

M Lou ctk ex

Monitor/Mutex

th r

thread 1

thread 3

ea

ea

th r th r th r

th r

ea ea

ea

d1 d1

d3

th r

ea

ea

d3

d1

Page 18

Threads Monitors Contention

Solving Monitor Contention Problems

pthread mutex contention can be detected using specially instrumented libraries Using these libraries with the Classic JVM we were able to:
Identify monitor contention Reduce the contention for monitors

The following are the steps that we took to accomplish this work
Note:

Standard design patterns were applied


VALUE:

These same patterns can be applied to your Java applications


Page 19
2001 Hewlett-Packard Company

Threads Monitors Contention

Heavily Contested Monitors in Classic JVM


Lock Requests
35,274,145 27,746,810 8,039,649

Number of Requests

40,000,000 30,000,000 20,000,000 10,000,000 0

libc._mem_rmutex Monitor Cache Lock (malloc)

Heap Lock

Lock Request Failures


Number of Failures

2,000,000 1,500,000 1,000,000 500,000 0

1,602,025

1,468,817 325,053

libc._mem_rmutex Monitor Cache Lock (malloc)

Heap Lock
Page 20

2001 Hewlett-Packard Company

Threads Monitors Contention

Had Waiters & Number Waiting


Had Waiters When Lock Acquired
60,057

Number of Waiters

80,000 60,000 40,000 20,000 0

48,872

3,367 libc._mem_rmutex (malloc) Monitor Cache Lock Heap Lock

Average Number of Waiters When Had Waiters


Number of Waiters

thread

thread

thread

thread

thread

thread

thread

thread

thread

thread

t hr

t hr

e thr

libc._mem_rmutex (malloc)

Monitor Cache Lock

Heap Lock

2001 Hewlett-Packard Company

thr e

e thr

ea thr

thr ea

thr ea

thr e

ea

ea

thr ea

thr ea

ad

d ea thr

d ea thr

d ea thr

ad

thr ea

ad

d ea thr

thread

thr ea

thr ea

d ea thr

d ea thr

d ea thr

thread

thr ea d

2.7
thr ea d
ad d t hr ea d

3.2
d d

thr ea

thr ea

d ea thr thr e

d ea thr

ad

10 8 6 4 2 0

8.7
thread thread

d ea thr

thread

Page 21

Threads Monitors Contention

Types of Monitors in Classic

Java System Monitors


Control access to the shared system resources
Examples:
Java Heap Java Class Loader Java Native Interface Pinning

Page 22
2001 Hewlett-Packard Company

Threads Monitors Contention

Types of Monitors in Classic

Java Application Monitors


Java system designers:
Create new monitor for each use or re-use? Monitor cache created to hold re-used monitors Monitor Cache Lock - required to acquire

Page 23
2001 Hewlett-Packard Company

Threads Monitors Contention

Implementation of Monitors
System Monitors
Heap Cls Ldr JNI Pin Thr Cr Comp Monitor

Monitor Cache Lock

Monitor Cache
Header

Header

Header

Header

Page 24
2001 Hewlett-Packard Company

Threads Monitors Contention

Apply Design Pattern Thread Local

Create thread local cache

Page 25
2001 Hewlett-Packard Company

Threads Monitors Contention

Thread Local Monitor Caches


s che a rC to System Monitors oni lM a L oc
Heap Cls Ldr JNI Pin Thr Cr Comp

ad hre

Monitor

Monitor Cache Lock

thread 1

Monitor Cache
Header Header

Header

thread 3
Header

thread 2
Header

Header

Header

Header

Header

Page 26
2001 Hewlett-Packard Company

Threads Monitors Contention

Reduce Contention Thread Local Monitors

-montlscache=N
N is the number of thread local cache entries Default is 8

Page 27
2001 Hewlett-Packard Company

Threads Monitors Contention

Apply Design Pattern Split pool of shared resources

Split monitor caches

Page 28
2001 Hewlett-Packard Company

Threads Monitors Contention

Multiple Monitor Cache Implementationad 1 re -Th


L ad e T hr oc s ch e a rC to System Monitors o ni M al
Heap Cls Ldr JNI Pin Thr Cr Comp Monitor

Monitor Cache Lock 1

Monitor Cache 1

thread 1

Monitor

Monitor Cache Lock 2

Monitor Cache 2

thread 3
Monitor

Monitor Cache Lock 3

Monitor Cache 3

thread 2

Page 29
2001 Hewlett-Packard Company

Threads Monitors Contention

Monitor Cache Lock Improvements

Thread local monitor cache


montlscache=N Number of entries in thread local cache No lock acquisition required

Split main monitor cache into sets


moncache=[Nx]M[+I]
(number x size + expansion)

Access controlled by independent cache locks

Page 30
2001 Hewlett-Packard Company

Threads Monitors Contention

Solving Monitor Contention Problems - Summary

Application to Java programs Locality:


Use the ThreadLocal class
Available in 1.3 (1.2 implementation had problems)

Split shared resources into separate sets


Access elements in each specific sub-set using:
Hash value Attribute Mapping function

Page 31
2001 Hewlett-Packard Company

Threads Monitors Contention

Applying Tuning Lessons

Optimum number of threads Making your application scale

Page 32
2001 Hewlett-Packard Company

Threads Monitors Contention

Why Frequent Monitor Contention?

Java encourages use of many threads


Example: Java Sockets API

Missing from Java:


I/O Multiplexing - notify when data available Polling - explicitly check for data Signals - asynchronous when data available

Java Sockets API


Thread per socket and blocks until data available

Page 33
2001 Hewlett-Packard Company

Threads Monitors Contention

Java Threads and Sockets

Ethernet

ai tin g

JVM Process
thread thread thread thread thread

thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread

on

I/O

Ethernet

Th re ad s

bl oc ke d

Ethernet

Ethernet

Ethernet Ethernet

Ethernet

Page 34
2001 Hewlett-Packard Company

Threads Monitors Contention

Solutions

Optimum number of threads Minimize contention for shared resources

Page 35
2001 Hewlett-Packard Company

Threads Monitors Contention

Optimizing Thread Number New Poll API

Poll functionality for Java applications


com.hp.io.Poll One thread watches activity on a set of sockets Small number of worker threads support:
Large number of clients

Page 36
2001 Hewlett-Packard Company

Threads Monitors Contention

Java Threads and Sockets

Ethernet

ai tin g

JVM Process
thread thread thread thread thread

thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread thread

on

I/O

Ethernet

Th re ad s

bl oc ke d

Ethernet

Ethernet

Ethernet Ethernet

Ethernet

Page 37
2001 Hewlett-Packard Company

Threads Monitors Contention

Poll Thread + Worker Threads


Si Al ngl lS e oc Th ke rea ts d fo Po r I lls /O

Ethernet

JVM Process
thread thread thread thread thread

Ethernet

Ethernet

Worker Thread Worker Thread Worker Thread Worker Thread Worker Thread Worker Thread

Poll Thread

Ethernet

Ethernet Ethernet

Ethernet

Page 38
2001 Hewlett-Packard Company

Threads Monitors Contention

Glance System Load Java One Thread per Socket Model

Low User CPU Usage High System Time

User System

Page 39
2001 Hewlett-Packard Company

Threads Monitors Contention

Glance System Load Poll API - 3x users - Less System

More Time Spent in Application

l ol P

Iu AP

sS se

m te ys

PU C

Page 40
2001 Hewlett-Packard Company

Threads Monitors Contention

Glance System Calls Java One Thread per Socket Model

Pattern for contention: HIGH sched_yield() and ksleep()

Page 41
2001 Hewlett-Packard Company

Threads Monitors Contention

Glance System Calls Poll API 3x Users Less sched_yield

100x Reduction! 2 Fold Improvement! 4 Fold Improvement!

Page 42
2001 Hewlett-Packard Company

Threads Monitors Contention

Poll Makes Large Applications Scalable

Thread number
Reduced from 100s or 1000s to dozens

Poll thread
Delegates work to worker threads Constantly busy

Fewer threads

Increase throughput

Page 43
2001 Hewlett-Packard Company

Threads Monitors Contention

HPs Poll API Example code segment

import com.hp.io.Poll; static Poll fds[]; int nfds = 0; // array of file descriptors // number of file descriptors in array

fds[nfds] = new Poll(files[0].getFD(),Poll.POLLOUT|Poll.POLLIN); int n = Poll.poll(fds, nfds);

Page 44
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 New I/O APIs Overview

Buffers for data of primitive types Character-set (charsets) and decoders and encoders
Translate between bytes and Unicode characters

Pattern-matching facility based on Perl-style regular expressions Channels: New primitive I/O abstraction File interface that supports locks and memory mapping Multiplexed, non-blocking I/O facility for writing scalable servers

Page 45
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 New I/O APIs Non-blocking

Buffers
Containers for data

Channels to entities capable of performing I/O Selectors of various types


Connections and selection keys

Selectors plus selectable channels


Multiplexed, non-blocking I/O facility

Page 46
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 New I/O APIs Channel Types

Channel - A nexus for I/O operations ReadableByteChannel - Read into a buffer ScatteringByteChannel - Read into sequence of buffers WritableByteChannel - Write from a buffer GatheringByteChannel - Write from sequence of buffers ByteChannel - Read/write to/from a buffer

Page 47
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 Multiplexed, Non-blocking I/O

SelectableChannel - Channel that can be multiplexed


DatagramChannel - Channel for a java.net.DatagramSocket Pipe.SinkChannel - Write end of a pipe Pipe.SourceChannel - Read end of a pipe ServerSocketChannel - Channel for a java.net.ServerSocket SocketChannel - Channel for a java.net.Socket

Selector - Multiplexor of selectable channels SelectionKey - Token representing the registration of a channel with a selector Pipe - Two channels that form a unidirectional pipe

Page 48
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 Multiplexed, Non-blocking I/O


private static void acceptConnections(int port) throws Exception { // Open the server socket channel ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); // Set to non-blocking mode // Bind server socket channel to the local host and port parameter InetAddress lh = InetAddress.getLocalHost(); InetSocketAddress isa = new InetSocketAddress(lh, port); ssc.socket().bind(isa);

Page 49
2001 Hewlett-Packard Company

Threads Monitors Contention

J2SE 1.4 Multiplexed, Non-blocking I/O


// Open the Selector for incoming requests: Selector acceptSelector = SelectorProvider.provider().openSelector(); // Register accepts on the server socket channel // Tell the selector that the socket wants to be put on the // ready list when accept operations occur which then sets-up // the multiplexed non-blocking I/O. SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT); int keysAdded = 0;

Page 50
2001 Hewlett-Packard Company

Threads Monitors Contention

// The select method will return when the operations registered // have occurred, the thread has been interrupted, or other ... while ((keysAdded = acceptSelector.select()) > 0) { // Key or keys have been returned, so process it (or them) Set readyKeys = acceptSelector.selectedKeys(); Iterator iter = readyKeys.iterator(); // Walk through the set of keys and process the requests while (iter.hasNext()) { SelectionKey sk = (SelectionKey)iter.next(); iter.remove(); // SelectionKey indexes into the Selector to obtain the // server socket channel ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel(); Socket s = nextReady.accept(); // Accept request // Perform the designated operation on the socket } } Page 51
2001 Hewlett-Packard Company

Threads Monitors Contention

Contention Choosing Correct Data Structures

Java 2 introduced java.util collection classes


Unsynchronized Synchronization provided by wrappers:
Example: Collections.synchronizedSet()

How do you know whether to use:


Synchronized collection classes Unsynchronized collection classes

Correctness is the key


Let us look at performance, too
Page 52
2001 Hewlett-Packard Company

Threads Monitors Contention

Collection Classes: List Interface

AbstractList
Skeletal implementation of the List interface Backed by a "random access" data store (such as an array) ArrayList Resizable-array implementation of the List interface An unsynchronized Vector class LinkedList Doubly linked list implementation of the List interface get() and set() are less efficient than ArrayList get/set First/Last() are efficient use for stack or queue Vector Implements a growable array of objects an array Stack
Last-in-first-out (LIFO) stack of objects Use LinkedList instead 2001 Hewlett-Packard Company
Page 53

Threads Monitors Contention

Collection Classes: Map Interface

AbstractMap
Skeletal implementation of the Map interface Mapping between key objects and value object pairs Unique keys HashMap Hash table based implementation of the Map interface Unsynchronized version of Hashtable TreeMap Red-Black tree based implementation of the SortedMap interface

Hashtable
Implements a hashtable, which maps key objects to values
Page 54
2001 Hewlett-Packard Company

Threads Monitors Contention

Collection Classes: Set Interface

AbstractSet
Skeletal implementation of the Set interface HashSet
Implements the Set interface (unique elements only) Uses a HashMap instance

TreeSet
Implements SortedSet Uses a TreeMap instance

Page 55
2001 Hewlett-Packard Company

Threads Monitors Contention

Collection Classes: Fastest


Sync? No No Yes Yes No No No No Usage Fastest List Slow - Use for queues Faster than sync ArrayList Speed similar to Vector Fastest Map Slow; + Iteration of keys Faster than sync HashMap Fastest Set Slow; + Iteration of keys
Page 56
2001 Hewlett-Packard Company

Interface Class List ArrayList LinkedList Vector Stack Map HashMap TreeMap Set HashSet TreeSet

HashTable Yes

Threads Monitors Contention

Data Structures Suggestions

Use appropriate data structures:


Convert collections into arrays for improved access speed Make conversions faster by implementing them in a subclass

Collection element access then avoids access methods Element access is direct
Create customized implementations of Hashtable

Can also just use a HashMap


Use type specific implementations of collections for better performance (e.g., IntegerVector rather than Vector)

Avoids casts for improved performance


WeakReferences for elements of large lookup tables SoftReferences for cache elements
2001 Hewlett-Packard Company

Page 57

Threads Monitors Contention

Suggestions for Minimizing Contention

Thread notification
Use notify() rather than notifyAll()

notifyAll wakes up all threads and will cause much unneeded thrashing Servlets
Minimize synchronization

Allows threads to execute in parallel


Do not use javax.servlet.SingleThreadModel

JDBC
Use JDBC connection pooling size correctly Release JDBC resources when done Reuse datasources for JDBC connections
Page 58
2001 Hewlett-Packard Company

Threads Monitors Contention

Finding Correct Number of Threads

For mostly CPU bound applications:


Too many threads create context switching overhead Too few threads do not fully use the system

Consider:
n=number of active threads k=number of CPUs (n < k) CPUs are underutilized (n == k) Ideal conditions, but each CPU will probably be under-utilized (I/O and other considerations) (n > k)

Greater such that CPUs are always busy is ideal Greater by a large amount leads to significant performance degradation from contention, starvation and context switching Hewlett-Packard Company 2001

Page 59

Threads Monitors Contention

Finding Correct Number of Threads

Too few threads:


CPU is waiting to do work, but no work to be done Unable to get 100% CPU All threads blocked [on I/O] and runnable when you do an execution snapshot Application performance increases as you increase the number of threads

Too many threads:


Execution snapshot shows high level of contention or context switching in the JVM process Application performance increases as you decrease the number of threads
Page 60
2001 Hewlett-Packard Company

Threads Monitors Contention

Java Monitors

http://developer.java.sun.com/developer/Books/performance2/chap4.pdf Chapter 4 of
"High Performance Java Computing : Multi-Threaded and Networked Programming", "Monitors" (Page last updated January 2001, Authors George Thiruvathukal, Thomas Christopher)

Java monitors not always the most efficient synchronization mechanism


Case in which transferring the lock can lead to a race condition Presentation of a more complete Monitor class

volatile fields are slower than non-volatile fields


Execution of instructions requires a forced store to memory rather than just leaving values in registers May be necessary to avoid concurrency problems
Page 61
2001 Hewlett-Packard Company

Threads Monitors Contention

Java Monitors

http://developer.java.sun.com/developer/Books/performance2/chap4.pdf

Good summary of policies for synchronizing threads trying to read from or write to shared resources:
One thread at a time Readers-preferred (readers have priority) Writers-preferred (writers have priority) Alternating readers-writers (alternates between a single writer and a batch of readers) Take-a-number (first-come, first-served)
Page 62
2001 Hewlett-Packard Company

Threads Monitors Contention

Threads, Monitors and Contention Summary

Paradox:
Monitor contention problems can be masked by specifically binding a process with contention problems to a single CPU All accesses to the lock word are local to that CPU

The good news:


Performance patterns visible in Glances windows expose serious problems at a high level

High system time (more threads degrade performance) Frequent calls to sched_yield, ksleep, kwakeup
SIGQUIT will tell you immediately if you have a problem HPjmeter for JDK 1.1.5+ and 1.2 uses heuristics to estimate monitor contention JDK 1.3.1 Xeprof collects exact information on monitor Page 63 contention and HPjmeter 1.2 displays the information
2001 Hewlett-Packard Company

Threads Monitors Contention

Threads, Monitors and Contention Summary: Patterns

"Worker Thread 17" prio=9 tid=0x1310b70 nid=41 lwp_id=14165 suspended [0x1194d000..0x11948478]


at fields.FieldPropertiesLibraryLoader.forClass(FieldPropertiesLibraryLoader.java:67)

- waiting to lock <0x3ca45848> (a java.lang.Object)


at fields.FieldsServiceImpl.getFpl(FieldsServiceImpl.java:75)

Page 64
2001 Hewlett-Packard Company

Threads Monitors and Resource Contention JDBC Usage

Page 65
Copyright 2001 Hewlett-Packard Company

Threads Monitors Contention

WLS JDBC Suggestions

http://www.weblogic.com/docs51/techdeploy/jdbcperf.html Weblogic JDBC tuning Last updated April 1999, BEA Systems

Use connection pools to the database.


Optimal pool size is when the connection pool is just large enough to service requests without waits

Cache frequently requested data in the JVM


Avoid unnecessary database requests

Page 66
2001 Hewlett-Packard Company

Threads Monitors Contention

WLS JDBC Suggestions

http://www.weblogic.com/docs51/techdeploy/jdbcperf.html Weblogic JDBC tuning Last updated April 1999, BEA Systems

Pre-fetch rows in batches


Tune the number of rows pre-fetched Avoid pre-fetching BLOBs

Avoid moving data unless absolutely necessary


Process the data and produce results as close to its source as possible Use stored procedures

Use set processing, not row at a time processing


Process multiple rows together wherever possible

Page 67
2001 Hewlett-Packard Company

Threads Monitors Contention

WLS JDBC Suggestions

Counting entries in a table (e.g. using SELECT count(*) from myTable, yourTable where ... ) is resource intensive
Try first selecting into temporary tables, returning only the count, and then sending a refined second query to return only a subset of the rows in the temporary table

Proper use of SQL can reduce resource requirements


Use queries which return the minimum amount of data needed Avoid SELECT * queries A complex query that returns a small subset of data is more efficient than a simple query that returns more data than is needed
Page 68
2001 Hewlett-Packard Company

Threads Monitors Contention

WLS JDBC Suggestions

Try to batch updates


Collect statements together and execute them together in one transaction Use conditional logic and a temporary (if necessary) to achieve statement batching

Never let a DBMS transaction span user input Consider using optimistic locking
Optimistic locking employs timestamps to verify that data has not been changed by another user, otherwise the transaction fails

Use in-place updates


Try to avoid moving rows or changing their sizes
Page 69
2001 Hewlett-Packard Company

Threads Monitors Contention

WLS JDBC Suggestions

Store operational data and historic data separately


Store frequently used data separately from infrequently used data

DBMSs work well with parallelism


Try to design the application to do other things while interacting with the DBMS

Choose the fastest JDBC driver

Page 70
2001 Hewlett-Packard Company

Anda mungkin juga menyukai