1 / 36

Lec 10 agenda

Lec 10 agenda. >git fetch origin lab10; > git checkout origin/lab10 -b lab10; Format/rules for Week 11 Advanced Topics (all beyond the scope of this course) Serialization Concurrency (Threads) Sockets Lab. Serialization.

ggadson
Télécharger la présentation

Lec 10 agenda

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. Lec 10 agenda >git fetch origin lab10; > git checkout origin/lab10 -b lab10; Format/rules for Week 11 Advanced Topics (all beyond the scope of this course) • Serialization • Concurrency (Threads) • Sockets Lab

  2. Serialization Allows you to turn Java Objects into serial data that can be either save to a file, store in a db, or send over a network. Useful for persisting data.

  3. Serialization analogy to physics Objects in Memory space are in a gas state and they're alive. Serialized objects are liquid and they're suspended (they can flow across networks, and be persisted to a hard-drives and databases)

  4. Serialization Syntax FileOutputStream filOut = new FileOutputStream("gamestate.ser"); ObjectOutputStream out = new ObjectOutputStream(filOut); out.writeObject(gst); out.close(); filOut.close();

  5. Deserialization Syntax FileInputStream filIn = new FileInputStream("gamestate.ser"); ObjectInputStream ois = new ObjectInputStream(filIn); gst= (GameState) ois.readObject(); ois.close(); filIn.close();

  6. Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed serially, from start to finish. In a threaded program, you can have multiple threads working concurrently.

  7. Process vs. Threads Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time. Threads: threads are so-called lightweight processes which have their own call-stack but can access shared data on the heap. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache.

  8. Threads are short-lived Threads are like processes, only they're short-lived. How short-lived? • When run() method terminates or returns • The thread is interrupted • An exception is thrown inside run()

  9. Concurrency (Threads) Concurrency is achieved through time-slicing. This is where the processor cycles through each active thread for an indeterminate period of time (the slice). This gives the illusion that there are multiple processes. With multi-core processors, this may mean, true multi-threading is possible, but NOT guaranteed

  10. Amdahl's Law Concurrency promises to perform certain task faster as these tasks can be divided into subtasks and these subtasks can be executed in parallel. Of course the runtime is limited by parts of the task which can be performed in parallel. The theoretical possible performance gain can be calculated by Amdahl's Law. If F (fixed) is the percentage of the program which can not run in parallel and n is the number of processes then the maximum performance gain is: 1/ (F+ ((1-F)/n)).

  11. Issues in Concurrency A visibility problem occurs if one thread reads shared data which is later changed by other thread and if thread A does not see this change. A access problem occurs if several thread trying to access and change the same shared data at the same time.

  12. Concurrency Failures Liveness failure: The program does not react anymore due to problems in the concurrent access of data, e.g. deadlocks. Safety failure: The program creates incorrect data.

  13. Syncrhonized keyword that only a single thread can execute a block of code at the same time ensures that each thread entering a synchronized block of code sees the effects of all previous modifications that were guarded by the same lock

  14. Volatile keyword If a variable is declared as volatile then it is guaranteed that any thread which reads the field will see the most recently written value.  This is to guard against caching. If you use synchronized properly, you don't need to worry about volatile.

  15. Car + Engine + Turn-key Runnable Thread .start()

  16. Car + Engine + Turn-key Runnable Thread .start() Thread thr = new Thread(new MyRunner()); thr.start(); //start will spawn a new thread

  17. Define your own Runnable class private class MyRunner implements Runnable { @Override public void run() { //do some work } }

  18. anonymous-inner class Thread thr = new Thread(new Runnable() { @Override public void run() { } }); thr.start();

  19. Reference anonymous thread and anonymous-inner class new Thread(new Runnable() { @Override public void run() { } }).start();

  20. Thread which can run itself private class MyRunningThread extends Thread { @Override public void run { //do some work } } new MyRunningThread().start();

  21. Thread Pools Thread Pools manage (and limit) the number of active threads. This tends to be more orderly and more efficient for scaled applications.

  22. Synchronizing methods When multiple threads have access to the same object, it makes sense to synchronize those methods which are prone to concurrency errors. The bank account example.

  23. Thread-safe collections //http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

  24. Running a Thread • Implement a class that implements the Runnable interface: public interface Runnable { void run(); } • Place the code for your task into the run method of your class: public class MyRunnable implements Runnable { public void run() { Task statements ... } }

  25. Running a Thread • Create an object of your subclass: Runnable r = new MyRunnable(); • Construct a Threadobject from the runnable object: Thread t = new Thread(r); • Call the start method to start the thread: t.start();

  26. Running Threads • sleep puts current thread to sleep for given number of milliseconds: Thread.sleep(milliseconds) • When a thread is interrupted, most common response is to terminate run

  27. Genericrunmethod public void run() { try { Task statements } catch (InterruptedException exception) { } Clean up, if necessary}

  28. ch20/greeting/GreetingRunnable.java 1 import java.util.Date; 2 3 /** 4 A runnable that repeatedly prints a greeting. 5 */ 6 publicclass GreetingRunner implements Runnable 7 { 8 privatestaticfinalint REPETITIONS = 10; 9 privatestaticfinalint DELAY = 1000; 10 11 private String strGreeting; 12 13 /** 14 Constructs the runnable object. 15 @param aGreeting the greeting to display 16 */ 17 public GreetingRunner(String strGreeting) 18 { 19 this.strGreeting = strGreeting; 20 } 21 Continued

  29. To Start the Thread • Construct an object of your runnableclass: Runnable t = new GreetingRunnable("Hello World"); • Then construct a thread and call the start method: Thread t = new Thread(r); t.start();

  30. Thread Scheduler • Thread scheduler: runs each thread for a short amount of time (a time slice) • Then the scheduler activates another thread • There will always be slight variations in running times - especially when calling operating system services (e.g. input and output) • There is no guarantee about the order in which threads are executed

  31. Terminating Threads • A thread terminates when its run method terminates • Do not terminate a thread using the deprecated stop method • Instead, notify a thread that it should terminate: t.interrupt(); • interrupt does not cause the thread to terminate – it sets a boolean variable in the thread data structure

  32. Terminating Threads • The run method should check occasionally whether it has been interrupted • Use the interruptedmethod • An interrupted thread should release resources, clean up, and exit: public void run() { for (int i = 1; i <= REPETITIONS && !Thread.interrupted(); i++) {Do work }Clean up }

  33. Terminating Threads • Java does not force a thread to terminate when it is interrupted • It is entirely up to the thread what it does when it is interrupted • Interrupting is a general mechanism for getting the thread’s attention

  34. Synchronizing Object Access • When a thread calls lock, it owns the lock until it calls unlock • A thread that calls lock while another thread owns the lock is temporarily deactivated • Thread scheduler periodically reactivates thread so it can try to acquire the lock • Eventually, waiting thread can acquire the lock

  35. Sockets See example package called socket from lab10

  36. SwingWorker SwingWorker takes two Object parameters. +The first is the return value and is passed to done() +The second parameter is the progress value and is passed to publish/process. Example: SwingWorker<Boolean, Integer> There are three important methods of SwingWorker. +doInBackGround() --background thread +process() -main UI thread +done() -main UI thread

More Related