summaryrefslogtreecommitdiff
path: root/SDL_Android/SmartDeviceLinkProxyAndroid/src/com/smartdevicelink/messageDispatcher/ProxyMessageDispatcher.java
blob: ca73b3ff16846f7c0abdfcc62b7e9bd52898b2dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.smartdevicelink.messageDispatcher;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

import com.smartdevicelink.util.DebugTool;

public class ProxyMessageDispatcher<messageType> {
	PriorityBlockingQueue<messageType> _queue = null;
	private Thread _messageDispatchingThread = null;
	IDispatchingStrategy<messageType> _strategy = null;

	// Boolean to track if disposed
	private Boolean dispatcherDisposed = false;
	
	public ProxyMessageDispatcher(String THREAD_NAME, Comparator<messageType> messageComparator, 
			IDispatchingStrategy<messageType> strategy) {
		_queue = new PriorityBlockingQueue<messageType>(10, messageComparator);
		
		_strategy = strategy;
		
		// Create dispatching thread
		_messageDispatchingThread = new Thread(new Runnable() {public void run(){handleMessages();}});
		_messageDispatchingThread.setName(THREAD_NAME);
		_messageDispatchingThread.setDaemon(true);
		_messageDispatchingThread.start();
	}
	
	public void dispose() {
		dispatcherDisposed = true;
		
		if(_messageDispatchingThread != null) {
			_messageDispatchingThread.interrupt();
			_messageDispatchingThread = null;
		}
	}
		
	private void handleMessages() {
		
		try {
			messageType thisMessage;
		
			while(dispatcherDisposed == false) {
				thisMessage = _queue.take();
				_strategy.dispatch(thisMessage);
			}
		} catch (InterruptedException e) {
			// Thread was interrupted by dispose() method, no action required
			return;
		} catch (Exception e) {
			DebugTool.logError("Error occurred dispating message.", e);
			_strategy.handleDispatchingError("Error occurred dispating message.", e);
		}
	}
		
	public void queueMessage(messageType message) {
		try {
			_queue.put(message);
		} catch(ClassCastException e) { 
			_strategy.handleQueueingError("ClassCastException encountered when queueing message.", e);
		} catch(Exception e) {
			_strategy.handleQueueingError("Exception encountered when queueing message.", e);
		}
	}
}