Вы находитесь на странице: 1из 251

Season of mists and mellow

fruitfulness,

Everything You Wanted to


Know

About Writing Async,


Concurrent HTTP
Apps in Java

Agenda
Mostly this:

Agenda
And this:

Agenda
And this:

About your speaker


git
h
c
u
r
hu
a
b
j
@
b.
co
m
/ jb
linkd.in/jbaruch ar
uc
h

stackoverflow.com/users/402053

What Frog?

What Frog?

What Frog?

What Frog?

E SERVE BINARIES FOR A LIVIN

CONCURRENT DOWNLOADS

Y U NO SUPPORT THEM?!

Requirements

parallel file Downloads


Parallel file parts
interrupt/pause/resume
Progress events
Checksums caching

First Association for concurrent


downloader

Lucky day: Download manager


written in java!

ONE DOES NOT SIMPLY

EMBED JDM

Lets look if we can use it!

1. No traceable license
2. No website or docs
3. No traceable sources
4. Its an app, not a lib

U WANT CONCURRENT DOWNLOA

WRITE IT YOURSELF

WHY WONT YOU JUST

USE URLCONNECTION?

Java.net.urlconnection

1. Memory wasteful
(buffering)
2. Minimal API
3. Blocking streams

What were looking for

1. Async/non-blocking
2. Event callbacks

What is IT going to take

1. Reactor
2. nio

Welcome to the reactor

pattern for lightweight


concurrency
Event driven
Threads reuse
Uses non-blocking Io

Original pattern

http://www.dre.vanderbilt.edu/~schmidt/PDF/rea
ctor-siemens.pdf

Guess the author by the


diagram

http://gee.cs.oswego.edu/dl/cpjs

In Java,
Reactor means
NIO

Selector as a multiplexer

Java version - Registering


SocketChannelchannel=
SocketChannel.open();
socketChannel.connect(new

InetSocketAddress("http://remote.com
",80));
...
Selectorselector=Selector.open();
channel.configureBlocking(false);
SelectionKeyk=

Java version - Dispatcher


while(!Thread.interrupted()){
selector.select();
Setselected=
selector.selectedKeys();
Iteratorit=
selected.iterator();
while(it.hasNext())
SelectionKeyk=(SelectionKey)
(it.next();
((Runnable)

Handling reactor events is complex

Need to maintain state


Buffering assembling
chunks
Coordinating async events

HTTP NIO FRAMWORKS

DO THE HEAVY LIFTING

Nio libraries

Most of them are servers


Netty, grizzly, etc.

Apache Mina
Apache HTTP components
asyncclient
Ning http client

Client and server nio


library
Evolved from netty
Latest release October
2012

Nio libraries

Most of them are servers


Netty, grizzly, etc

Apache Mina
Apache HTTP components
asyncclient
Ning http client

Nings async http client

Here it is!

try (AsyncHttpClient asyncHttpClient = new


AsyncHttpClient()) {
ListenableFuture<Response> future =
asyncHttpClient.prepareGet(
"http://oss.jfrog.org/api/system/ping").execute(
new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response
response) {
System.out.println(response.getResponseBody(
));
return response;
}
@Override
public void onThrowable(Throwable t) {
t.printStackTrace();
}

HAC Concepts

Request producer
Response consumer

try (CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClients.createDefault()) {


asyncHttpClient.start();
Future<HttpResponse> future = asyncHttpClient.execute(
HttpAsyncMethods.createGet("http://oss.jfrog.org/api/system/ping"),
new AsyncByteConsumer<HttpResponse>() {
@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println(response.getStatusLine().getReasonPhrase());
}
@Override
protected void onByteReceived(final CharBuffer buf, final IOControl ioctrl) { }
@Override
protected void releaseResources() { }
@Override
protected HttpResponse buildResult(final HttpContext context) {
return (HttpResponse) context.getAttribute("http.response");
}

}, null);
HttpResponse response = future.get();

WAIT A SECOND

THEY ARE ALMOST THE SAME!

Choosing between ning and http


asyncclient

"All problems in computer


science can be solved by
another level of
David
indirection"
Wheeler

p u b lic in terface H ttp P rovid erD ow n load H an d ler {


void onResponseReceived(in t statusCode, M ap< String,
List< String> > headers);
b oolean onBytesReceived(ByteBuff
er buf);
void onFailed(Throw able error);
void onCanceled();
void onCom pleted();
}

Head to head
Feature/Librar Ning client
y
Maturity
Good
Download
cancelation
Progress
hooks

Easy

Events not
granular
enough
Documentatio A bit sparse
n

Http Async Client


Very new (early
2014)
With bugs
Just use
onByteReceived()

Minimal

Performance?
900
800
700
600
500

Ning
AHAC

400
300
200
100
0

Small file

Medium file

Large file

http://blogs.atlassian.com/2013/07/http-client-p

Rfc2616: a universe of its


own

Confused?

Just read some stackoverflow


(and improve your rep as you go)

for
discovering
that range
header is
lost on
redirect

HTTP WAR STORIES

Question!

What should
be contentlength when
using
compression?

https://github.com/http2/http2-spec/issues/46

Question!

Why when redirected to CDN


all the chunks start from zero?

H ttpAsyncClientBuilder builder = H ttpAsyncClients.custom ();


// add redirect strategy that copies "range" headers, if exist
b u ild er.setR ed irectS trateg y(new D efau ltR ed irectS trateg y() {
@ O verride
public H ttpU riRequest getRedirect(H ttpRequest request, H ttpResponse
response,
H ttpC ontext context)
H ttpU riRequest redirectRequest = super.getRedirect(request, response,
context);
// copy "Range" headers, if exist
H eader[] rangeH eaders = request.getH eaders(H ttpH eaders.RAN G E);
if (rangeH eaders != null) {
for (H eader header : rangeH eaders) {
red irectR eq u est.ad d H ead er(h ead er);
}
}
return redirectRequest;
}});

Question!

How many
simultaneous
connections should
I open?

HTTP 1.1 GOES LIKE:

CAN YOU PLEASE LIMIT


TO 2 CONNECTIONS?

BROWSERS GO LIKE:

URL ENCODING?

Question!

Whats
wrong
with the
following
code?

public static String


encodeUrl(String urlStr) {
URLEncoder.encode(urlSt
r, "UTF-8");
...
}

Decoded URLs cannot be


re-encoded to the same form
http://exam ple.com /?query= a& b= = c
Cannot be decoded back after it w as
encoded:
http://exam ple.com /?query= a% 26b= = c

Dont use
java.net.URLEncoder
Utility class for HTML form
encoding. This class contains static
methods for converting a String to
the application/xwwwform
urlencodedMIME format.
For more information about HTML
form encoding, consult the HTML
specification.

AHC Alternatives
org.apache.http.client.utils.U RIBuilder
org.apache.http.client.utils.U RLEncode
dU tils

Question!

How do I
close a
socket
correctly
?

How hard can it be to close a


socket?

The art of socket closing

http://www.safaribooksonline.com/library/view/http-the-

Half-closed: no new
customers

Never block in socket


close()

The other side expects


you to clean up nicely
It will give up on time
out
You will wait (forever)

I ALWAYS CLOSE
CONNECTIONS

AND WHEN I DO IT, I USE


TRY-WITH-RESOURCES

Remember?

Question!

How can I
write file
parts
concurrent
ly?

Write to separate files,


combine on finish
Write to same file,
seeking to the right
position

WHY WONT YOU JUST USE

JAVA.IO.RANDOMACCESSFILE?!

USE FileChannel
Implements SeekableByteChannel

java.nio.channels.FileC h an n el# w rite


(
java.nio.ByteBuff
er src, long
p osition )

download progress tracking


FileProgres
sInfo

* FilePartProgressI
nfo

PersistentFileProgressInfo
Save the total size, sha1, number of parts
State of each part (offset, size, completed...)

File Locking

File locking Levels

VM level
OS level

OS level File locking


Multiple downloader instances
writing to the same file
Needed for writing:
Partial download file
Persistent download progress

OS Level File Locking Exclusive


FileLock lock = fi
leChannel.tryLock();
//N on -sh ared : (0L, Long.M AX_VALU E,
false)
if (lock = = n u ll) {
th row n ew
O verlappingFileLockException();
}
retu rn lock;
}

OS Level File Locking


Advisory exclusive
p rivate FileLock lock(FileChannelfi
leChannel) th row s
IO Exception {
FileLock lock = fi
leChannel.tryLock(Long.M A X _V A LU E
- 1, 1, false);
if (lock = = n u ll) {
th row n ew O verlappingFileLockException();
}
retu rn lock;
WTF?!
}

VM Level File Locking


WHY DO YOU NEED
LOCKS

IF YOU WRITE TO
DIFFERENT PARTS OF

VM Level File Locking


Prevent same VM threads writing to
the file when we started closing it
Closing sequence:
Release file locks
Close channels
Rename a file to it's final name
(remove .part)
Erase progress info

VM Level File Locking


ReentrantReadW riteLock.ReadLock w riteToFileLock
= rw l.readLock();
ReentrantReadW riteLock.W riteLock closeFileLock =
rw l.w riteLock();
public void close() throw s IO Exception {
this.closeFileLock.lock();
}
public int w rite(int partIndex, ByteBuff
er buf) {
if (!this.w riteToFileLock.tryLock()) {
throw new IllegalStateException("File is being
closed");
}

Whats next?

http/2
Mostly standardizing Google's spdy
Header compression
multiplexing
Prioritization
Server push

On the way clear some stuff


E.g. compressed content length

Ease the load

Links!
RTFM: RFC 2616
Ultimate book: HTTP: The
Definitive Guide
Amazon
Safari

Reactor pattern
Doug Lea on NIO

No, Thank you!

A Quick Tour
of Logos

The Logical Appeal

So what exactly is logic? Who


cares?
Informally, logic is about saying things that make
sense. You can think of it in that way if you like.
It's pretty sunny today, so you should wear sunscreen.

Formally, logic is the art of arguing


not like a fight or debate, but by
using the information we already
If
it's sunny
you new
should wear
know
to today,
draw
andsunscreen.
useful
Indeed it is sunny today.
conclusions.
Therefore, you should wear sunscreen.

But wait. That just looked like the


exact same thing you said before,
you hack.

Well, yes. But that's how an argument looks in sta


rm! You can break down any argument into this
hat makes it easier to think about.

If it's sunny today, you should wear sunscre


Premises/
givens
It is sunny today.
__________________________________________
Conclusion
Therefore, you should wear sunscreen.

(Premises always come first, and the conclusion always comes

How about a more complex


argument?
1. This piece of fresh fruit is fuzzy.
2. It also has seeds.
3. If a fruit is fuzzy, it's either a kiwi or a peach.
4. Peaches have a pit; they don't have seeds.
5. So the fruit can't be a peach.
6. So the fruit must be a kiwi.

Which of the above sentences is a conclusion?

How about a more complex


argument?
1. This piece of fresh fruit is fuzzy.
2. It also has seeds.
3. If a fruit is fuzzy, it's either a kiwi or a peach.
4. Peaches have a pit; they don't have seeds.
5. So the fruit can't be a peach.
6. So the fruit must be a kiwi.

Good logic lets us cobble together lots of


different pieces of information, and tell from
them what's probably or definitely true.

But what counts as good logic?


That argument was good (made sense), because
the conclusion followed from the premises. We'll
see what this means in a moment.

Why don't we look at a bad argument?

But what counts as good logic?


Some people have fallen off cliffs and lived.

herefore, if I jump off this cliff, I will definitely be

Come
on.
What
could
possibly

But what counts as good logic?


Some people have fallen off cliffs and lived.

herefore, if I jump off this cliff, I will definitely be

his argument is weak. Although the premise is tr


t's easy to think of ways (very painful ways) that
onclusion could be false. The easiest way to spo
ogic is to do just that: try to think of another way

Philosophers call these counterexamples).

But what counts as good logic?


Let's look at two kinds of
arguments.
1. Deductive reasoning:
All interns can breathe fire. So
Philip can breathe fire.
Is there a piece of the puzzle missing?

But what counts as good logic?

Let's look at two kinds of arguments.


1. Deductive reasoning:
All interns can breathe fire. Philip
is an intern.
So Philip can
breathe fire.
Sometimes you may encounter hidden stateme
nd ideas, which the writer sneaks in but doesn't
ay outright.

But what counts as good logic?


Let's look at two kinds of arguments.
1. Deductive reasoning:
All interns can breathe fire. Philip
is an intern.
So Philip can
breathe fire.
Are the premises true?
If so, then the conclusion's
100% guaranteed true.
No getting around it!

But what counts as good logic?


Let's look at two kinds of arguments.
2. Inductive reasoning:
I touched a stove and it burned me. I did this
fifty times, and the same thing happened. So
the
next time I touch the stove, it will burn me.

Are the premises true?


If so, then the conclusion's
LIKE
probably true. There might
still be exceptions.

WHAT?

How is this useful to me?


Like Mr. Morgan said, the ability to
make strong logical arguments will
become more and more important
later on in high school and college.
Pathos and ethos are still valuable!
But your audience will be a lot better
at questioning them. Logos is handy
because, if you use it well, it can't

How is this useful to me?


But even better is the superpower to spot weak
logic.

Next time you watch TV or go online (with your


parents' permission, of course), try to keep track
of how many different arguments are being
pitched to you by ads. How much info is given to
you? How much is left out?

What time is it?


Adven- wait, no. Activity time!

Pair off into groups of four. Each group will receive an examp
of a poor argument (these may be either inductive or deduct

With your group, you will have 5 minutes to try to come up w


one counterexample - one way in which the argument
could be wrong, even if the premises are definitely true.
Poke it full of holes!
Also, choose a group representative to tell us your reasoning

(It's OK to imagine unlikely or weird explanations;


don't be afraid to think outside the box.

Some examples:

RGUMENT: I pulled an all-nighter studying for last week's bi


est, and I ended up with an A. Tiredness must make me sma

OUNTER: What if you got an A because you actually studied


Or maybe the test was going to be easy for you all along?

ARGUMENT: If I play with Dad's power tools, he'll yell at me.


But Dad is yelling at me for something. So I guess I must hav
played with the power tools.

COUNTER: What if he's yelling at you for a different reason:


scratching the car, or hammer-throwing the cat onto the roof

John Keats

"To Autumn" is a poem by English


Romantic poet John Keats (31 October
1795 23 February 1821).

"To Autumn" is the final work in a group


of poems known as
Keats's "1819 odes".

"To Autumn" is a poem of three stanzas, each of eleven


lines. Written in 1819, the structure is that of an odal hymn
, having three clearly defined sections corresponding to the
Classical divisions of strophe, antistrophe, and epode

The imagery is richly achieved through


the personification of Autumn

Poem

Season of mists and mellow


fruitfulness,

Close bosom-friend of the


maturing sun;

Conspiring with him how to load


and bless

With fruit the vines that round


the thatch-eves run;

To bend with apples the moss'd


cottage-trees,

And fill all fruit with


ripeness to the core;

To swell the gourd, and plump the


hazel shells

With a sweet kernel; to set


budding more,

And still more, later flowers for


the bees,

Until they think warm days will


never cease,

For Summer has o'er-brimm'd


their clammy cells.

Who hath not seen thee oft amid


thy store?

Sometimes whoever seeks


abroad may find

Thee sitting careless on a granary


floor,

Thy hair soft-lifted by the


winnowing wind

Or on a half-reapd furrow
sound asleep,

Drowsed with the fume of poppies, while


thy hook

Spares the next swath and all its


twind flowers:

And sometimes like a gleaner thou


dost keep

Steady thy laden head across a


brook;

Or by a cyder-press, with
patient look,

Thou watchest the last oozings,


hours by hours.

Where are the songs of Spring? Ay,


where are they?

Think not of them, thou hast thy


music too,

While barrd clouds bloom the softdying day

And touch the stubble-plains with


rosy hue;

Then in a wailful choir the small


gnats mourn

Among the riversallows, borne aloft

Or sinking as the light wind


lives or dies;
sinking

And full-grown lambs loud bleat from


hilly bourn;

Hedge-crickets sing; and now with


treble soft

The redbreast whistles from a gardencroft;

And gathering swallows twitter in the


skies.

Close bosom-friend of the


maturing sun;

Conspiring with him how to load and


bless

With fruit the vines that round the thatch-eves run;

To bend with apples the moss'd cottagetrees,

And fill all fruit with ripeness to the core;

To swell the gourd, and plump the


hazel shells

With a sweet kernel; to set budding


more,

And still more, later flowers for the


bees,

Until they think warm days will never


cease,

For Summer has o'er-brimm'd their


clammy cells.

Who hath not seen thee oft amid thy


store?

Sometimes whoever seeks abroad


may find

Thee sitting careless on a granary


floor,

Thy hair soft-lifted by the winnowing


wind

Or on a half-reapd furrow sound


asleep,

Drowsed with the fume of poppies, while thy


hook

Spares the next swath and all its


twind flowers:

And sometimes like a gleaner thou


dost keep

Steady thy laden head across a


brook;

Or by a cyder-press, with
patient look,

Thou watchest the last oozings, hours


by hours.

Where are the songs of Spring? Ay, where


are they?

Think not of them, thou hast thy music


too,

While barrd clouds bloom the softdying day

And touch the stubble-plains with


rosy hue;

Then in a wailful choir the small gnats


mourn

Among the river-sallows,


borne aloft

Or sinking as the light wind


lives or dies;
sinking

And full-grown lambs loud bleat from hilly


bourn;

Hedge-crickets sing; and now with treble


soft

The redbreast whistles from a gardencroft;

And gathering swallows twitter in the


skies.

Trusses

Element Formulation by Virtual


Work
Use virtual work to derive element
stiffness matrix based on assumed
displacements
Principle of virtual work states that if a
general structure that is in equilibrium
with its applied forces deforms due to a
set of small compatible virtual
displacements, the virtual work done is
equal to its virtual strain energy of
internal stresses.

At element level, Ue = We
Ue = virtual strain energy of internal
stresses
We = virtual work of external forces
acting through virtual displacements

We now assume a simple displacement


function to define the displacement of
every material point in the element.
Usually use low order polynomials
Here
u = a1 + a2 x
u is axial displacement
a1, a2 are constants to be determined
x is local coordinate along member

The constants are found by imposing


the known nodal displacements ui, uj
at nodes i and j
ui = a1 + a2xi
uj = a1 + a2xj
ui, uj are nodal displacements
xi, xj are nodal coordinates

letting xi = 0, xj = L, we get
a1 = u i
a2 = (uj-ui)/L

We can write
x x ui

u 1
[N ]{d}

L L u j

[N] = matrix of element shape functions


or interpolation functions
{d} = nodal displacements

N N1

N2

x
N1 1 ,
L
x
N2
L
Pr operties
N i 1 at node i and zero at all other nodes
Ni 1

i.e. at any point in the element N1 N 2 1

N1=1

Variation of N1

N2=1

Variation of N2

Strain is given by
du
d[N]

{d} [B]{d}
dx
dx
1
B 1 1
L

where [B] is a matrix relating strain


to nodal displacement (matrix of
derivatives of shape function)

Now

= E(= E[B]{d}-E
Stress and strain are constant in a
member

Define internal virtual strain energy


for a set of virtual displacements
{d} to beU ( )T dV
e

- = virtual strain
- = stress level at equilibrium
dV = volume

Virtual work of nodal forces is


T
We = {d} {f}
Then, virtual work is given by

dv d
T

Substituting and rearranging gives


V [B]{d}

E[B]{d} Eo dV {d}T {f }

{d}T V [B]T E[B]{d}dV {d}T V [B]T E odv {d}T {f }

Canceling {d} gives [k]{d}={F}


where[k ] [B]T E[B]dV
T

1
F f EAo
1
For thermal problem

o T

for a truss we get


EA 1 1
[k ]
L 1 1

this formulation method also applies


to 2-d and 3-d elements

ocedure for Direct Stiffness Method (Displacement Metho


1. Discretize into finite elements, Identify nodes, elements
and number them in order.
2. Develop element stiffness matrices [Ke] for all the
elements.
3. Assemble element stiffness matrices to get the global
stiffness matrix ([KG] = [Ke]). The size of of global
stiffness matrix = total d.o.f of the structure including at
boundary nodes. Assembly is done by matching element
displacement with global displacements. Also develop
appropriate force vector (by adding element force vectors)
such that equation of the type [KG] {u}={F} is obtained.

Procedure for Direct Stiffness Method


4. Apply kinematic boundary conditions. Without applying
boundary conditions, [KG] will be singular. (minimum
number of boundary conditions required is to arrest Rigid
Body displacements).
5.

Solve for unknown displacements {u} ( {u}= [KG] 1{F}).

6. Once displacements are determined find


(a) reactions by picking up appropriate rows from the
equation {F}=[KG] {u}, (b) Find element forces {f}=[Ke]
{ue}, (c) Element stresses given by {e}= [D][B]{ue}.

F1 , u1

F 2, u2

2
Boundary Conditions
u1=0, u 2=0

F3 , u3

2A, L, E

KG

2 -2

AE

-2 2+1 -1

L
-1
1

A, L, E

Reactions

0
AE
PL
2P
F1 2 -2 0
1
L
3AE
3
0
0
AE
PL
P
F3 0 -1 1
1
L
3AE
3
0

Element Forces

Element 1
f1
2AE 1 -1 u1

L -1 1 u 2
f 2
2p / 3
2AE 1 -1 PL 0

2p / 3
L -1 1 3AE 1
Element 2
f1
AE 1 -1 u 2

L -1 1 u 3
f 2
p / 3
AE 1 -1 PL 1
=

p / 3
L -1 1 3AE 0

f2

f1
A, L, E

2P
3

2P
3
2A, L, E

P
3

A, L, E

P
3

Element 1

Element 2
u1

u2

u2

AE 1 1
K1
L 1 1

K2

u3

AE
1 1

L 1 1

Stress in element 1
u1
1 1 u1

1 E1 EB E

L L u 2
u2
u 2 u1
4 1.5 0
=E
2.0 10
200N / mm 2
L
150
Stress in element 2
u2
1 1 u 2

2 E2 EB E

L L u 3
u 3
u3 u2
4 1.2 1.5
=E
2.0 10
40N / mm 2
L
150

Direct Element Formulation


truss element acts like 1-d spring
l >> transverse dimensions
pinned connection to other members
(only axial loading).
usually constant cross section and
modulus of elasticity

AE
k
L
A = cross section area
E = modulus of elasticity
L = length

Assume displacements are much


smaller than overall geometry
vertical displacements of horizontal
member produce no vertical force

Stiffness matrix is written in local


element coordinates aligned along
element axis
want stiffness matrix for arbitrary
orientation

rotate coordinate systems using


rotation matrix [R]
displacement components in global
coordinates are related to
displacement components in local
coordinates by {d}=[R]{d}
{d} = displacement in global
coordinates
{d} = displacement in local element
coordinates

qj

qi

vi

pi

ui

vj
AE

Pj

ui

L
x

k
0

st
1 column
k
0
k
0

rd
3 column
k
0

qi = 0

pi = k=AE / L

ui=1

qi = 0

pi = k=AE / L u
i=1

qj = 0

pj = k = AE / L

qj = 0

0
0

th
4 column
0
0
0
0

2 nd column
0
0

qi = 0

qj = 0
pj = 0
vj =1

pi = 0

qi = 0

vi =1
pi = 0

qj = 0
pj = 0

start with member on x axis, element


equations are
k
0

k
0

0
0

0
0

u ' i
v '

u
'

j
v ' j

p 'i
q'
i

p'j
q ' j

or {k}{d}={f}
Note that y equations are all zero

qj

vj

x
pj

uj

pi

ui

x
vi

qi

at node i
u 'i u i cos( ) v i sin( )

p ' i p i cos( ) q i sin( )

v 'i u i sin( ) v i cos( )

q ' i q i sin( ) q i cos( )

At node i

u ' i
cos

sin
v ' i

sin u i

cos v i

p ' i
cos

sin
q ' i

A similar matrix can be obtained at node j

u ' i
cos
v '
sin
i
u '
0
j

v ' j
0

sin
cos

0
0

cos

sin

0 u i
v

0
i
sin u j

cos v j

sin pi

cos q i

Matrix [R] is:


0
0 c
cos sin
sin cos
0
0 s


0
cos sin 0
0
0
0
0

sin

cos

s 0
c 0
0 c
0 s

0
0

s
c

Similarly , force components are


related by {f} = [R]{f}
Local force displacement relation is
[k]{d} = {f}
global force displacement relation is
[k][R]{d} = [R]{f}
using fact that [R]-1 = [R]T, we get
T
[R] [k][R]{d} = {f}

then [k] = stiffness matrix in global


T
coordinates is [R] [k][R]

c2

cs
[k] k 2
c

cs

cs c cs
2
2
s cs s
2
cs c
cs
2
2
s cs s
2

Structure equation is [k] {D} = {F}


[k] = structure stiffness matrix
{D} = nodal displacement vector
{F} = applied load vector

DB{u 'i u 'j }

note u 'i u i cos( ) v i sin( )


u i
={c s}
v i

-1
E
L

u i
u i
v
v
1 c s 0 0 i
E
i

u c -s c s u

L 0 0 c s j
L
j
vj
v j

Finite Element Model


usually use existing codes to solve
problems
user responsible for
creating the model
executing the program
interpreting the results

arrangement of nodes and elements


is known as the mesh
plan to make the mesh model the
structure as accurately as possible

for a truss
each member is modeled as 1 truss
element
truss members or elements are
connected at nodes
node connections behave like pin joints
truss element behaves in exact
agreement with assumptions
no need to divide a member into more
than 1 element

such subdivision will cause execution to


fail
due to zero stiffness against lateral force at
the node connection where 2 members are
in axial alignment

there is geometric symmetry


often possible to reduce the size of
problem by using symmetry
need loading symmetry as well

Fig. 3-5 and 3-6 show symmetric


loads and the reduced model
need to impose extra conditions along
the line of symmetry
displacement constraints: nodes along the
line of symmetry must always move along
that line
changed loads: the load at the line of
symmetry is split in two

Computer input assistance


a preprocessor is used to assist user
input
required inputs are
data to locate nodes in space
definition of elements by node numbers
type of analysis to be done
material properties
displacement conditions
applied loads

interactive preprocessors are preferable


you can see each node as it is created
elements are displayed as they are created
symbols are given for displacement and
load conditions
usually allow mesh generation by replication
or interpolation of an existing mesh
allow inserting nodes along lines
allow entering a grid by minimum and
maximum positions plus a grid spacing

truss element consists of 2 node


numbers that connect to form
element
other information for truss is
modulus of elasticity
cross sectional area

data can form a material table


assign element data by reference to
the table

boundary or displacement conditions


are set by selecting a node and
setting its displacement
do not over constrain a structure by
prescribing zero displacements
where there is no physical support

loading conditions are set by


selecting nodes and specifying force
or moment components
check model carefully at this point

Analysis Step
mostly transparent to user
small truss models have enough
accuracy and performance for an
accurate solution
a large model has a large number of
elements and nodes

numerical solution may not be


accurate if there are full matrices
get better accuracy if the nonzero
terms are close to the diagonal
reduces the number of operations and
round off error (banded matrix)

in FE model, element or node


numbering can affect bandwidth
good numbering pattern can minimize
bandwidth
different methods based on node or
element numbering
to minimize, plan numbering pattern so
nodes that connect through an element
have their equations assembled close
together

In Fig. 3-7, node numbers are


considered, Xs show nonzero terms

In Fig. 3-8, node numbers are


considered

many programs have bandwidth or


wavefront minimizers available
most programs will keep original
numbering for display but use the
minimized number scheme

Вам также может понравиться