java.lang.ThreadLocal.withInitial()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(8.8k)|赞(0)|评价(0)|浏览(295)

本文整理了Java中java.lang.ThreadLocal.withInitial()方法的一些代码示例,展示了ThreadLocal.withInitial()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ThreadLocal.withInitial()方法的具体详情如下:
包路径:java.lang.ThreadLocal
类名称:ThreadLocal
方法名:withInitial

ThreadLocal.withInitial介绍

暂无

代码示例

代码示例来源:origin: jdbi/jdbi

LazyHandleSupplier(Jdbi db, ConfigRegistry config) {
  this.db = db;
  this.config = ThreadLocal.withInitial(() -> config);
}

代码示例来源:origin: neo4j/neo4j

@Override
public void init( LongSupplier lastClosedTransactionIdSupplier )
{
  this.cursorContext = ThreadLocal.withInitial( () -> new TransactionVersionContext( lastClosedTransactionIdSupplier ) );
}

代码示例来源:origin: confluentinc/ksql

ThreadLocalCloseable(final Supplier<T> initialValueSupplier) {
 this.created = new LinkedList<>();
 this.closed = false;
 this.local = ThreadLocal.withInitial(
   () -> {
    synchronized (this) {
     if (closed) {
      throw new IllegalStateException("ThreadLocalCloseable has been closed");
     }
     created.add(initialValueSupplier.get());
     return created.get(created.size() - 1);
    }
   });
}

代码示例来源:origin: Netflix/zuul

@Inject
public EventLoopGroupMetrics(Registry registry)
{
  this.registry = registry;
  this.metricsForCurrentThread = ThreadLocal.withInitial(() ->
  {
    String name = nameForCurrentEventLoop();
    EventLoopMetrics metrics = new EventLoopMetrics(registry, name);
    byEventLoop.put(Thread.currentThread(), metrics);
    return metrics;
  });
}

代码示例来源:origin: apache/hive

private static synchronized MemoryManager getThreadLocalOrcLlapMemoryManager(final Configuration conf) {
 if (threadLocalOrcLlapMemoryManager == null) {
  threadLocalOrcLlapMemoryManager = ThreadLocal.withInitial(() -> new LlapAwareMemoryManager(conf));
 }
 return threadLocalOrcLlapMemoryManager.get();
}

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public void asHigherOrderFunctions() {
// BEGIN local_formatter
// One implementation
ThreadLocal<DateFormat> localFormatter
  = ThreadLocal.withInitial(() -> new SimpleDateFormat());

// Usage
DateFormat formatter = localFormatter.get();
// END local_formatter

// BEGIN local_thread_id
// Or...
AtomicInteger threadId = new AtomicInteger();
ThreadLocal<Integer> localId
  = ThreadLocal.withInitial(() -> threadId.getAndIncrement());

// Usage
int idForThisThread = localId.get();
// END local_thread_id
  }

代码示例来源:origin: jdbi/jdbi

/**
 * Loads the StringTemplateGroup from the given path on the classpath.
 *
 * @param classLoader the classloader from which to load the resource.
 * @param path the resource path on the classpath.
 * @return the loaded StringTemplateGroup.
 */
public static STGroup findStringTemplateGroup(ClassLoader classLoader, String path) {
  return CACHE.computeIfAbsent(path, p -> ThreadLocal.withInitial(() -> readStringTemplateGroup(classLoader, path))).get();
}

代码示例来源:origin: jdbi/jdbi

Handle(ConfigRegistry config,
    ConnectionCloser closer,
    TransactionHandler transactions,
    StatementBuilder statementBuilder,
    Connection connection) {
  this.closer = closer;
  this.transactions = transactions;
  this.connection = connection;
  this.config = ThreadLocal.withInitial(() -> config);
  this.extensionMethod = new ThreadLocal<>();
  this.statementBuilder = statementBuilder;
  this.forceEndTransactions = !transactions.isInTransaction(this);
}

代码示例来源:origin: neo4j/neo4j

ParallelNativeIndexPopulator( File baseIndexFile, IndexLayout<KEY,VALUE> layout, NativeIndexPopulatorPartSupplier<KEY,VALUE> partSupplier )
{
  this.layout = layout;
  this.threadLocalPopulators = ThreadLocal.withInitial( () -> newPartPopulator( baseIndexFile, partSupplier ) );
  this.completePopulator = partSupplier.part( baseIndexFile );
}

代码示例来源:origin: com.zaxxer/HikariCP

/**
* Construct a ConcurrentBag with the specified listener.
*
* @param listener the IBagStateListener to attach to this bag
*/
public ConcurrentBag(final IBagStateListener listener)
{
 this.listener = listener;
 this.weakThreadLocals = useWeakThreadLocals();
 this.handoffQueue = new SynchronousQueue<>(true);
 this.waiters = new AtomicInteger();
 this.sharedList = new CopyOnWriteArrayList<>();
 if (weakThreadLocals) {
   this.threadList = ThreadLocal.withInitial(() -> new ArrayList<>(16));
 }
 else {
   this.threadList = ThreadLocal.withInitial(() -> new FastList<>(IConcurrentBagEntry.class, 16));
 }
}

代码示例来源:origin: AxonFramework/AxonFramework

public EventCipher(Function<Event, Integer> keySelector, List<byte[]> secretKeys) {
  this.keySelector = keySelector;
  this.secretKeys = new SecretKeySpec[secretKeys.size()];
  for(int i = 0; i < this.secretKeys.length; i++) {
    byte[] key = secretKeys.get(i);
    if(key.length != 16 && key.length != 24) {
      throw new EventStoreClientException("AXONIQ-8001",
          String.format("secret key length should be 128, 196 or 258 bits but is %d bytes for key %d",
              key.length, i));
    }
    this.secretKeys[i] = new SecretKeySpec(key,"AES");
  }
  this.ivParameterSpec = new IvParameterSpec(new byte[16]); /* All-zero IV */
  this.magicNumber = MAGIC_NUMBER_STRING.getBytes(StandardCharsets.US_ASCII);
  this.encryptingCiphers = new ThreadLocal[this.secretKeys.length];
  for(int i = 0; i < this.secretKeys.length; i++) {
    final int keyIndex = i;
    this.encryptingCiphers[i] = ThreadLocal.withInitial(() -> initCipher(Cipher.ENCRYPT_MODE, keyIndex));
    this.encryptingCiphers[i].get(); // If we can't create the cipher, better to know it sooner than later
  }
  this.decryptingCiphers = new ThreadLocal[this.secretKeys.length];
  for(int i = 0; i < this.secretKeys.length; i++) {
    final int keyIndex = i;
    this.decryptingCiphers[i] = ThreadLocal.withInitial(() -> initCipher(Cipher.DECRYPT_MODE, keyIndex));
    this.decryptingCiphers[i].get(); // If we can't create the cipher, better to know it sooner than later
  }
  this.nonceGenerator = ThreadLocal.withInitial(SecureRandom::new);
}

代码示例来源:origin: wildfly/wildfly

SecurityDomain(Builder builder, final LinkedHashMap<String, RealmInfo> realmMap) {
  this.realmMap = realmMap;
  this.defaultRealmName = builder.defaultRealmName;
  this.preRealmPrincipalRewriter = builder.principalDecoder.andThen(builder.preRealmRewriter);
  this.realmMapper = builder.realmMapper;
  this.roleMapper = builder.roleMapper;
  this.permissionMapper = builder.permissionMapper;
  this.postRealmPrincipalRewriter = builder.postRealmRewriter;
  this.securityIdentityTransformer = builder.securityIdentityTransformer;
  this.trustedSecurityDomain = builder.trustedSecurityDomain;
  this.securityEventListener = builder.securityEventListener;
  final Map<String, RoleMapper> originalRoleMappers = builder.categoryRoleMappers;
  final Map<String, RoleMapper> copiedRoleMappers;
  if (originalRoleMappers.isEmpty()) {
    copiedRoleMappers = emptyMap();
  } else if (originalRoleMappers.size() == 1) {
    final Map.Entry<String, RoleMapper> entry = originalRoleMappers.entrySet().iterator().next();
    copiedRoleMappers = Collections.singletonMap(entry.getKey(), entry.getValue());
  } else {
    copiedRoleMappers = new LinkedHashMap<>(originalRoleMappers);
  }
  this.categoryRoleMappers = copiedRoleMappers;
  // todo configurable
  anonymousIdentity = Assert.assertNotNull(securityIdentityTransformer.apply(new SecurityIdentity(this, AnonymousPrincipal.getInstance(), EMPTY_REALM_INFO, AuthorizationIdentity.EMPTY, copiedRoleMappers, IdentityCredentials.NONE, IdentityCredentials.NONE)));
  currentSecurityIdentity = ThreadLocal.withInitial(() -> anonymousIdentity);
}

代码示例来源:origin: Netflix/zuul

@Inject
public EventLoopGroupMetrics(Registry registry)
{
  this.registry = registry;
  this.metricsForCurrentThread = ThreadLocal.withInitial(() ->
  {
    String name = nameForCurrentEventLoop();
    EventLoopMetrics metrics = new EventLoopMetrics(registry, name);
    byEventLoop.put(Thread.currentThread(), metrics);
    return metrics;
  });
}

代码示例来源:origin: linkedin/cruise-control

_acquiredClusterModelSemaphore = ThreadLocal.withInitial(() -> false);

代码示例来源:origin: apache/incubator-druid

final ThreadLocal<Function<String, String>> threadLocal = ThreadLocal.withInitial(
  () -> {
   final SimpleDateFormat parser = new SimpleDateFormat(timeFormat);

代码示例来源:origin: apache/incubator-druid

this.threadLocalGrouper = ThreadLocal.withInitial(() -> groupers.get(threadNumber.getAndIncrement()));

代码示例来源:origin: neo4j/neo4j

final DoubleLatch jobLatch = new DoubleLatch();
final DoubleLatch testLatch = new DoubleLatch();
final ThreadLocal<Boolean> hasRun = ThreadLocal.withInitial( () -> false );

代码示例来源:origin: hugegraph/hugegraph

public TinkerpopTransaction(Graph graph) {
  super(graph);
  this.refs = new AtomicInteger(0);
  this.opened = ThreadLocal.withInitial(() -> false);
  this.graphTransaction = ThreadLocal.withInitial(() -> null);
  this.schemaTransaction = ThreadLocal.withInitial(() -> null);
}

代码示例来源:origin: palantir/atlasdb

public ReentrantManagedConnectionSupplier(final ConnectionManager delegate) {
  this.delegate = Preconditions.checkNotNull(delegate);
  this.threadLocal = ThreadLocal.withInitial(() ->
      new ResourceSharer<Connection, SQLException>(ResourceTypes.CONNECTION) {
        @Override
        public Connection open() {
          return delegate.getConnectionUnchecked();
        }
      });
}

代码示例来源:origin: org.elasticsearch/elasticsearch

private static ThreadLocal<MessageDigest> createThreadLocalMessageDigest(String digest) {
  return ThreadLocal.withInitial(() -> {
    try {
      return MessageDigest.getInstance(digest);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException("unexpected exception creating MessageDigest instance for [" + digest + "]", e);
    }
  });
}

相关文章