Session 6 Multithreading Object Equality How can we
Session 6: Multithreading
Object Equality • How can we test the equality of two objects? • For integer or float or any primitive types the equality is tested via == operator. • What about objects? • What happens if we compare obj 1 == obj 2?
Testing Equality Student student 1 = new Student("A", 10); Student student 2 = new Student("A", 10); if(student 1 == student 2){ System. out. println("Equal"); }else{ System. out. println("Not Equal"); } Output: Not Equal
Testing Equality Line line = new Line(1, 1, 5, 6); Shape a. Shape = line; if (line == a. Shape) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } Output: Equal
Using “==” on References • If two references are compared using “==”, then Java just examines whether they point to the same object or not • If we want to assume that two different objects are equal when their members have identical values, we have to override the “ ” method which is a member of object class and use it instead of “==” – By default, the “equals” methods also performs the same check like “==“
The “equals” method • Checks to see whether two objects are equal or not • We can override this method to implement our own equality logic • Method signature public boolean Object • As the parameter is passed as object, performed inside the overridden “equals” method • Note that, if coded improperly, the downcasting may throw “ ” • Should use the “ ” operator to prevent the “Class. Cast. Exception” from occurring
equals public class Person { private String name; public Person(String name) { this. name = name; } @Override public booleanequals(Objecto) { Person person = (Person) o; return this. name. equals(person. name); } } Person person 1 = new Person("Sakib"); Person person 2 = new Person("Sakib"); if (person 1 == person 2) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } if (person 1. equals(person 2)) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } Output: Not Equal
Try it!! • Write proper instance of testing. • Write a class name Student. It had two fields – Name – Mark • Write custom logic for equality testing.
Output Student student 1 = new Student("A", 10); Student student 2 = new Student("A", 10); if (student 1 == student 2) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } if (student 1. equals(student 2)) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } if (student 1. equals(new Integer[4])) { System. out. println("Equal"); } else { System. out. println("Not Equal"); } Output: Not Equal
Let’s muse What will happen if the code is executed? for(inti=0; true ; i++){ System. out. println("Loop one count: " + i); } Second loop will never get executed !! for(intj=0; true ; j++){ System. out. println("Loop two count: " + j); }
Solution • What happens if we need to concurrent execution flow. • Normal solution is to write two separate programs. • But there are much smart solution -
processes and threads • In concurrent programming, there are two basic units of execution: and • A computer system normally has many active processes and threads. • Processing time for a single core is shared among processes and threads through an OS feature called time slicing.
Processes • A process has a self-contained execution environment. • Processes are often seen as synonymous with programs or applications. • A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. • Generally we can say: Microsoft word is running as a process; Media Player, Internet Explorer too.
Threads • Threads are sometimes called lightweight processes. • Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. • Threads exist within a process — every process has. • Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
Windows Task Manager
Mac Os X : Activity Monitor
Who to write thread!! • Two basic ways – extending Thread class – implementing Runnable interface • There is not restriction on doing any one of that. • But generally implementing more appreciated. • Because java supports only one extension. In some cases it may not be possible to extend Thread class as the class already could extend some other class.
Extending Thread Class public class Simple. Thread extends Thread { @Override public void run() { for (inti = 1; i< 10; i++) { System. out. println(i); } } public static void main(String[] args) { Thread thread = new Simple. Thread(); thread. start(); System. out. println("Line bellow thread. start()"); } }
Implementing Runnable Interface public class Simple. Runnable implements Runnable { @Override public void run() { for (inti = 1; i< 10; i++) { System. out. println(i); } } } public static void main(String[] args) { Thread thread = new Thread(new. Simple. Runnable()); thread. start(); System. out. println("Line bellow thread. start()"); }
sleep() • You can introduce some delay in currently executing thread. • sleep() is a static function of Thread class. Thread. sleep(100); //delay in millisecond Thread. sleep(100, 123); //delay in millisecond plus nanoseconds
Let’s try!! • Write two classes – Unit. One – Unit. Two • Each of them implements Runnable interface. • Unit. One print’s cumulative sum up to 30 with a delay 300 milliseconds. • And Unit. Two prints factorial up to 15 with a delay of 400 milliseconds.
Output Thread unit. One. Thread = new Thread(new. Unit. One()); Thread unit. Two. Thread = new Thread(new. Unit. Two()); unit. One. Thread. start(); unit. Two. Thread. start(); System. out. println("End of main thread. "); Sum up to 5 = 1 + 2 + 3 + 4 + 5 Factorial up to 5 = 1 * 2 * 3 * 4 * 5 Output: Sum up to 1 is 1 Factorial up to 1 is 1 End of main thread. Sum up to 2 is 3 Factorial up to 2 is 2 Sum up to 3 is 6 Factorial up to 3 is 6 Sum up to 4 is 10 Factorial up to 4 is 24 Sum up to 5 is 15 Sum up to 6 is 21 Factorial up to 5 is 120 Sum up to 7 is 28
Shared Resources • The most complex part of multithreading programming. • Imagine a server there is a queue of requests. • Multiple users can request for the service. • And there could be more then one serving unit that could serve the user request.
Simple shared resource scenario - 1 Note Book (Shared) User 1 User 2 User 3 User 4 User 5 User 6 What happens if all the users try to write in the note book simultaneously
Simple shared resource scenario - 2 Service Provider 1 Service Provider 2 Service Provider 3 What happens if the shared resource is accessed simultaneously? Queue(Sh ared) User 4 User 1 User 3 User 2 User 6 User 5
Synchronization • The solution to the problem is synchronization. • Java has a rich support for synchronization of shared resources.
Example - Notebook • One note book • Multiple writer.
Note. Book. java public class Note. Book { } private final List<String> notes; public intget. Length() { synchronized (this. notes) { return this. notes. size(); } } public Note. Book() { notes = Collections. synchronized. List(new. Array. List<Stri ng>()); } public void add. Note(String note) { synchronized (this. notes) { System. out. println("Adding: " + note); this. notes. add(note); } } public String get. Note(int index) { synchronized (this. notes) { return this. notes. get(index); } } @Override public String to. String() { synchronized (this. notes) { return this. notes. to. String(); } }
Writer. java @Override public void run() { public class Writer implements Runnable { for (inti = 1; i< 4; i++) { note. Book. add. Note("Note: " + i + " -by "" + name + """); private String name; private Note. Booknote. Book; try { private long delay; Thread. sleep(this. delay); } catch (Interrupted. Exception ex) { public Writer(String name, long delay, Note. Booknote. Book) { System. out. println("Writer " + name + " was interrupted"); this. name = name; } this. note. Book = note. Book; } this. delay = delay; } } } package thread. shared;
Thread. join() • One thread can wait for another thread to finish up the process then continue. • This could be done by calling • Run the examples with uncomment the join statements.
Let’s Try!! • Try to write a Reader that will print out the whole Notebook in every 150 milliseconds.
main() Note. Book notebook = new Note. Book(); Writer writer. One = new Writer("Tom", 100, notebook); Writer writer. Two = new Writer("Jerry", 500, notebook); Reader reader = new Reader(notebook); Thread thread. One = new Thread(writer. One); Thread thread. Two = new Thread(writer. Two); Thread thread. Reader = new Thread(reader); thread. One. start(); thread. Two. start(); thread. Reader. start(); try { thread. One. join(); thread. Two. join(); } catch (Interrupted. Exception ex) { System. out. println("Interupted. . . "); } System. out. println("Interupting Reader"); thread. Reader. interrupt(); System. out. println("Ending main");
Output Adding: Note: 1 -by "Tom" Adding: Note: 1 -by "Jerry" [Note: 1 -by "Tom", Note: 1 -by "Jerry"] Adding: Note: 2 -by "Tom" [Note: 1 -by "Tom", Note: 1 -by "Jerry", Note: 2 -by "Tom"] Adding: Note: 3 -by "Tom" [Note: 1 -by "Tom", Note: 1 -by "Jerry", Note: 2 -by "Tom", Note: 3 -by "Tom"] Adding: Note: 2 -by "Jerry" [Note: 1 -by "Tom", Note: 1 -by "Jerry", Note: 2 -by "Tom", Note: 3 -by "Tom", Note: 2 -by "Jerry"] Adding: Note: 3 -by "Jerry" [Note: 1 -by "Tom", Note: 1 -by "Jerry", Note: 2 -by "Tom", Note: 3 -by "Tom", Note: 2 -by "Jerry", Note: 3 -by "Jerry"] Interupting Reader Ending main
- Slides: 33