RSS feed [root] /weblog /concurrency /java




login:

password:

title search:




 


Mon Sep 18 00:29:41 GMT 2023

concurrency



(google search) (amazon search)
second
download zip of files only

Wed Sep 06 13:46:21 GMT 2023 From /weblog/java/concurrency

Thread


An API to get the state of a thread, but someone say it is not reliable - http://java.sun.com[..]5.0/docs/api/java/lang/Thread.State.html http://java.silke-wingens.de/2011/03/13/threads-states/?lang=en

http://www.nabble.com[..]readed-programs-tf3627394.html#a10128844

Having said that, I have to note that using Thread#getState() is not
something you can absolutely rely on as the behavior isn't guaranteed
to be the same on all platforms. That is, it can be a useful tool for
debugging and test-driving but not ideal for regression (unit)
testing.

Overview of Java thread - http://java67.blogspot.hk[..]t-thread-and-javalangthread-in-java.html

Loom - https://webtide.com/do-looms-claims-stack-up-part-1/ https://webtide.com/do-looms-claims-stack-up-part-2/

How will we debug Loom applications? - https://www.reddit.com[..]drv/how_will_we_debug_loom_applications/

Question: Why exactly are fibers cheaper than platform threads? - https://www.reddit.com[..]ion_why_exactly_are_fibers_cheaper_than/

Handling Virtual Threads - https://dzone.com/articles/handling-virtual-threads

1. Avoid Synchronized Blocks/Methods
2. Avoid Thread Pools To Limit Resource Access
3. Reduce ThreadLocal Usage
https://dzone.com[..]o-avoid-when-switching-to-virtual-thread

Exploring the design of Java’s new virtual threads - https://blogs.oracle.com/javamagazine/post/java-virtual-threads

(google search) (amazon search)


Wed Mar 08 12:44:43 GMT 2023 From /weblog/java/concurrency

threadlocal


There is a little bit performance cost for threadlocal variable - http://software.intel.com[..]ost-of-accessing-thread-local-variables/

Look like a useful but less known API - http://crazybob.org/2006/07/hard-core-java-threadlocal.html

Forward up discussion - http://www.theserverside.com[..]d_id=41473&asrc=EM_NNL_406677&uid=703565 pointing out some problems of using this technique, include similar effect of GLOBLE , possible memory leak

Another discussion in higher level - http://blog.objectmentor.com[..]04/thread-local-a-convenient-abomination , Key is "An object is an abstraction of function. A thread is an abstraction of schedule" , you can read further conclusion at http://www.infoq.com/news/2007/09/confusing_uow_with_threads

Protential issue of using threadlocal, one is memory leak and the other is it is that local - http://blog.maxant.co.uk/pebble/2008/09/23/1222200780000.html http://www.javacodegeeks.com[..]hreading-stories-threadlocal-in-web.html
http://plumbr.eu[..]shoot-yourself-in-foot-with-threadlocals

The beauty of the design of threadlocal, how it prevent locking and memory leaking - http://plumbr.eu/blog/how-is-threadlocal-implemented

JEP 429: Extent-Local Variables to Promote Immutability in Java - https://www.infoq.com/news/2022/09/extent-local-variables-java/

An Introduction to Scoped Values in Java - https://foojay.io/today/an-introduction-to-scoped-values-in-java/

(google search) (amazon search)


Sat Mar 19 12:00:19 GMT 2022 From /weblog/java/concurrency

Interrupt


Just know that interrupt() call is just setting a flag, it have to be doing IO work (like database call), or in wait() status, before the thread can really be interrupted.

http://blogs.sun.com[..]winger?entry=swingworker_stop_that_train

Another nice explanation about interrupt, in summary:

What should we do when we call code that may cause an InterruptedException? Don't immediately yank out the batteries! Typically there are two answers to that question:
1) Rethrow the InterruptedException from your method. This is usually the easiest and best approach. It is used by the new java.util.concurrent.* package [ http://java.sun.com[..]util/concurrent/Semaphore.html#acquire() ], which explains why we are now constantly coming into contact with this exception.
2) Catch it, set interrupted status, return. If you are running in a loop that calls code which may cause the exception, you should set the status back to being interrupted. For example:
while (!Thread.currentThread().isInterrupted()) {
// do something
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
Remember the Law of the Sabotaged Doorbell - don't just ignore interruptions, manage them properly!

- http://www.javaspecialists.eu/archive/Issue146.html

Another blog explain about InterruptedException - http://www.nurkiewicz.com[..]terruptedexception-and-interrupting.html

http://ocpsoft.org[..]running-infinite-java-regular-expression

http://praveer09.github.io[..]derstanding-thread-interruption-in-java/

How to Stop a Java Thread Without Using Thread.stop()? - https://4comprehension.com[..]a-java-thread-without-using-thread-stop/

(google search) (amazon search)


Sat Feb 05 13:05:36 GMT 2022 From /weblog/java/concurrency

primitive


Benchmark for LongAddr - http://concurrencyfreaks.blogspot.hk[..]gspot.hk/2013/09/longadder-and-dclc.html

If there is a concern about wasting too many memory for Atomic* wrapper class, we may consider changed to use AtomicFieldUpdater to update primitive directly - http://normanmaurer.me[..]/Lesser-known-concurrent-classes-Part-1/

What exactly is 'tearing'? - https://www.reddit.com[..]comments/rsr8az/what_exactly_is_tearing/

(google search) (amazon search)


Wed Oct 06 06:16:36 GMT 2021 From /weblog/java/concurrency

Executor


Sample ResubmittingScheduledThreadPoolExecutor, the coding is nice! http://www.javaspecialists.eu/archive/Issue154.html

Implement thread pool properly - http://www.kimchy.org/juc-executorservice-gotcha/

RetryExecutor - http://nurkiewicz.blogspot.hk[..]/2013/07/asynchronous-retry-pattern.html

ScheduledThreadPoolExecutor corePoolSize=0 at JDK9 cause 100% CPU - https://josephmate.github.io[..]1-10-03-my-bug-used-up-100cpu-or-did-it/

(google search) (amazon search)



Sun Mar 29 10:15:44 GMT 2020 From /weblog/java/concurrency

collections


Even though

private List synchList = Collections.synchronizedList(new LinkedList());

is thread safe, serialize sync List is NOT thread safe for sure. The story is, if you only synchronized the collection, and if we try to get the iterator in concurrent access environment, it will throws currencymodificationexception .

For collection is small, may be making defensive copy http://www.javapractices.com/Topic15.cjp is good. Otherwise, in java5, there is concurrency collection.

reference:
http://jroller.com[..]ntry=collections_synchronizedlist_broken
http://jroller.com/page/ctarrington?entry=java_collections_trivia

Map operation, include use of FutureTask and putIfAbsent() method from ConcurrentMap. - http://www.javaspecialists.co.za/archive/newsletter.do?issue=125

Other then lterate through the elements, adding and removing elements can also be problem, this article document a few good cases about that - http://rayfd.wordpress.com[..]en-a-synchronized-class-isnt-threadsafe/

Samples of using Queue.drainTo() - http://binkley.blogspot.com[..]rforming-fixed-amounts-of-work-with.html

http://tech.puredanger.com/2009/02/28/java-7-transferqueue/

Overview of blockingqueue - http://tutorials.jenkov.com[..]/java-util-concurrent/blockingqueue.html

Simple benchmark - http://java-persistence-performance.blogspot.com[..]jvm-performance-part-iii-concurrent.html

Multi-thread behaviour - http://vanillajava.blogspot.com[..]hread-safety-issues-with-vector-and.html

java.util.concurrent.ConcurrentHashMap VS openhft.collections.SharedHashMap - http://openhft.blogspot.co.uk[..]autilconcurrentconcurrenthashmap-vs.html

Why are there so many concurrent queues implementations in Java? - https://vmlens.com/articles/cp/why_so_many_queues/

Why hashmap is not thread safe - https://www.pixelstech.net[..]a-HashMap-is-considered-as-thread-unsafe

(google search) (amazon search)


Tue Jan 28 10:48:00 GMT 2020 From /weblog/java/concurrency

tutorial


Another nice tutorial set of concurrency framework - http://www.javacodegeeks.com/search/label/Concurrency

Java concurrency, Building and testing concurrent applications for the Java platform - http://www.ibm.com[..]/training/kp/j-kp-concurrency/index.html

JVM concurrency: Java and Scala concurrency basics - http://www.ibm.com[..]/java/library/j-jvmc1/index.html?ca=drs-

http://javarevisited.blogspot.com.au[..]reading-interview-questions-answers.html

5 things you didn't know about ... Multithreaded Java programming - https://www.ibm.com/developerworks/library/j-5things15

266Threading Questions in Job Interviews (2/2) - https://www.javaspecialists.eu/archive/Issue266.html

Parallel Collection Processing: Without Parallel Streams - https://4comprehension.com/parallel-collection-processing-1/

(google search) (amazon search)


Sat Mar 09 15:33:41 GMT 2019 From /weblog/java/concurrency

framework


https://dzone.com[..]ye-view-on-java-concurrency-frameworks-1

(google search) (amazon search)


Thu Sep 28 08:21:47 GMT 2017 From /weblog/java/concurrency

Contended


preventing false sharing with the @Contended annotation - https://dzone.com[..]false-sharing-is-and-how-jvm-prevents-it

(google search) (amazon search)


Fri Mar 10 09:49:16 GMT 2017 From /weblog/java/concurrency

Map


putall can cause ConcurrentModifcationException - http://cr.openjdk.java.net[..]ses/sun/management/Agent.java.sdiff.html

Note on writing CopyOnWrite wrapper - http://flyingspaniel.blogspot.com[..]ot.com/2010/12/copyonwrite-wrappers.html

Sometime this is a bit difficult for Chinese to be a good programmer, recently some colleague and me discuss about the behaviour of this class and look like we have difficult understanding

A: ConcurrentHashMap support for locking as this is thread-safe
B: ConcurrentHashMap is thread safe for read but not for write because there is no lock, we still need to have external lock to keep it thread safe. By the way, I get ConcurrentModificationException from this before.
C: ConcurrentHashMap don't support for locking but they still thread safe for all operations, which is how "This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details." mentioned.

Too good that we can actually take a look at the source code to see what going on nowadays rather than just guessing - http://www.google.com[..]HashMap&sourceid=opera&ie=utf-8&oe=utf-8 By the way, this constructor is useful for a lot of concurrency access but actually not many developer notice about this - http://java.sun.com[..]rrentHashMap.html#ConcurrentHashMap(int, float, int)

Lazy initialization of map values - http://artisans-serverintellect-com.si-eioswww6.com[..]ect-com.si-eioswww6.com/default.asp?W122

HashMap.get() can cause infinite loop - http://lightbody.net[..]5/07/hashmapget_can_cause_an_infini.html

Discussing the effect of initCapacity() of HashMap in Java - http://saloon.javaranch.com[..]ltimatebb.cgi?ubb=get_topic&f=1&t=021171

OpenJDK and HashMap …. Safely Teaching an Old Dog New (Off-Heap!) Tricks - http://www.infoq.com/articles/Open-JDK-and-HashMap-Off-Heap

We can run search in ConcurrenctHashMap - https://dzone.com/articles/concurrenthashmap-in-java8

(google search) (amazon search)


Tue Jan 03 01:45:40 GMT 2017 From /weblog/java/concurrency

synchronisers


Similar to Barrier - http://tech.puredanger.com/2008/07/08/java7-phasers/

An example, show how to coordinate producer and consumer with Phaser - http://javaforu.blogspot.com[..]08/java-7s-jucphaser-short-tutorial.html

When to use CountDownLatch, Semaphore, CyclicBarrier, Exchanger and Phaser - https://codurance.com/2016/08/24/the-java-synchronisers/

(google search) (amazon search)


Thu Oct 06 15:58:24 GMT 2016 From /weblog/java/concurrency

Lock


ReentrantReadWriteLock - http://www-128.ibm.com[..]loperworks/library/j-jtp10264/index.html

why it suppose to be faster than VM level lock - http://osdir.com[..]sr.166-concurrency/2005-02/msg00031.html and a test about it - http://mechanical-sympathy.blogspot.gr[..]r/2011/11/java-lock-implementations.html

Samples of how to use it, and how to write test cases about it - http://www.javaspecialists.eu/archive/Issue152.html

Some useful VM parameter to tune the locks: -XX:+EliminateLocks , -XX:+DoEscapeAnalysis , -XX:+UseBiasedLocking - http://work.tinou.com[..]locking-escape-analysis-for-dummies.html

Discuss about 3 difference lock for Java, bias, thin and fat - http://www.javacodegeeks.com/2011/05/how-jvm-handle-locks.html

Why using the read lock will make lock detector fail - http://javaeesupportpatterns.blogspot.com.au[..]concurrency-hidden-thread-deadlocks.html

Basic of synchronization and locking - http://www.takipiblog.com[..]about-synchronization-in-java-and-scala/

Better semaphore with striped api - http://codingjunkie.net/striped-concurrency/

Comparing and discuss difference locking approach - http://www.javaspecialists.eu/archive/Issue215.html

Compare performance behavior of RWLock, StampedLock and Optimistic lock - http://www.takipiblog.com[..]ocks-vs-readwritelocks-and-synchronized/

Comparing sync and lock - http://www.rationaljava.com[..]ase-study-in-analysing-latency-lock.html

http://vmlens.com/articles/reentrant-lock-cheat-sheet/

(google search) (amazon search)


Tue Jul 05 08:29:21 GMT 2016 From /weblog/java/concurrency

race


http://vmlens.com[..]-or-how-to-find-an-irreproducable-bug-2/
http://vmlens.com[..]-java-race-conditions-with-tests-part-2/

(google search) (amazon search)



Wed Mar 26 03:10:08 GMT 2014 From /weblog/java/concurrency

Reference


How weak and soft reference work http://www.javaspecialists.co.za/archive/Issue098.html http://javarevisited.blogspot.com.au[..]rence-phantom-strong-reference-java.html

Issue about weakhashmap - http://blogs.azulsystems.com/cliff/2007/08/why-weakhashmap.html

When soft reference clean? - http://jeremymanson.blogspot.com[..]/07/how-hotspot-decides-to-clear_07.html

(google search) (amazon search)


Mon Dec 23 10:09:08 GMT 2013 From /weblog/java/concurrency

pool


Demo how java 1.5 built-in thread pool work: http://blogs.sun.com[..]ry=swingworker_throttling_and_monitoring

Sample of thread pool - http://www.javaworld.com/javaworld/jw-01-2005/jw-0124-pool_p.html

Discussion about how to estimate threadpool size - http://www.infoq.com/articles/Java-Thread-Pool-Performance-Tuning

(google search) (amazon search)


Tue Oct 22 09:25:00 GMT 2013 From /weblog/java/concurrency

Double-Checked Locking


Very detailed explanation: http://www.cs.umd.edu[..]va/memoryModel/DoubleCheckedLocking.html

Some more information, also demo in fact not much difference for most cast: http://blogs.sun.com[..]page/cwebster?entry=double_check_locking

Even more discussion - http://www-128.ibm.com/developerworks/java/library/j-dcl.html

In Chinese - http://www.infoq.com[..]hecked-locking-with-delay-initialization

(google search) (amazon search)


Mon Sep 23 10:11:40 GMT 2013 From /weblog/java/concurrency

testing


Series of blog showing how to use JMock API to help testing MT code - http://www.google.com[..]shhtresohqc&ie=UTF-8&q=JMock+and+Threads

A test for deadlock - http://cr.openjdk.java.net[..]notationTypeDeadlockTest.java.sdiff.html http://cr.openjdk.java.net[..]t/java/util/logging/Bug8010939.java.html

Some technique, use of SynchronousExecutorService and Events - http://alexecollins.com[..]ntent/5-tips-unit-testing-threaded-code/

(google search) (amazon search)


Thu Jun 07 16:56:58 GMT 2012 From /weblog/java/concurrency

Actor


Collections from IBM - http://www.ibm.com[..]rworks/training/kp/j-kp-actorconcurrency

(google search) (amazon search)


Sat Nov 12 18:37:44 GMT 2011 From /weblog/java/concurrency

Join


Example of Join - http://cnapagoda.blogspot.com/2010/01/thread-join-method.html

(google search) (amazon search)


Sun Sep 25 01:35:12 GMT 2011 From /weblog/java/concurrency

yield


Yield is not that reliable- http://www.azulsystems.com[..]-pair-of-somebody-elses-concurrency-bugs

(google search) (amazon search)


Sun Aug 28 11:58:48 GMT 2011 From /weblog/java/concurrency

monitoring


Sample code of try-sync


import sun.misc.*;

import java.lang.reflect.*;

public class MonitorUtils {
private static Unsafe unsafe = getUnsafe();

public static boolean trySynchronize(Object monitor) {
return unsafe.tryMonitorEnter(monitor);
}

public static void unsynchronize(Object monitor) {
unsafe.monitorExit(monitor);
}

private static Unsafe getUnsafe() {
try {
for (Field field : Unsafe.class.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
if (field.getType() == Unsafe.class) {
field.setAccessible(true);
return (Unsafe) field.get(null);
}
}
}
throw new IllegalStateException("Unsafe field not found");
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize unsafe", e);
}
}
}


http://www.javaspecialists.eu/archive/Issue194.html

(google search) (amazon search)


Sun Jun 26 16:27:08 GMT 2011 From /weblog/java/concurrency

hint


A nice list of hints about concurrency in java - http://www.weiqigao.com[..]c_burke_java_concurrency_by_example.html

Testing about java parallel processing - http://embarcaderos.net[..]ng-and-multi-core-utilization-with-java/

Some concurrency basic information - http://blog.andrewhubbs.com/?p=107

Tutorial of concurrency package - http://tutorials.jenkov.com/java-util-concurrent/index.html

Using Latch with Executor - http://binkley.blogspot.com[..]06/new-shimmer-for-java-concurrency.html

(google search) (amazon search)


Tue Feb 15 17:16:05 GMT 2011 From /weblog/java/concurrency

AnonymousInnerClass


Here is an tricky concurrency concern in Java when using Anonymous Inner Class with ExecutorService, if you use collection from outside class, that collection actually a global variable in the Inner Class, and need to take care the issues happened in concurrency access.

For this class:

public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new Runnable() {
@Override
public void run() {
list.add(new String());
}
});
es.shutdown();
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
break;
}
}
for (String string : list) {
if (string == null)
System.out.println("Have null");
}
}

actually same as

private static final class RunnableImpl implements Runnable {
private final List mList;
private RunnableImpl(List list) {
mList = list;
}

@Override
public void run() {
mList.add(new String());
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new RunnableImpl(list));
/** @formatter:on */
es.shutdown();
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
break;
}
}
for (String string : list) {
if (string == null)
System.out.println("Have null");
}
}


(google search) (amazon search)