Concurrent Programming in JAVA

27
Concurrent Programming in JAVA What is it? When/How do I use it? When is my class safe? What should I think about during Design?

description

Concurrent Programming in JAVA. What is it? When/How do I use it? When is my class safe? What should I think about during Design?. What is it?. Blocks of code that execute independently of other code blocks within the same process. Known as a thread of control, or simply a thread - PowerPoint PPT Presentation

Transcript of Concurrent Programming in JAVA

Page 1: Concurrent Programming in JAVA

Concurrent Programming in JAVA

What is it?

When/How do I use it?

When is my class safe?

What should I think about during Design?

Page 2: Concurrent Programming in JAVA

What is it?

• Blocks of code that execute independently of other code blocks within the same process.

• Known as a thread of control, or simply a thread

• Same as a machine that does multi-tasking

Page 3: Concurrent Programming in JAVA

From Mr. Bunny's Big Cup o' Java

"Java supports a deterministic scheduling algorithm called change thepriority and see if it makes any difference."

Page 4: Concurrent Programming in JAVA

When do I use it?

• Heavy computational requirements

• Waiting on I/O

• Simulation of independent objects

• GUI interactions

• Mobile code

• Embedded Systems

• Test Suites

Page 5: Concurrent Programming in JAVA

How do I use it?(Part 1)

• Create a class that extends the class Thread– This will limit the capability of the class

– Can be a perfect solution however.

• Create a class that implements the Runnable Interface– Allows a class to maintain its inheritance structure

– May have a class implementing Runnable that can be used by many classes within an application.

Page 6: Concurrent Programming in JAVA

Example 1

import java.util.Properties;import java.io.*;

public class PropertiesThread extends Thread {

private String theFileName;

public PropertiesThread(String fileName) { theFileName = fileName; }

Page 7: Concurrent Programming in JAVA

Example 1

public void run() { File file = new File(theFileName); try { FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); Properties props = System.getProperties(); props.load(bis); } catch (Exception ex) {

//handle exception } }

Page 8: Concurrent Programming in JAVA

Example 1

public class UseProperty {

public UseProperty(String propFileName) { PropertyThread propThread = new PropertyThread(propFileName); propThread.start();

//Do More Stuff }

public static void main(String[] args) { UseProperty useProps =

new UseProperty(args[0]); }}

Page 9: Concurrent Programming in JAVA

Example 2

public class CreditCard extends Payment implements Runnable { private String cardNumber; private String exprDate; private CCService service = null;

public CreditCard () {Thread t = new Thread(this);t.start();

} public void setValues (String aCardNumber, String anExprDate,

float anAmount) {cardNumber = aCardNumber;exprDate = anExprDate;setAmount(anAmount);

}

Page 10: Concurrent Programming in JAVA

Example 2

public String authorize () { while (service == null) {

try { Thread.sleep(500);

} catch (InterruptedException interEx) { }

}return service.authorize(cardNumber, exprDate, amount);

}

Page 11: Concurrent Programming in JAVA

Example 2

public void run() {while (true) {

try { service = //Some Lookup Facility

break; } catch (Exception ex) {

//Decide what to do }

} }}

Page 12: Concurrent Programming in JAVA

How do I use it?(Part 1)

Thread Class• start() - This method will create a new

thread of control and the code in the run() method will execute

• run() - This method will do nothing unless it is overridden in a sub-class or a class that implements the Runnable interface was an argument to the Thread’s constructor.

Page 13: Concurrent Programming in JAVA

How do I use it?(Part 1)

Thread Class• interrupt(), interrupted(), isInterrupted() -

These methods allow a thread to be canceled, as well as check the status and/or reset the interrupt status for the Thread.

• yield() - This method pauses the current Thread to allow others to execute. It is merely a hint to the JVM.

Page 14: Concurrent Programming in JAVA

How do I use it?(Part 1)

Thread Class• stop() - DO NOT USE THIS METHOD! It is

unsafe. It will throw a ThreadDeath exception that will cause all the locks to be released, exposing possibly damaged objects to other Threads. The code cannot perform any necessary rollback procedures, etc.

• suspend() - DITTO! Same with the complementary method resume(), use wait() and notify()

Page 15: Concurrent Programming in JAVA

When is my class safe?

• It is Immutable– The class contains no fields– The class contains only fields that are final

• It contains locking to protect against invalid states for fields.– Using the synchronized key word on methods or code

blocks

• It is Confined– Guaranteeing that only one thread (or at most one thread at

a time has access

Page 16: Concurrent Programming in JAVA

Examplespublic class ImmutableHello {

public String sayHello(String name) {return “Hello “+name+”!”;

}}

public class SyncPayment {private float amount;

public synchronized float getAmount() { return amount;

}

public synchronized void setAmount(float anAmount) { amount = anAmount;

}}

Page 17: Concurrent Programming in JAVA

Examples

Per 2.2.7 of Concurrent Programming in Java, page 94:

“Atomicity guarantees ensure that when a non-long/double is usedin an expression, you will obtain either its initial value or somevalue that was written by some thread, but not some jumble of bitsresulting from two or more threads both trying to write values atthe same time. However, as seen below (not shared here), atomicity alone does not guarantee that you will get the valuemost recently written by any thread. For this reason, atomicityguarantees per se normally have little impact on concurrent program design.”

Page 18: Concurrent Programming in JAVA

Types/Examples• Method Confinement

• Thread Confinement

• Object Confinement

public class MyMethodConfinement { public Sring displayBalance(long acctNum) {

Account account = new Account(acctNum);return “The Balance is: “+account.getBalance();

}

Page 19: Concurrent Programming in JAVA

Examples

public class MyThreadConfinement implements Runnable{static ThreadLocal databaseConn = new ThreadLocal(); final String connectString;public void dbConnection() { try {

connectString = System.getProperty(“DATABASE_STR”);

Thread thread = new Thread(this);thread.start();

} catch (Exception ex) {//Handle failure

} }

Page 20: Concurrent Programming in JAVA

Examples

public void run() { Connection conn = Database.getConnection(connectStr); databaseConn.set(conn);}

public ResultSet executeMyQuery() { Connection aConn = (Connection) databaseConn.get(); //Use conn2 to process a query and return a ResultSet }}

Page 21: Concurrent Programming in JAVA

Examples

public class HostObject() {private final NTSObject ntsObject;public HostObject(String name) {

ntsObject = new NTSObject(name);}

public synchronized String getName() {return ntsObject.getName();

}

public synchronized Address getAddress() {return ntsObject.getAddress();

}}

Page 22: Concurrent Programming in JAVA

What should I think about during Design?

• Safety vs. Liveliness - Too many locks can increase overhead as well as affect liveliness

• Look to make sure that 1 lock isn’t being used to protect more than one piece of functionality.

• Do not lock around long executing blocks of code

• Do not synchronize on stateless methods

Page 23: Concurrent Programming in JAVA

What should I think about during Design?

Things I Can Do• Separate Synchronization

– isolate critical code, proceed on

• Split independent functionality into separate classes– Host and Helper classes

• Reduce Synchronization– decide whether or not a field can ever be set to an illegal

value– decide whether or not a field can be stale.– remove the accessor itself

Page 24: Concurrent Programming in JAVA

What should I think about during Design?

Things I Can Do

• Split the locks themselves

• Separate fields that are inter-dependent into a separate class.

Page 25: Concurrent Programming in JAVA

How do I use it?(Part 2)

Utility Classes

• No way to back off from an attempt to obtain a lock that is held

• To give up waiting after an amount of time

• No way to specify a read vs write type lock.

• Cannot acquire a lock in one method and release in another

• Can create denial-of-service problems

Page 26: Concurrent Programming in JAVA

How do I use it?(Part 2)

Utility Classes

• Read/Write Locks – an interface that contains readLock() and

writeLock() methods with the signature of the Sync interface

• The Mutex class implements the standard Sync interface– acquire, attempt, release

Page 27: Concurrent Programming in JAVA

Doug Lea’s Stuff

Home Page:http://g.oswego.edu/dl/

util.concurrent (from Home Page): /classes/EDU/oswego/cs/dl/util/concurrent/intro.html