SocketTagger.java revision 5112325117859c7c6cd042c17f519f967c551b20
1/*
2 * Copyright (C) 2011 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 */
16
17package dalvik.system;
18
19import java.io.FileDescriptor;
20import java.net.Socket;
21import java.net.SocketException;
22
23/**
24 * Callbacks for socket assignment and reassignment.
25 *
26 * @hide
27 */
28public abstract class SocketTagger {
29
30    private static SocketTagger tagger = new SocketTagger() {
31        @Override public void tag(FileDescriptor socketDescriptor) throws SocketException {}
32        @Override public void untag(FileDescriptor socketDescriptor) throws SocketException {}
33    };
34
35    /**
36     * Notified when {@code socketDescriptor} is either assigned to the current
37     * thread. The socket is either newly connected or reused from a connection
38     * pool. Implementations of this method should be thread-safe.
39     */
40    public abstract void tag(FileDescriptor socketDescriptor) throws SocketException;
41
42    /**
43     * Notified when {@code socketDescriptor} is released from the current
44     * thread to a connection pool. Implementations of this method should be
45     * thread-safe.
46     *
47     * <p><strong>Note:</strong> this method will not be invoked when the socket
48     * is closed.
49     */
50    public abstract void untag(FileDescriptor socketDescriptor) throws SocketException;
51
52    public final void tag(Socket socket) throws SocketException {
53        tag(socket.getFileDescriptor$());
54    }
55
56    public final void untag(Socket socket) throws SocketException {
57        untag(socket.getFileDescriptor$());
58    }
59
60    /**
61     * Sets this process' socket tagger to {@code tagger}.
62     */
63    public static synchronized void set(SocketTagger tagger) {
64        if (tagger == null) {
65            throw new NullPointerException("tagger == null");
66        }
67        SocketTagger.tagger = tagger;
68    }
69
70    /**
71     * Returns this process socket tagger.
72     */
73    public static synchronized SocketTagger get() {
74        return tagger;
75    }
76}
77