Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CMPE212 – Section 001 - Reminders • Assignment 5 due Today. • Quiz marking not started yet... • Just after the final exam – make sure you have all assignment marks and that all quizzes are fully graded. Winter 2017 CMPE212 - Prof. McLeod 1 Today • Multi-Threading, Cont. • Multi-Core Threading. • What’s Left in Java? Winter 2017 CMPE212 - Prof. McLeod 2 Example Program • Suppose that we want to have a window that: 1. Has a timer counting seconds. 2. Buttons to start and stop the timer. 3. A TextArea node to store comments, provided one at a time. 4. A Close button to close the window. – No sweat, right? See LoggerNoThreads Winter 2017 CMPE212 - Prof. McLeod 3 So, What’s the Problem? • The program cannot move beyond the timer loop. • Events such as paint() calls will not get processed – they just pile up! • What’s the solution? Winter 2017 CMPE212 - Prof. McLeod 4 Multi-Threading • In a JavaFX program Application runs on its own thread. • Our timing loop is still on the Application thread and is blocking other thread processes. • The easiest way is to use the existing animation thread that is already available through the use of the Timeline object. • See LoggerTimeline Winter 2017 CMPE212 - Prof. McLeod 5 Timeline • From before: timeline = new Timeline(new KeyFrame(Duration.ZERO, actionEvent -> incrementClock()), new KeyFrame(Duration.millis(1000))); timeline.setCycleCount(Timeline.INDEFINITE); Winter 2017 CMPE212 - Prof. McLeod 6 Timeline, Cont. • Use timeline.playFromStart() to start the timer and timeline.stop() to halt it. • Invoking Platform.exit() will also stop all Application threads when you exit the program. Winter 2017 CMPE212 - Prof. McLeod 7 Multi-Threading, Cont. • Suppose you wish to create your own thread instead of piggybacking on an existing thread? • Use classes from the javafx.concurrent package. • These include Service and Task. • Threads based on the Thread class cannot work with the Application thread. Winter 2017 CMPE212 - Prof. McLeod 8 Task • Task is designed to work with JavaFX applications. • It cannot directly access scenegraph nodes on the Application thread, because Node objects are not “thread safe”. • It is a one-shot deal. Once the task is finished, you cannot re-start it. • It is generic! • You must override the T call() method. Winter 2017 CMPE212 - Prof. McLeod 9 Task, Cont. • call() contains the process that will run on a separate thread. • call() returns a type T, but if it does not return anything then you can return null and use “Void” for the type. Winter 2017 CMPE212 - Prof. McLeod 10 Task, Cont. • The class uses “update” methods to update node contents: • • • • updateMessage(String message) updateProgress(…) updateTitle(…) updateValue(T value) • These are to be bound to specific node properties: Winter 2017 CMPE212 - Prof. McLeod 11 Task, Cont. • Binding, example: lblTime.textProperty().bind(myService.messageProperty()); • “myService” is a Service object, but use the same syntax to bind a Task property to a node property. • Inside the Task call method: updateMessage("" + timeCounter); Winter 2017 CMPE212 - Prof. McLeod 12 Task, Cont. • These update calls are immediately “coalesced” on the Application thread. They may not run at once, but will run in the order in which they have been added to the main thread. • One way to update multiple nodes is to add a change listener to the bound node which updates the other nodes of interest. • Another is to use an AnimationTimer to trigger updates when a frame is drawn. Winter 2017 CMPE212 - Prof. McLeod 13 Task, Cont. • If you need to do more to the scenegraph that just update the property of a single node, then consider using: Platform.runLater(Runnable r) • The Runnable is a process (which can be a Task, for example) which will be piled onto the Application thread. Winter 2017 CMPE212 - Prof. McLeod 14 Service • A Task cannot be re-started. • Use a Service instead. • Service creates and manages a Task in a way that is compatible with the Application thread. • Generic! • Override the method: Task<T> createTask() • This method creates the Task object for the Service. Winter 2017 CMPE212 - Prof. McLeod 15 Service, Cont. • Has many useful methods to monitor and manipulate the task, including: – – – – – – .cancel() .cancelled() .isRunning() .reset() .restart() .start() // Stops the task // Returns true if the task is cancelled // Returns true if the task is running // Resets the service // Cancels and re-starts the task // Starts the task • See LoggerThreaded Winter 2017 CMPE212 - Prof. McLeod 16 The Thread Class, Cont. • Threads have a priority. • This helps the processor decided which thread gets a larger slice of processor time. • Threads with a lower priority can be delayed by CPU-intensive threads with a higher priority. • Use getPriority() and setPriority(int) methods. • Priorities lie between 1 and 10, with 5 being the default. • (Use Thread.MAX_PRIORITY, Thread.MIN_PRIORITY and Thread.NORM_PRIORITY.) Winter 2017 CMPE212 - Prof. McLeod 17 The Thread Class, Cont. • Other methods are listed in the API. • In particular, sleep(long sleeptime) can put the current thread to sleep for a specified number of milliseconds. This gives other threads a chance to do something. You should always place a sleep() command inside any loops in your thread. • sleep() can throw the InterruptedException too. • Or you can simply invoke the yield() method to pause the current thread and allow other threads to execute. Winter 2017 CMPE212 - Prof. McLeod 18 Multi-Threading, Cont. • The thread in a task can be halted (externally!) in two ways: • A cancel has been issued. • An InterruptedException has been thrown. • Inside a loop in your call method, you need to invoke .isCancelled() to see if you need to stop the loop. • Put any blocking calls like Thread.sleep() inside a try catch to catch the InterruptedException and use the catch to stop the loop. Winter 2017 CMPE212 - Prof. McLeod 19 Use of Multi-Core Processors in Java >7 • Look up the “Fork/Join” framework in the Java Tutorial, which is in the Concurrency section: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html • Designed to work best with recursive processes, it allows you to split your tasks over the multiple cores of your processor. • The framework handles all the multiple threads needed in a thread “pool”. Winter 2017 CMPE212 - Prof. McLeod 20 Multi-Core Processing, Cont. • The idea is straight-forward: if the task is small then: Do the task normally, non-recursively otherwise: Split the task into two parts and recurse. • The size of “small” depends on what you are trying to do – some experimentation will be required... Winter 2017 CMPE212 - Prof. McLeod 21 Multi-Core Processing, Cont. • You need to do this in such a way that the recursed tasks are given to “Worker” threads that are part of a thread pool controlled by the fork/join framework. • The framework spreads the threads over the available cores using a “Work stealing” algorithm: • If a core thread is idle a task can be stolen from a threaded core that is still busy. Winter 2017 CMPE212 - Prof. McLeod 22 Multi-Core Processing, Cont. • Your task must be built as a class that extends java.util.concurrent.RecursiveAction. • You need to write a concrete version of void compute() • This is where you carry out the tasks. • Recurse your task by instantiating your class twice and then supply these objects to a call to invokeAll(task1, task2) Winter 2017 CMPE212 - Prof. McLeod 23 Multi-Core Processing, Cont. • In order to start the process, instantiate your class for the first time and supply this object to the invoke() method of an instantiated ForkJoinPool object. • Sound complicated? Not really! • See the demo program MultiCoreQuicksortingExperiment.java. • Compares a normal quicksort to a multi-core quicksort. Winter 2017 CMPE212 - Prof. McLeod 24 Multi-Core Processing, Cont. • Note the use of: Runtime.getRuntime().availableProcessors() to get the number of available cores. • Even without any further experimentation to optimize the code, the multi-core version is definitely faster than a normally-coded quicksort! Winter 2017 CMPE212 - Prof. McLeod 25 Want to Know More about MultiThreading? • Read over the Concurrency section in the Java Tutorial: http://docs.oracle.com/javase/tutorial/essential/conc urrency/index.html Winter 2017 CMPE212 - Prof. McLeod 26 Other JavaFX Topics • Packaging, Deployment & Distribution. Web page embedded, stand-alone, etc. • 3D graphics. • Images and image manipulation. • 2D and 3D Animation. • Lots of other controls! • Charts. • Visual effects and transformation. • Media (sound and video) playback. Winter 2017 CMPE212 - Prof. McLeod 27 Other Java Topics • Other Collection Types. Iterators. • Streams. Sockets. Internet streams and web pages. • Regular expressions. • Working with databases. • Security. • JDBC, JSP, JMX, JNDI, JAXP, JAXB, RMI, … Winter 2017 CMPE212 - Prof. McLeod 28 More Acronyms! • • • • • • • Java Database Connectivity Java Server Pages Java Management Extensions Java Naming and Directory Interface Java API for XML Processing Java Architecture for XML Binding Remote Method Invocation • Look for ‘Specialized Trails and Lessons’ in the Java Tutorial. Winter 2017 CMPE212 - Prof. McLeod 29