Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lecture 12 More on Hashing Multithreading. 2 Speakers!

Similar presentations


Presentation on theme: "1 Lecture 12 More on Hashing Multithreading. 2 Speakers!"— Presentation transcript:

1 1 Lecture 12 More on Hashing Multithreading

2 2 Speakers!

3 3 Hashing An object may contain an arbitrary amount of data, and searching a data structure that contains many large objects is expensive suppose your collection of Strings stores the text of various books, you are adding a book, and you need to make sure you are preserving the Set definition – ie that no book already in the Set has the same text as the one you are adding. A hash function maps each datum to a value to a fixed and manageable size. This reduces the search space and makes searching less expensive Hash functions must be deterministic, since when we search for an item we will search for its hashed value. If an identical item is in the list, it must have received the same hash value

4 4 Hashing Any function that maps larger data to smaller ones must map more than one possible original datum to the same mapped value Diagram from Wikipedia When more than one item in a collection receives the same hash value, a collision is said to occur. There are various ways to deal with this. The simplest is to create a list of all items with the same hash code, and do a sequential or binary search of the list if necessary

5 5 Hashing Hash functions often use the data to calculate some numeric value, then perform a modulo operation. This results in a bounded-length hash value. If the calculation ends in % n, the maximum hash value is n-1, no matter how large the original data is. It also tends to produce hash values that are relatively uniformly distributed, minimizing collisions. Modulo may be used again within a hash-based data structure in order to scale the hash values to the number of keys found in the structure

6 6 Hashing Sparse: A AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ Not Sparse: Juror 1 Juror 2 Juror 3 Juror 4 The more sparse the data, the more useful hashing is

7 7 Hashing Hashing is used for many purposes in programming. The one we are interested in right now is that it makes it easier to look up data or memory addresses in a table

8 8 Why Hashing? The preceding chapters introduced search trees. An element can be found in O(logn) time in a well-balanced search tree. Is there a more efficient way to search for an element in a container? This chapter introduces a technique called hashing. You can use hashing to implement a map or a set to search, insert, and delete an element in O(1) time.

9 9 Map Recall that a map stores entries. Each entry contains two parts: key and value. The key is also called a search key, which is used to search for the corresponding value. For example, a dictionary can be stored in a map, where the words are the keys and the definitions of the words are the values. A map is also called a dictionary, a hash table, or an associative array.

10 10 What is Hashing? If you know the index of an element in the array, you can retrieve the element using the index in O(1) time. So, can we store the values in an array and use the key as the index to find the value? The answer is yes if you can map a key to an index. The array that stores the values is called a hash table. The function that maps a key to an index in the hash table is called a hash function. Hashing is a technique that retrieves the value using the index obtained from key without performing a search.

11 11 Hash Function and Hash Codes A typical hash function first converts a search key to an integer value called a hash code, and then compresses the hash code into an index to the hash table.

12 12 What is Hashing? A collision occurs when multiple values receive the same hash code. There are several standard ways to deal with collisions. The first approach, open addressing, involves ways of finding available addresses in the table. The simplest form of this is linear probing, which checks whether the key is found at the expected place in the array. If not, it checks the next spot, etc. There are more complex variants of open addressing, which you can read about in the textbook. The second approach, separate chaining, uses a list at each location in the hash table. When looking up a value by hash, search the list of all nodes with that hash value.

13 13 Linear Probing

14 14 Handling Collisions Using Separate Chaining The separate chaining scheme places all entries with the same hash index into the same location, rather than finding new locations. Each location in the separate chaining scheme is called a bucket. A bucket is a container that holds multiple entries.

15 15 Implementing Map Using Hashing Run TestMyHashMap MyHashMap MyMap

16 Multithreading Multithreading is just what it sounds like: concurrent running of multiple tasks. Multithreading does not always involve parallel execution, in which multiple operations are executed simultaneously. It can be implemented in a situation in which multiple threads have access to the CPU at different times 16

17 Multithreading Multithreading has been available in programming for a long time, even when it was unusual to run an application on multiple processors. Multithreading offers a way to run multiple tasks at once without blocking, ie making tasks wait for another task which has not completed because it is waiting for user input, for some resource to become available, for a set amount of time to pass, etc. Multithreading offers a way to give higher-priority tasks access to resources when needed without starving lower-priority ones Event driven programming with GUI components often uses multiple threads, some of which are waiting for user input. 17

18 Multithreading Multithreading also makes it easier for an operating system or other scheduling mechanism to spread work among different processors. This is increasingly important as multiple cores have become the norm and as distributed applications, ones running on multiple computers on a network, become more prevalent. 18

19 Threads Concept 19 Multiple threads on multiple CPUs Multiple threads sharing a single CPU

20 Creating Tasks and Threads 20 Write a class that implements Runnable Instantiate a Thread, sending an instance of your Runnable implementation to the constructor Call start() on the Thread

21 The Thread Class 21

22 The Static sleep(milliseconds) Method The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. For example, consider this code: int lastNum = 15; for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); try { Thread.sleep(i* i * i); } catch (InterruptedException ex) { } Every time a number i is printed, the current thread is put to sleep for i 3 milliseconds. 22

23 The following example uses a.wav file which is available at http://cd.textfiles.com/10000soundssongs/WAV/COWBELL2.WAV Any other very short.wav file would work too. 23

24 package week8; import javax.sound.sampled.*; import java.io.File; import java.io.IOException; import javax.sound.sampled.LineEvent.Type; public class WavPlayer { File file; AudioListener listener; AudioInputStream audioInputStream; public WavPlayer(String fileName) { file = new File(fileName); } public void playClip() throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException { listener = new AudioListener(); audioInputStream = AudioSystem.getAudioInputStream(file); try { Clip clip = AudioSystem.getClip(); clip.addLineListener(listener); clip.open(audioInputStream); try { clip.start(); listener.waitUntilDone(); } finally { clip.close(); } } finally { audioInputStream.close(); } private class AudioListener implements LineListener { private boolean done = false; @Override public synchronized void update(LineEvent event) { Type eventType = event.getType(); if (eventType == Type.STOP || eventType == Type.CLOSE) { done = true; // notifyAll() tells all objects or threads that are waiting for // the line to do something that its state has changed notifyAll(); } public synchronized void waitUntilDone() throws InterruptedException { while (!done) { wait(); } 24

25 package week8; public class Rhythm implements Runnable { private int interval; private WavPlayer player; public Rhythm(String wav, int intervalIn) { interval = intervalIn; player = new WavPlayer(wav); } @Override public void run() { while (true) { try { player.playClip(); Thread.sleep(interval); } catch (Exception e) { e.printStackTrace(); } 25

26 package week8; public class RhythmDriver { public static void main(String[] args) { Rhythm r1 = new Rhythm("cowbell2.WAV", 400); Rhythm r2 = new Rhythm("cowbell2.WAV", 600); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } 26


Download ppt "1 Lecture 12 More on Hashing Multithreading. 2 Speakers!"

Similar presentations


Ads by Google