Example usage for java.lang.ref WeakReference WeakReference

List of usage examples for java.lang.ref WeakReference WeakReference

Introduction

In this page you can find the example usage for java.lang.ref WeakReference WeakReference.

Prototype

public WeakReference(T referent) 

Source Link

Document

Creates a new weak reference that refers to the given object.

Usage

From source file:de.uniba.wiai.kinf.pw.projects.lillytab.reasoner.tbox.RBox.java

@Override
public synchronized IRBox<I, L, K, R> getImmutable() {
    IRBox<I, L, K, R> immutable = null;
    if (_immutable != null) {
        immutable = _immutable.get();//from   w ww  . j av a  2  s . com
    }
    if (immutable == null) {
        immutable = new ImmutableRBox<>(getTBox().getImmutable(), this);
        _immutable = new WeakReference<>(immutable);
    }
    return immutable;
}

From source file:br.com.anteros.social.facebook.AnterosFacebookSession.java

public void setOnLogoutListener(OnLogoutListener onLogoutListener) {
    this.onLogoutListener = new WeakReference<OnLogoutListener>(onLogoutListener);
}

From source file:cc.osint.graphd.server.GraphServerHandler.java

public String executeRequest(Channel responseChannel, String clientId,
        ConcurrentHashMap<String, String> clientState, String request) throws Exception {
    StringBuffer rsb = new StringBuffer();
    String cmd;//ww w. j av  a 2s.  c  o m
    String[] args;

    if (request.indexOf(GraphServerProtocol.SPACE) != -1) {
        cmd = request.substring(0, request.indexOf(GraphServerProtocol.SPACE)).trim().toLowerCase();
        args = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim()
                .split(GraphServerProtocol.SPACE);
    } else {
        cmd = request.trim().toLowerCase();
        args = new String[0];
    }

    // USE GRAPH: use <graphName>
    if (cmd.equals(GraphServerProtocol.CMD_USE)) {
        if (null == nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_NOT_EXIST");
        } else {
            if (null != clientState.get(ST_DB))
                clientState.remove(ST_DB);
            clientState.put(ST_DB, args[0]);
            rsb.append(GraphServerProtocol.R_OK);
        }

        // CREATE GRAPH: create <graphName>
    } else if (cmd.equals(GraphServerProtocol.CMD_CREATE)) {
        if (null != nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_ALREADY_EXISTS");
        } else {
            Graph newGraph = new Graph(args[0]);
            nameGraphMap.put(args[0], newGraph);
            WeakReference<Graph> graphRef = new WeakReference<Graph>(newGraph);
            GraphCommandExecutor graphCommandExecutor = new GraphCommandExecutor(args[0], graphRef);
            graphCommandExecutorService.execute(graphCommandExecutor);
            graphCommandExecutorMap.put(args[0], graphCommandExecutor);

            rsb.append(GraphServerProtocol.R_OK);
        }

        // DROP GRAPH: drop <graphName>
    } else if (cmd.equals(GraphServerProtocol.CMD_DROP)) {
        if (null == nameGraphMap.get(args[0])) {
            rsb.append(GraphServerProtocol.R_ERR);
            rsb.append(" DB_NOT_EXIST");
        } else {
            nameGraphMap.remove(args[0]);
            graphCommandExecutorMap.remove(args[0]);
            // TODO: DROP <KEY>
            // TODO: KILL graphCommandExecutor (via poisonPill message)
            rsb.append(GraphServerProtocol.R_OK);
        }

        // NAME THIS CONNECTION: namecon <name>
    } else if (cmd.equals(GraphServerProtocol.CMD_NAMECON)) {
        clientState.put(ST_NAMECON, args[0] + "-" + clientId);
        rsb.append(clientState.get(ST_NAMECON));
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // DUMP CLIENT STATE: clstate
    } else if (cmd.equals(GraphServerProtocol.CMD_CLSTATE)) {
        JSONObject result = new JSONObject(clientState);
        rsb.append(result.toString());
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // SERVER STATUS: sstat
    } else if (cmd.equals(GraphServerProtocol.CMD_SSTAT)) {
        JSONObject result = new JSONObject();
        JSONObject names = new JSONObject();
        names.put("TYPE_FIELD", Graph.TYPE_FIELD);
        names.put("KEY_FIELD", Graph.KEY_FIELD);
        names.put("WEIGHT_FIELD", Graph.WEIGHT_FIELD);
        names.put("EDGE_SOURCE_FIELD", Graph.EDGE_SOURCE_FIELD);
        names.put("EDGE_TARGET_FIELD", Graph.EDGE_TARGET_FIELD);
        names.put("RELATION_FIELD", Graph.RELATION_FIELD);
        names.put("VERTEX_TYPE", Graph.VERTEX_TYPE);
        names.put("EDGE_TYPE", Graph.EDGE_TYPE);
        result.put("names", names);

        rsb.append(result.toString());
        rsb.append(GraphServerProtocol.NL);
        rsb.append(GraphServerProtocol.R_OK);

        // LIST NAMED GRAPHS
    } else if (cmd.equals(GraphServerProtocol.CMD_LISTG)) {
        for (String name : nameGraphMap.keySet()) {
            rsb.append(name);
            rsb.append(GraphServerProtocol.NL);
        }
        rsb.append(GraphServerProtocol.R_OK);

        // GRAPH STATUS: gstat <name>
    } else if (cmd.equals(GraphServerProtocol.CMD_GSTAT)) {
        Graph gr0 = nameGraphMap.get(args[0]);
        if (null == gr0) {
            rsb.append(GraphServerProtocol.R_NOT_EXIST);
        } else {
            JSONObject result = new JSONObject();
            result.put("vertex_count", gr0.numVertices());
            result.put("edge_count", gr0.numEdges());
            rsb.append(result.toString());
            rsb.append(GraphServerProtocol.NL);
            rsb.append(GraphServerProtocol.R_OK);
        }

    } else {

        //
        // graph-specific operations
        //

        WeakReference<InboundChannelProcess> inboundChannelProcessRef = inboundChannelMap.get(clientId);

        //
        // async override handler
        // 

        if (cmd.startsWith("&")) {
            cmd = cmd.substring(1);
            request = request.substring(1);
            responseChannel.write(graphCommandExecutorMap.get(clientState.get(GraphServerHandler.ST_DB))
                    .execute(responseChannel, clientId, clientState, inboundChannelProcessRef.get(), request,
                            cmd, args)
                    + GraphServerProtocol.NL);
        } else {

            //
            // graph-specific, queue-driven ordered operations
            //

            GraphCommand graphCommand = new GraphCommand();
            graphCommand.responseChannel = responseChannel;
            graphCommand.clientId = clientId;
            graphCommand.clientState = clientState;
            graphCommand.inboundChannelProcess = inboundChannelProcessRef.get();
            graphCommand.request = request;
            graphCommand.cmd = cmd;
            graphCommand.args = args;
            graphCommand.poisonPill = false;

            graphCommandExecutorMap.get(clientState.get(GraphServerHandler.ST_DB)).queue(graphCommand);
        }

        // a null return value indicates it's been queued for execution
        // by the appropriate GraphCommandExecutor
        return null;
    }

    // unknown request
    if (rsb.toString().equals("")) {
        log.info("GraphServerProtocol.R_UNK: " + cmd);
        rsb.append(GraphServerProtocol.R_UNK);
        rsb.append(GraphServerProtocol.SPACE);
        rsb.append(cmd);
    }
    rsb.append(GraphServerProtocol.NL);
    return rsb.toString();
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

public Bitmap getPreview(final Object o) {
    final String name = getObjectName(o);
    final String packageName = getObjectPackage(o);
    // check if the package is valid
    synchronized (sInvalidPackages) {
        boolean packageValid = !sInvalidPackages.contains(packageName);
        if (!packageValid) {
            return null;
        }/*from   w w  w . ja  va 2s.  c  o  m*/
    }
    synchronized (mLoadedPreviews) {
        // check if it exists in our existing cache
        if (mLoadedPreviews.containsKey(name)) {
            WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
            Bitmap bitmap = bitmapReference.get();
            if (bitmap != null) {
                return bitmap;
            }
        }
    }

    Bitmap unusedBitmap = null;
    synchronized (mUnusedBitmaps) {
        // not in cache; we need to load it from the db
        while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
            Bitmap candidate = mUnusedBitmaps.remove(0).get();
            if (candidate != null && candidate.isMutable() && candidate.getWidth() == mPreviewBitmapWidth
                    && candidate.getHeight() == mPreviewBitmapHeight) {
                unusedBitmap = candidate;
            }
        }
        if (unusedBitmap != null) {
            final Canvas c = mCachedAppWidgetPreviewCanvas.get();
            c.setBitmap(unusedBitmap);
            c.drawColor(0, PorterDuff.Mode.CLEAR);
            c.setBitmap(null);
        }
    }

    if (unusedBitmap == null) {
        unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight, Bitmap.Config.ARGB_8888);
    }
    Bitmap preview = readFromDb(name, unusedBitmap);

    if (preview != null) {
        synchronized (mLoadedPreviews) {
            mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
        }
        return preview;
    } else {
        // it's not in the db... we need to generate it
        final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
        preview = generatedPreview;
        if (preview != unusedBitmap) {
            throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
        }

        synchronized (mLoadedPreviews) {
            mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
        }

        // write to db on a thread pool... this can be done lazily and improves the performance
        // of the first time widget previews are loaded
        new AsyncTask<Void, Void, Void>() {
            public Void doInBackground(Void... args) {
                writeToDb(o, generatedPreview);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);

        return preview;
    }
}

From source file:io.adeptj.runtime.server.Server.java

/**
 * Bootstrap Undertow Server and OSGi Framework.
 *//*from   ww w . j  a  v a2s . co  m*/
@Override
public void start() {
    this.cfgReference = new WeakReference<>(Configs.of().undertow());
    Config httpConf = Objects.requireNonNull(this.cfgReference.get()).getConfig(KEY_HTTP);
    int httpPort = this.handlePortAvailability(httpConf);
    LOGGER.info("Starting AdeptJ Runtime @port: [{}]", httpPort);
    this.printBanner();
    this.deploymentManager = Servlets.defaultContainer().addDeployment(this.deploymentInfo());
    this.deploymentManager.deploy();
    try {
        this.rootHandler = this.rootHandler(this.deploymentManager.start());
        this.undertow = this
                .enableAJP(this.enableHttp2(ServerOptions.build(this.workerOptions(Undertow.builder()),
                        Objects.requireNonNull(this.cfgReference.get()))))
                .addHttpListener(httpPort, httpConf.getString(KEY_HOST)).setHandler(this.rootHandler).build();
        this.undertow.start();
    } catch (ServletException ex) {
        throw new InitializationException(ex.getMessage(), ex);
    }
    if (!Environment.isServerConfFileExists()) {
        this.createServerConfFile();
    }
}

From source file:com.digium.respokesdk.RespokeCall.java

/**
 *  Set a receiver for the Listener interface
 *
 *  @param listener  The new receiver for events from the Listener interface for this call instance
 *//*from   www .j  a v  a 2  s .  c o  m*/
public void setListener(Listener listener) {
    listenerReference = new WeakReference<Listener>(listener);
}

From source file:com.digium.respokesdk.RespokeSignalingChannel.java

public RespokeSignalingChannel(String token, Listener newListener, String baseURL, Context context) {
    appToken = token;//from   w  ww  . ja v  a 2 s . c  om
    this.baseURL = baseURL;
    listenerReference = new WeakReference<Listener>(newListener);
    appContext = context;
    workerThread = new RespokeWorkerThread("RespokeWorkerThread");
    workerThread.start();
    workerThread.prepareHandler();
}

From source file:com.dpbymqn.fsm.manager.FsmManager.java

private void onDecision(final Method m, final OnDecision a, Class<? extends StatefulObject> stObjectClz,
        Class<? extends StateListener> clzLst, StateListener sl, StatefulObject st) {
    if (!testDeclaredAndActualClassConformity(m, a.smClass(), st, sl, stObjectClz, clzLst)) {
        return;//from w w w  .  j  a  v a2s . c  o m
    }
    final Class<? extends StatefulObject> stcls = StatefulObject.class.equals(a.smClass()) ? stObjectClz
            : a.smClass();
    final String prev = StringUtils.isEmpty(a.prev()) ? null : a.prev();
    final String next = StringUtils.isEmpty(a.next()) ? null : a.next();
    final WeakReference<StateListener> slRef = new WeakReference<StateListener>(sl);
    if (String.class.equals(m.getReturnType())) {
        if (m.getParameterTypes() != null) {
            switch (m.getParameterTypes().length) {
            case 1:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return null;
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    fromState);
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return null;
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm);
                        }
                    });

                }
                break;
            case 2:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return null;
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {

                        return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), sm,
                                fromState);
                    }
                });
                break;
            }
        } else {
            regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                @Override
                public Boolean query(StatefulObject sm, String fromState, String toState) {
                    return null;
                }

                @Override
                public String query(StatefulObject sm, String fromState) {
                    return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get());
                }
            });
        }
    } else if (Boolean.class.equals(m.getReturnType()) || boolean.class.equals(m.getReturnType())) {

        if (m.getParameterTypes() != null) {
            switch (m.getParameterTypes().length) {
            case 1:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    toState);
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm);
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                }
                break;
            case 2:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    fromState, toState);

                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm, toState);

                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                }
                break;
            case 3:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), sm,
                                fromState, toState);
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {
                        return null;
                    }
                });
                break;
            default:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get());
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {
                        return null;
                    }
                });
            }
        }
    }
}

From source file:com.sworddance.taskcontrol.FutureListenerProcessor.java

/**
 * Sets the future being monitor for being set to #future
 * @param future//www  .j a  v a2s .  c o m
 */
private <P extends Future<MV>> void setMonitoredFuture(P future) {
    if (this.monitoredFuture == null) {
        this.monitoredFuture = new WeakReference<P>(future);
    }
}

From source file:com.digium.respokesdk.RespokeClient.java

/**
 *  Set a receiver for the ResolvePresenceListener interface
 *
 *  @param listener  The new receiver for events from the ResolvePresenceListener interface for this client instance
 *//*ww  w .j a  v a2s .  c o m*/
public void setResolvePresenceListener(ResolvePresenceListener listener) {
    resolveListenerReference = new WeakReference<ResolvePresenceListener>(listener);
}