Example usage for java.util.concurrent.atomic AtomicReference set

List of usage examples for java.util.concurrent.atomic AtomicReference set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference set.

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java

/**
 * Creates and opens a file with the specified path. If the parent folder
 * does not exist, we create it and mark it and its parent as hidden -- we
 * assume that file reside in $tf\10\ and we need to mark both $tf and 10 as
 * hidden. If filePath was not specified or its creation failed, and
 * createTempOnFailure=true we will create a new temporary file, using
 * tempUniqueString./*  w w  w  .  ja va  2 s .c o m*/
 *
 *
 * @param filePath
 *        in: the path to create the file at, out: the path actually created
 *        (possibly a temporary file in another directory) (must not be
 *        <code>null</code>)
 * @param createTempOnFailure
 * @param tempUniqueString
 * @param tempCreated
 * @return
 * @throws IOException
 */
public static FileOutputStream createFile(final AtomicReference<String> filePath,
        final boolean createTempOnFailure, final String tempUniqueString, final AtomicBoolean tempCreated)
        throws IOException {
    Check.notNull(filePath, "filePath"); //$NON-NLS-1$

    FileOutputStream localStream = null;
    tempCreated.set(false);

    Exception createException = null;
    if (filePath.get() != null && filePath.get().length() > 0) {
        try {
            localStream = new FileOutputStream(filePath.get());
        } catch (final Exception ex) {
            createException = ex;
            if (!createTempOnFailure) {
                throw new VersionControlException(ex);
            }
        }
    }
    if (localStream == null && createTempOnFailure) {
        tempCreated.set(true);

        final File tempFile = TempStorageService.getInstance().createTempFile();
        localStream = new FileOutputStream(tempFile);

        log.info(MessageFormat.format(
                "Could not create baseline folder collection file {0}, using temporary file {1}", //$NON-NLS-1$
                filePath.get(), tempFile), createException);

        filePath.set(tempFile.getAbsolutePath());
    } else {
        Check.notNullOrEmpty(filePath.get(), "filePath.get()"); //$NON-NLS-1$
    }

    return localStream;
}

From source file:org.apache.nifi.processors.kudu.AbstractKudu.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    try {//from  w  ww .j a v  a 2  s .  c o  m
        if (flowFile == null)
            return;
        final Map<String, String> attributes = new HashMap<String, String>();
        final AtomicReference<Throwable> exceptionHolder = new AtomicReference<>(null);
        final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER)
                .asControllerService(RecordReaderFactory.class);
        final KuduSession kuduSession = this.getKuduSession(kuduClient);

        session.read(flowFile, (final InputStream rawIn) -> {
            RecordReader recordReader = null;
            try (final BufferedInputStream in = new BufferedInputStream(rawIn)) {
                try {
                    recordReader = recordReaderFactory.createRecordReader(flowFile, in, getLogger());
                } catch (Exception ex) {
                    final RecordReaderFactoryException rrfe = new RecordReaderFactoryException(
                            "Unable to create RecordReader", ex);
                    exceptionHolder.set(rrfe);
                    return;
                }

                List<String> fieldNames = recordReader.getSchema().getFieldNames();
                final RecordSet recordSet = recordReader.createRecordSet();

                if (skipHeadLine)
                    recordSet.next();

                int numOfAddedRecord = 0;
                Record record = recordSet.next();
                while (record != null) {
                    org.apache.kudu.client.Operation oper = null;
                    if (operationType == OperationType.UPSERT) {
                        oper = upsertRecordToKudu(kuduTable, record, fieldNames);
                    } else {
                        oper = insertRecordToKudu(kuduTable, record, fieldNames);
                    }
                    kuduSession.apply(oper);
                    numOfAddedRecord++;
                    record = recordSet.next();
                }

                getLogger().info("KUDU: number of inserted records: " + numOfAddedRecord);
                attributes.put(RECORD_COUNT_ATTR, String.valueOf(numOfAddedRecord));

            } catch (KuduException ex) {
                getLogger().error("Exception occurred while interacting with Kudu due to " + ex.getMessage(),
                        ex);
                exceptionHolder.set(ex);
            } catch (Exception e) {
                exceptionHolder.set(e);
            } finally {
                IOUtils.closeQuietly(recordReader);
            }
        });
        kuduSession.close();
        if (exceptionHolder.get() != null) {
            throw exceptionHolder.get();
        }

        // Update flow file's attributes after the ingestion
        session.putAllAttributes(flowFile, attributes);

        session.transfer(flowFile, REL_SUCCESS);
        session.getProvenanceReporter().send(flowFile, "Successfully added flowfile to kudu");

    } catch (IOException | FlowFileAccessException e) {
        getLogger().error("Failed to write due to {}", new Object[] { e });
        session.transfer(flowFile, REL_FAILURE);
    } catch (Throwable t) {
        getLogger().error("Failed to write due to {}", new Object[] { t });
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:org.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
public void shouldAllowReferenceOfVertexIdOutsideOfOriginalThreadAuto() throws Exception {
    final Vertex v1 = graph.addVertex("name", "stephen");

    final AtomicReference<Object> id = new AtomicReference<>();
    final Thread t = new Thread(() -> id.set(v1.id()));
    t.start();/*from  w  w w .j a  va2s.co  m*/
    t.join();

    assertEquals(v1.id(), id.get());

    g.tx().rollback();
}

From source file:org.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
public void shouldAllowReferenceOfEdgeIdOutsideOfOriginalThreadAuto() throws Exception {
    final Vertex v1 = graph.addVertex();
    final Edge e = v1.addEdge("self", v1, "weight", 0.5d);

    final AtomicReference<Object> id = new AtomicReference<>();
    final Thread t = new Thread(() -> id.set(e.id()));
    t.start();// w ww.ja  va  2s .  c om
    t.join();

    assertEquals(e.id(), id.get());

    g.tx().rollback();
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java

@Test
public void testSafetyWithCrash() throws Exception {
    final int itemQty = 100;

    DistributedQueue<TestQueueItem> producerQueue = null;
    DistributedQueue<TestQueueItem> consumerQueue1 = null;
    DistributedQueue<TestQueueItem> consumerQueue2 = null;

    CuratorFramework producerClient = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    CuratorFramework consumerClient1 = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    CuratorFramework consumerClient2 = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {//w w  w  .  j a va  2 s. c o  m
        producerClient.start();
        consumerClient1.start();
        consumerClient2.start();

        ExecutorService service = Executors.newCachedThreadPool();

        // make the producer queue
        {
            producerQueue = QueueBuilder.builder(producerClient, null, serializer, QUEUE_PATH).buildQueue();
            producerQueue.start();
            QueueTestProducer producer = new QueueTestProducer(producerQueue, itemQty, 0);
            service.submit(producer);
        }

        final Set<TestQueueItem> takenItems = Sets.newTreeSet();
        final Set<TestQueueItem> takenItemsForConsumer1 = Sets.newTreeSet();
        final Set<TestQueueItem> takenItemsForConsumer2 = Sets.newTreeSet();
        final AtomicReference<TestQueueItem> thrownItemFromConsumer1 = new AtomicReference<TestQueueItem>(null);

        // make the first consumer queue
        {
            final QueueConsumer<TestQueueItem> ourQueue = new QueueConsumer<TestQueueItem>() {
                @Override
                public void consumeMessage(TestQueueItem message) throws Exception {
                    synchronized (takenItems) {
                        if (takenItems.size() > 10) {
                            thrownItemFromConsumer1.set(message);
                            throw new Exception("dummy"); // simulate a crash
                        }
                    }

                    addToTakenItems(message, takenItems, itemQty);
                    synchronized (takenItemsForConsumer1) {
                        takenItemsForConsumer1.add(message);
                    }

                    Thread.sleep((long) (Math.random() * 5));
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                }
            };
            consumerQueue1 = QueueBuilder.builder(consumerClient1, ourQueue, serializer, QUEUE_PATH)
                    .lockPath("/a/locks").buildQueue();
            consumerQueue1.start();
        }

        // make the second consumer queue
        {
            final QueueConsumer<TestQueueItem> ourQueue = new QueueConsumer<TestQueueItem>() {
                @Override
                public void consumeMessage(TestQueueItem message) throws Exception {
                    addToTakenItems(message, takenItems, itemQty);
                    synchronized (takenItemsForConsumer2) {
                        takenItemsForConsumer2.add(message);
                    }
                    Thread.sleep((long) (Math.random() * 5));
                }

                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                }
            };
            consumerQueue2 = QueueBuilder.builder(consumerClient2, ourQueue, serializer, QUEUE_PATH)
                    .lockPath("/a/locks").buildQueue();
            consumerQueue2.start();
        }

        synchronized (takenItems) {
            while (takenItems.size() < itemQty) {
                takenItems.wait(1000);
            }
        }

        int i = 0;
        for (TestQueueItem item : takenItems) {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }

        Assert.assertNotNull(thrownItemFromConsumer1.get());
        Assert.assertTrue((takenItemsForConsumer2.contains(thrownItemFromConsumer1.get())));
        Assert.assertTrue(Sets.intersection(takenItemsForConsumer1, takenItemsForConsumer2).size() == 0);
    } finally {
        IOUtils.closeQuietly(producerQueue);
        IOUtils.closeQuietly(consumerQueue1);
        IOUtils.closeQuietly(consumerQueue2);

        IOUtils.closeQuietly(producerClient);
        IOUtils.closeQuietly(consumerClient1);
        IOUtils.closeQuietly(consumerClient2);
    }
}

From source file:org.apache.openejb.activemq.JMS2AMQTest.java

@Test
public void receive() throws InterruptedException {
    final String text = TEXT + "2";
    final AtomicReference<Throwable> error = new AtomicReference<>();
    final CountDownLatch ready = new CountDownLatch(1);
    final CountDownLatch over = new CountDownLatch(1);
    new Thread() {
        @Override/* ww w .j  a va  2s. c  om*/
        public void run() {
            {
                setName(JMS2AMQTest.class.getName() + ".receive#receiver");
            }

            try (final JMSContext context = cf.createContext()) {
                try (final JMSConsumer consumer = context.createConsumer(destination2)) {
                    ready.countDown();
                    assertEquals(text, consumer.receiveBody(String.class, TimeUnit.MINUTES.toMillis(1)));
                }
            } catch (final Throwable ex) {
                error.set(ex);
            } finally {
                over.countDown();
            }
        }
    }.start();

    ready.await(1, TimeUnit.MINUTES);
    sleep(150); // just to ensure we called receive already

    // now send the message
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination2, text);
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }

    over.await(1, TimeUnit.MINUTES);

    // ensure we got the message and no exception
    final Throwable exception = error.get();
    if (exception != null) {
        exception.printStackTrace();
    }
    assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}

From source file:de.hybris.platform.jdbcwrapper.DataSourceFactoryTest.java

@Test
public void testPoolShutdownAfterError() {
    final Tenant t = Registry.getCurrentTenantNoFallback();
    final Map<String, String> params = new HashMap<String, String>(
            t.getMasterDataSource().getConnectionParameters());
    // make it fail on connect by messing up the user name
    params.put(SystemSpecificParams.DB_USERNAME, "FooDosntExist");

    final DataSourceFactory dataSourceFactory = t.getMasterDataSource().getDataSourceFactory();

    final AtomicReference<WeakReference<JDBCConnectionPool>> poolRef = new AtomicReference<WeakReference<JDBCConnectionPool>>();

    final DataSourceFactory f = new DataSourceFactory() {

        @Override/* w  w  w.  java 2  s  . c  o m*/
        public HybrisDataSource createJNDIDataSource(final String id, final Tenant tenant,
                final String jndiName, final boolean readOnly) {
            throw new UnsupportedOperationException();
        }

        @Override
        public HybrisDataSource createDataSource(final String id, final Tenant tenant,
                final Map<String, String> connectionParams, final boolean readOnly) {
            throw new UnsupportedOperationException();
        }

        @Override
        public JDBCConnectionPool createConnectionPool(final HybrisDataSource dataSource,
                final Config poolConfig) {
            final JDBCConnectionPool ret = dataSourceFactory.createConnectionPool(dataSource, poolConfig);
            poolRef.set(new WeakReference<JDBCConnectionPool>(ret));
            return ret;
        }

        @Override
        public Connection wrapConnection(final HybrisDataSource wrappedDataSource,
                final Connection rawConnection) {
            return dataSourceFactory.wrapConnection(wrappedDataSource, rawConnection);
        }

        @Override
        public Statement wrapStatement(final Connection wrappedConnection, final Statement rawStatement) {
            return dataSourceFactory.wrapStatement(wrappedConnection, rawStatement);
        }

        @Override
        public PreparedStatement wrapPreparedStatement(final Connection wrappedConnection,
                final PreparedStatement rawStatement, final String query) {
            return dataSourceFactory.wrapPreparedStatement(wrappedConnection, rawStatement, query);
        }

        @Override
        public ResultSet wrapResultSet(final Statement wrappedStatement, final ResultSet rawResultSet) {
            return dataSourceFactory.wrapResultSet(wrappedStatement, rawResultSet);
        }
    };

    HybrisDataSource ds = null;
    try {
        TestUtils.disableFileAnalyzer("DataSource creation should throw exception");
        ds = new DataSourceImpl(t, "DummyDS", params, false, f);
    } catch (final Exception e) {
        // fine so far - now check how the pool behaves
        assertPoolIsShutDown(poolRef.get(), 30);
    } finally {
        TestUtils.enableFileAnalyzer();
    }
    if (ds != null) {
        // in case data source creation did not fail as expected we must clean up for sure 
        ds.destroy();
        fail("data source creation was supposed to fail but did not");
    }
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

@Test
public void testTransactionCleanUpSimple()
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;/*from   ww w.j  ava2s  . c o m*/
    try {
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), 1);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = 1;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final CyclicBarrier gate = new CyclicBarrier(2);
        final AtomicReference<Throwable> threadError = new AtomicReference<Throwable>();
        final AtomicReference<RecordingTransaction> threadTransaction = new AtomicReference<ThreadPoolTest.RecordingTransaction>();
        final PoolableThread thread1 = pool.borrowThread();
        thread1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Transaction tx = new RecordingTransaction();
                    tx.activateAsCurrentTransaction();
                    tx.begin();
                    tx.begin(); // second time
                    tx.begin(); // third time
                    assertTrue(tx.isRunning());
                    assertEquals(3, tx.getOpenTransactionCount());
                    threadTransaction.set((RecordingTransaction) tx);
                    gate.await(10, TimeUnit.SECONDS);
                } catch (final Throwable t) {
                    threadError.set(t);
                }
            }
        });
        gate.await(10, TimeUnit.SECONDS);
        assertNull(threadError.get());
        // busy waiting for correct number of rollbacks - at the moment there is no hook for a better solution
        final RecordingTransaction tx = threadTransaction.get();
        final long maxWait = System.currentTimeMillis() + (15 * 1000);
        while (tx.rollbackCounter.get() < 3 && System.currentTimeMillis() < maxWait) {
            Thread.sleep(100);
        }
        assertEquals(3, tx.rollbackCounter.get());

        final PoolableThread thread2 = pool.borrowThread();
        assertNotSame(thread1, thread2);
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));
    }
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final String contentType, final Future<MessageSender> senderTracker,
        final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, contentType)) {
        HttpUtils.badRequest(ctx,/*from  ww  w  . j  a v  a 2s  .c  o  m*/
                String.format("Content-Type %s does not match with the payload", contentType));
    } else {
        final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL));
        if (contentType == null) {
            HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE));
        } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) {
            HttpUtils.badRequest(ctx, "Bad QoS Header Value");
        } else {

            final Device authenticatedDevice = getAuthenticatedDevice(ctx);
            final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                    authenticatedDevice);
            final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

            // AtomicBoolean to control if the downstream message was sent successfully
            final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false);
            // AtomicReference to a Handler to be called to close an open command receiver link.
            final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>();

            // Handler to be called with a received command. If the timer expired, null is provided as command.
            final Handler<Message> commandReceivedHandler = commandMessage -> {
                // reset the closeHandler reference, since it is not valid anymore at this time.
                closeLinkAndTimerHandlerRef.set(null);
                if (downstreamMessageSent.get()) {
                    // finish the request, since the response is now complete (command was added)
                    if (!ctx.response().closed()) {
                        ctx.response().end();
                    }
                }
            };

            CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {

                if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                    final MessageSender sender = senderTracker.result();
                    final Message downstreamMessage = newMessage(
                            ResourceIdentifier.from(endpointName, tenant, deviceId),
                            sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload,
                            tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx));
                    customizeDownstreamMessage(downstreamMessage, ctx);

                    // first open the command receiver link (if needed)
                    return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler)
                            .compose(closeLinkAndTimerHandler -> {
                                closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler);

                                if (qosHeader == null) {
                                    return sender.send(downstreamMessage);
                                } else {
                                    return sender.sendAndWaitForOutcome(downstreamMessage);
                                }
                            });
                } else {
                    // this adapter is not enabled for the tenant
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                }
            }).compose(delivery -> {
                LOG.trace(
                        "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName);
                metrics.incrementProcessedHttpMessages(endpointName, tenant);
                ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
                downstreamMessageSent.set(true);

                // if no command timer was created, the request now can be responded
                if (closeLinkAndTimerHandlerRef.get() == null) {
                    ctx.response().end();
                }

                return Future.succeededFuture();

            }).recover(t -> {

                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);

                cancelResponseTimer(closeLinkAndTimerHandlerRef);

                if (ClientErrorException.class.isInstance(t)) {
                    final ClientErrorException e = (ClientErrorException) t;
                    ctx.fail(e.getErrorCode());
                } else {
                    metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
                    HttpUtils.serviceUnavailable(ctx, 2);
                }
                return Future.failedFuture(t);
            });
        }
    }
}

From source file:com.github.anba.test262.environment.Environments.java

/**
 * Creates a new Rhino environment/*from   w  w  w  .j  a v  a2  s . c o m*/
 */
public static <T extends GlobalObject> EnvironmentProvider<T> rhino(final Configuration configuration) {
    final int version = configuration.getInt("rhino.version", Context.VERSION_DEFAULT);
    final String compiler = configuration.getString("rhino.compiler.default");
    List<?> enabledFeatures = configuration.getList("rhino.features.enabled", emptyList());
    List<?> disabledFeatures = configuration.getList("rhino.features.disabled", emptyList());
    final Set<Integer> enabled = intoCollection(filterMap(enabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());
    final Set<Integer> disabled = intoCollection(filterMap(disabledFeatures, notEmptyString, toInteger),
            new HashSet<Integer>());

    /**
     * Initializes the global {@link ContextFactory} according to the
     * supplied configuration
     * 
     * @see ContextFactory#initGlobal(ContextFactory)
     */
    final ContextFactory factory = new ContextFactory() {
        @Override
        protected boolean hasFeature(Context cx, int featureIndex) {
            if (enabled.contains(featureIndex)) {
                return true;
            } else if (disabled.contains(featureIndex)) {
                return false;
            }
            return super.hasFeature(cx, featureIndex);
        }

        @Override
        protected Context makeContext() {
            Context context = super.makeContext();
            context.setLanguageVersion(version);
            return context;
        }
    };

    EnvironmentProvider<RhinoGlobalObject> provider = new EnvironmentProvider<RhinoGlobalObject>() {
        @Override
        public RhinoEnv<RhinoGlobalObject> environment(final String testsuite, final String sourceName,
                final Test262Info info) {
            Configuration c = configuration.subset(testsuite);
            final boolean strictSupported = c.getBoolean("strict", false);
            final String encoding = c.getString("encoding", "UTF-8");
            final String libpath = c.getString("lib_path");

            final Context cx = factory.enterContext();
            final AtomicReference<RhinoGlobalObject> $global = new AtomicReference<>();

            final RhinoEnv<RhinoGlobalObject> environment = new RhinoEnv<RhinoGlobalObject>() {
                @Override
                public RhinoGlobalObject global() {
                    return $global.get();
                }

                @Override
                protected String getEvaluator() {
                    return compiler;
                }

                @Override
                protected String getCharsetName() {
                    return encoding;
                }

                @Override
                public void exit() {
                    Context.exit();
                }
            };

            @SuppressWarnings({ "serial" })
            final RhinoGlobalObject global = new RhinoGlobalObject() {
                {
                    cx.initStandardObjects(this, false);
                }

                @Override
                protected boolean isStrictSupported() {
                    return strictSupported;
                }

                @Override
                protected String getDescription() {
                    return info.getDescription();
                }

                @Override
                protected void failure(String message) {
                    failWith(message, sourceName);
                }

                @Override
                protected void include(Path path) throws IOException {
                    // resolve the input file against the library path
                    Path file = Paths.get(libpath).resolve(path);
                    InputStream source = Files.newInputStream(file);
                    environment.eval(file.getFileName().toString(), source);
                }
            };

            $global.set(global);

            return environment;
        }
    };

    @SuppressWarnings("unchecked")
    EnvironmentProvider<T> p = (EnvironmentProvider<T>) provider;

    return p;
}