1 lecture 12 more on hashing multithreading. 2 speakers!

26
1 Lecture 12 More on Hashing Multithreading

Upload: brandon-todd

Post on 31-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

1

Lecture 12 More on HashingMultithreading

2

Speakers!

3

HashingAn object may contain an arbitrary amount of data, and searching a data structure that contains many large objectsis 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 expensiveHash 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

HashingAny function that maps larger data to smaller ones must map more than one possible original datum to the same mapped value

Diagram from WikipediaWhen 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

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

HashingSparse:AAAABACADAEAFAG AHAIAJAK

ALAMANAOAPAQARASATAUAVAWAX

AYAZ

Not Sparse:

Juror 1Juror 2Juror 3Juror 4

The more sparse the data, the more useful hashing is

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

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

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

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

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

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

Linear Probing

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.

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

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.

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.

19

Threads ConceptMultiple threads on multiple CPUs

Multiple threads sharing a single CPU

Thread 3

Thread 2

Thread 1

Thread 3

Thread 2

Thread 1

20

Creating Tasks and Threads

// Custom task class public class TaskClass implements Runnable { ... public TaskClass(...) { ... } // Implement the run method in Runnable public void run() { // Tell system how to run custom thread ... } ... }

// Client class public class Client { ... public void someMethod() { ... // Create an instance of TaskClass TaskClass task = new TaskClass(...); // Create a thread Thread thread = new Thread(task); // Start a thread thread.start(); ... } ... }

java.lang.Runnable

TaskClass

Write a class that implements RunnableInstantiate a Thread, sending an instance of your Runnable implementation to the constructorCall start() on the Thread

21

The Thread Class

java.lang.Thread

+Thread()

+Thread(task: Runnable)

+start(): void

+isAlive(): boolean

+setPriority(p: int): void

+join(): void

+sleep(millis: long): void

+yield(): void

+interrupt(): void

Creates a default thread.

Creates a thread for a specified task.

Starts the thread that causes the run() method to be invoked by the JVM.

Tests whether the thread is currently running.

Sets priority p (ranging from 1 to 10) for this thread.

Waits for this thread to finish.

Puts the runnable object to sleep for a specified time in milliseconds.

Causes this thread to temporarily pause and allow other threads to execute.

Interrupts this thread.

«interface» java.lang.Runnable

22

The Static sleep(milliseconds) MethodThe 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 i3 milliseconds.

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.

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;

@Overridepublic 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 changednotifyAll();

}}

public synchronized void waitUntilDone() throws InterruptedException {while (!done) {

wait();}

}}

}

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);

}

@Overridepublic void run() {

while (true) {try {

player.playClip();

Thread.sleep(interval);

} catch (Exception e) {e.printStackTrace();

}

}}

}

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();

}}