Path: blob/master/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java
41155 views
/*1* Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package sun.rmi.transport;2526import java.lang.ref.ReferenceQueue;27import java.rmi.NoSuchObjectException;28import java.rmi.Remote;29import java.rmi.dgc.VMID;30import java.rmi.server.ExportException;31import java.rmi.server.ObjID;32import java.security.AccessController;33import java.security.PrivilegedAction;34import java.util.HashMap;35import java.util.Map;36import sun.rmi.runtime.Log;37import sun.rmi.runtime.NewThreadAction;3839/**40* Object table shared by all implementors of the Transport interface.41* This table maps object ids to remote object targets in this address42* space.43*44* @author Ann Wollrath45* @author Peter Jones46*/47public final class ObjectTable {4849/** maximum interval between complete garbage collections of local heap */50@SuppressWarnings("removal")51private final static long gcInterval = // default 1 hour52AccessController.doPrivileged((PrivilegedAction<Long>) () ->53Long.getLong("sun.rmi.dgc.server.gcInterval", 3600000));5455/**56* lock guarding objTable and implTable.57* Holders MAY acquire a Target instance's lock or keepAliveLock.58*/59private static final Object tableLock = new Object();6061/** tables mapping to Target, keyed from ObjectEndpoint and impl object */62private static final Map<ObjectEndpoint,Target> objTable =63new HashMap<>();64private static final Map<WeakRef,Target> implTable =65new HashMap<>();6667/**68* lock guarding keepAliveCount, reaper, and gcLatencyRequest.69* Holders may NOT acquire a Target instance's lock or tableLock.70*/71private static final Object keepAliveLock = new Object();7273/** count of non-permanent objects in table or still processing calls */74private static int keepAliveCount = 0;7576/** thread to collect unreferenced objects from table */77private static Thread reaper = null;7879/** queue notified when weak refs in the table are cleared */80static final ReferenceQueue<Object> reapQueue = new ReferenceQueue<>();8182/** handle for GC latency request (for future cancellation) */83private static GC.LatencyRequest gcLatencyRequest = null;8485/*86* Disallow anyone from creating one of these.87*/88private ObjectTable() {}8990/**91* Returns the target associated with the object id.92*/93static Target getTarget(ObjectEndpoint oe) {94synchronized (tableLock) {95return objTable.get(oe);96}97}9899/**100* Returns the target associated with the remote object101*/102public static Target getTarget(Remote impl) {103synchronized (tableLock) {104return implTable.get(new WeakRef(impl));105}106}107108/**109* Returns the stub for the remote object <b>obj</b> passed110* as a parameter. This operation is only valid <i>after</i>111* the object has been exported.112*113* @return the stub for the remote object, <b>obj</b>.114* @exception NoSuchObjectException if the stub for the115* remote object could not be found.116*/117public static Remote getStub(Remote impl)118throws NoSuchObjectException119{120Target target = getTarget(impl);121if (target == null) {122throw new NoSuchObjectException("object not exported");123} else {124return target.getStub();125}126}127128/**129* Remove the remote object, obj, from the RMI runtime. If130* successful, the object can no longer accept incoming RMI calls.131* If the force parameter is true, the object is forcibly unexported132* even if there are pending calls to the remote object or the133* remote object still has calls in progress. If the force134* parameter is false, the object is only unexported if there are135* no pending or in progress calls to the object.136*137* @param obj the remote object to be unexported138* @param force if true, unexports the object even if there are139* pending or in-progress calls; if false, only unexports the object140* if there are no pending or in-progress calls141* @return true if operation is successful, false otherwise142* @exception NoSuchObjectException if the remote object is not143* currently exported144*/145public static boolean unexportObject(Remote obj, boolean force)146throws java.rmi.NoSuchObjectException147{148synchronized (tableLock) {149Target target = getTarget(obj);150if (target == null) {151throw new NoSuchObjectException("object not exported");152} else {153if (target.unexport(force)) {154removeTarget(target);155return true;156} else {157return false;158}159}160}161}162163/**164* Add target to object table. If it is not a permanent entry, then165* make sure that reaper thread is running to remove collected entries166* and keep VM alive.167*/168static void putTarget(Target target) throws ExportException {169ObjectEndpoint oe = target.getObjectEndpoint();170WeakRef weakImpl = target.getWeakImpl();171172if (DGCImpl.dgcLog.isLoggable(Log.VERBOSE)) {173DGCImpl.dgcLog.log(Log.VERBOSE, "add object " + oe);174}175176synchronized (tableLock) {177/**178* Do nothing if impl has already been collected (see 6597112). Check while179* holding tableLock to ensure that Reaper cannot process weakImpl in between180* null check and put/increment effects.181*/182if (target.getImpl() != null) {183if (objTable.containsKey(oe)) {184throw new ExportException(185"internal error: ObjID already in use");186} else if (implTable.containsKey(weakImpl)) {187throw new ExportException("object already exported");188}189190objTable.put(oe, target);191implTable.put(weakImpl, target);192193if (!target.isPermanent()) {194incrementKeepAliveCount();195}196}197}198}199200/**201* Remove target from object table.202*203* NOTE: This method must only be invoked while synchronized on204* the "tableLock" object, because it does not do so itself.205*/206private static void removeTarget(Target target) {207// assert Thread.holdsLock(tableLock);208209ObjectEndpoint oe = target.getObjectEndpoint();210WeakRef weakImpl = target.getWeakImpl();211212if (DGCImpl.dgcLog.isLoggable(Log.VERBOSE)) {213DGCImpl.dgcLog.log(Log.VERBOSE, "remove object " + oe);214}215216objTable.remove(oe);217implTable.remove(weakImpl);218219target.markRemoved(); // handles decrementing keep-alive count220}221222/**223* Process client VM signalling reference for given ObjID: forward to224* corresponding Target entry. If ObjID is not found in table,225* no action is taken.226*/227static void referenced(ObjID id, long sequenceNum, VMID vmid) {228synchronized (tableLock) {229ObjectEndpoint oe =230new ObjectEndpoint(id, Transport.currentTransport());231Target target = objTable.get(oe);232if (target != null) {233target.referenced(sequenceNum, vmid);234}235}236}237238/**239* Process client VM dropping reference for given ObjID: forward to240* corresponding Target entry. If ObjID is not found in table,241* no action is taken.242*/243static void unreferenced(ObjID id, long sequenceNum, VMID vmid,244boolean strong)245{246synchronized (tableLock) {247ObjectEndpoint oe =248new ObjectEndpoint(id, Transport.currentTransport());249Target target = objTable.get(oe);250if (target != null)251target.unreferenced(sequenceNum, vmid, strong);252}253}254255/**256* Increments the "keep-alive count".257*258* The "keep-alive count" is the number of non-permanent remote objects259* that are either in the object table or still have calls in progress.260* Therefore, this method should be invoked exactly once for every261* non-permanent remote object exported (a remote object must be262* exported before it can have any calls in progress).263*264* The VM is "kept alive" while the keep-alive count is greater than265* zero; this is accomplished by keeping a non-daemon thread running.266*267* Because non-permanent objects are those that can be garbage268* collected while exported, and thus those for which the "reaper"269* thread operates, the reaper thread also serves as the non-daemon270* VM keep-alive thread; a new reaper thread is created if necessary.271*/272@SuppressWarnings("removal")273static void incrementKeepAliveCount() {274synchronized (keepAliveLock) {275keepAliveCount++;276277if (reaper == null) {278reaper = AccessController.doPrivileged(279new NewThreadAction(new Reaper(), "Reaper", false));280reaper.start();281}282283/*284* While there are non-"permanent" objects in the object table,285* request a maximum latency for inspecting the entire heap286* from the local garbage collector, to place an upper bound287* on the time to discover remote objects that have become288* unreachable (and thus can be removed from the table).289*/290if (gcLatencyRequest == null) {291gcLatencyRequest = GC.requestLatency(gcInterval);292}293}294}295296/**297* Decrements the "keep-alive count".298*299* The "keep-alive count" is the number of non-permanent remote objects300* that are either in the object table or still have calls in progress.301* Therefore, this method should be invoked exactly once for every302* previously-exported non-permanent remote object that both has been303* removed from the object table and has no calls still in progress.304*305* If the keep-alive count is decremented to zero, then the current306* reaper thread is terminated to cease keeping the VM alive (and307* because there are no more non-permanent remote objects to reap).308*/309@SuppressWarnings("removal")310static void decrementKeepAliveCount() {311synchronized (keepAliveLock) {312keepAliveCount--;313314if (keepAliveCount == 0) {315if (!(reaper != null)) { throw new AssertionError(); }316AccessController.doPrivileged(new PrivilegedAction<Void>() {317public Void run() {318reaper.interrupt();319return null;320}321});322reaper = null;323324/*325* If there are no longer any non-permanent objects in the326* object table, we are no longer concerned with the latency327* of local garbage collection here.328*/329gcLatencyRequest.cancel();330gcLatencyRequest = null;331}332}333}334335/**336* The Reaper thread waits for notifications that weak references in the337* object table have been cleared. When it receives a notification, it338* removes the corresponding entry from the table.339*340* Since the Reaper is created as a non-daemon thread, it also serves341* to keep the VM from exiting while there are objects in the table342* (other than permanent entries that should neither be reaped nor343* keep the VM alive).344*/345private static class Reaper implements Runnable {346347public void run() {348try {349do {350// wait for next cleared weak reference351WeakRef weakImpl = (WeakRef) reapQueue.remove();352353synchronized (tableLock) {354Target target = implTable.get(weakImpl);355if (target != null) {356if (!target.isEmpty()) {357throw new Error(358"object with known references collected");359} else if (target.isPermanent()) {360throw new Error("permanent object collected");361}362removeTarget(target);363}364}365} while (!Thread.interrupted());366} catch (InterruptedException e) {367// pass away if interrupted368}369}370}371}372373374