L9: Making Software Run in Parallel And Display Things Flashcards
Concurrency
Threads are used in Java to allow concurrency
(running multiple instances of one process or different processes in parallel)
Without concurrency, all statements in Java are executed in order
Note that statements are also not atomic, for instance, ++ x;
Problems in concurrency arise, because threads work on shared memory
If it is dangerous, why use concurrency?
Developing graphical user interfaces (GUIs)
* Main thread drives the GUI
* Event handlers (e.g., clicking on a button) must respond quickly to not “hang” GUI
* In Java screen cannot be updated while event handler runs (in same thread)
How to make a singleton thread safe?
Either use eager instantiation (instance exists before any thread)
Or implement thread safety by forcing threads to synchronize when executing critical code
We can also synchronize single statements or check whether a thread isAlive()
What is Swing?
Java GUI library
(there are older [AWT] and newer alternatives [JavaFX])
Swing is all-Java for Desktop apps
* Components are building blocks (frames, panels, labels, buttons, text fields)
* Hierarchical organization (components contain other components)
* Components create events (e.g., user clicking a button) that can be “listened” to
General hints for GUIs in NetBeans
* For a new window you can add a new JFrame (will setup some basic corpus)
* Enables visual design tab to drag&drop components (NetBeans will generate the code)
Threading look at Swing
Swing distinguishes three types of threads
* Initial thread that execute the normal application (starts in main)
* Event dispatch thread that executes event-handling
* Worker/background threads that perform time-expensive background tasks
Most of these threads are created automatically
- utilize them to develop a responsive GUI
Note that only a few Swing components are labeled “thread save”
- everything else has to happen on the event dispatch thread
Command
It’s a useful pattern (not only) for threading
Encapsulate a request with all information needed to execute later
* Decouple call data and call moment
* Define
* What method to call
* In what object
* Using what arguments
* And what to do with the return value
Used for
* Undo/redo (graded assignment)
* Queues and logging
Compound commands
Consist of a sequence of commands including nesting and hierarchy
Can be implemented using the composite design pattern
Does not require a receiver
Offers an add method to append commands
Executes the contained commands in order of the defined sequence
and reverts the contained commands in reversed order