blob: 1702e408c1927cd6df9f7a9faa349dc5d41416be [file] [log] [blame]
Brett Chabot9c27c902013-09-27 11:00:56 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.tradefed.command.remote;
17
18import com.android.tradefed.device.ITestDevice;
19
20import java.util.ArrayList;
21import java.util.Collection;
22import java.util.Hashtable;
23import java.util.Map;
24
25/**
26 * Singleton class that tracks devices that have been remotely allocated.
27 */
28class DeviceTracker {
29
30 /**
31 * Use on demand holder idiom
32 * @see http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
33 */
34 private static class SingletonHolder {
35 public static final DeviceTracker cInstance = new DeviceTracker();
36 }
37
38 public static DeviceTracker getInstance() {
39 return SingletonHolder.cInstance;
40 }
41
42 // private constructor - don't allow instantiation
43 private DeviceTracker() {
44 }
45
46 // use Hashtable since its thread-safe
47 private Map<String, ITestDevice> mAllocatedDeviceMap = new Hashtable<String, ITestDevice>();
48
49 /**
50 * Mark given device as remotely allocated.
51 */
52 public void allocateDevice(ITestDevice d) {
53 mAllocatedDeviceMap.put(d.getSerialNumber(), d);
54 }
55
56 /**
57 * Mark given device serial as freed.
58 *
59 * @return the corresponding {@link ITestDevice} or <code>null</code> if device with given
60 * serial cannot be found
61 */
62 public ITestDevice freeDevice(String serial) {
63 return mAllocatedDeviceMap.remove(serial);
64 }
65
66 /**
67 * Mark all remotely allocated devices as freed.
68 *
69 * @return a {@link Collection} of all remotely allocated devices
70 */
71 public Collection<ITestDevice> freeAll() {
72 Collection<ITestDevice> devices = new ArrayList<ITestDevice>(mAllocatedDeviceMap.values());
73 mAllocatedDeviceMap.clear();
74 return devices;
75 }
76}