1 / 27

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?. 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

Download Presentation

Concurrent Programming in JAVA

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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?

  2. 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

  3. From Mr. Bunny's Big Cup o' Java "Java supports a deterministic scheduling algorithm called change the priority and see if it makes any difference."

  4. When do I use it? • Heavy computational requirements • Waiting on I/O • Simulation of independent objects • GUI interactions • Mobile code • Embedded Systems • Test Suites

  5. 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.

  6. Example 1 import java.util.Properties; import java.io.*; public class PropertiesThread extends Thread { private String theFileName; public PropertiesThread(String fileName) { theFileName = fileName; }

  7. 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 } }

  8. 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]); } }

  9. 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); }

  10. Example 2 public String authorize () { while (service == null) { try { Thread.sleep(500); } catch (InterruptedException interEx) { } } return service.authorize(cardNumber, exprDate, amount); }

  11. Example 2 public void run() { while (true) { try { service = //Some Lookup Facility break; } catch (Exception ex) { //Decide what to do } } } }

  12. 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.

  13. 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.

  14. 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()

  15. 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

  16. public 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; } } Examples

  17. Examples Per 2.2.7 of Concurrent Programming in Java, page 94: “Atomicity guarantees ensure that when a non-long/double is used in an expression, you will obtain either its initial value or some value that was written by some thread, but not some jumble of bits resulting from two or more threads both trying to write values at the same time. However, as seen below (not shared here), atomicity alone does not guarantee that you will get the value most recently written by any thread. For this reason, atomicity guarantees per se normally have little impact on concurrent program design.”

  18. 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(); }

  19. 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 } }

  20. 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 } }

  21. 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(); } }

  22. 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

  23. 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

  24. 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.

  25. 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

  26. 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

  27. 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

More Related