Showing posts with label multithread. Show all posts
Showing posts with label multithread. Show all posts

Wednesday, March 28, 2012

Lock and condition java 5 concurrent api


old way:
use synchronized keyword

Object monitorObject;

synchronized(monitorObject){
//critical section
}

new way: use Lock.lock() and Lock.unlock()
Lock lockObject;

try{
lockObject.lock();
}
finally{
lockObject.unlock();
}

----

old way: use wait() and notify() in the critical section

//insdie your critical section

boolean somecondition;
while(somecondition){
wait();
}

boolean someOtherCondition;
if(someOtherCondition){
notify();
}

new way: use await() and signal() on condition variables

Condition conditionVariable = lockObject.newCondition();

boolean somecondition;
while(somecondition){
conitionVariable.await();
}

boolean someothercondition;
if(someOtherCondition){
conditionVariable.signal();
}

Wednesday, February 8, 2012

线程之间怎么通讯?什么是critical section/semaphore/mutax,区别?

线程之间怎么通讯?什么是critical section/semaphore/mutax,区别?
网上找到这么一段话,

how do 2 threads communicate?

Basically via memory i.e. member fields of a class. Any thread can write into a single field and let any other thread read its value.
But if you need to make sure that any value written into the field will also be found/read by another thread, you need to put the statements accessing your communication field into blocks

synchronized( lockObj ){ commField= ...; }

The lockObj is a central object (also called semaphore or mutex - for mutual exclusion ) you should choose carefully so that it can be accessed from all your classes and very early: think of an instance of java.lang.Class : that's a foolproof singleton.

I want to discourage you from using the "fast and easy" synchronized qualifier for methods. This way you end up with a mess of Locks and creating deadlocks!

what is critical section

In concurrent programming a critical section is a piece of code that accesses a shared resource (data structure or device) that must not be concurrently accessed by more than one thread of execution. A critical section will usually terminate in fixed time, and a thread, task or process will have to wait a fixed time to enter it (aka bounded waiting). Some synchronization mechanism is required at the entry and exit of the critical section to ensure exclusive use.

--
what is semaphore

In computer science, a semaphore is a variable or abstract data type that provides a simple but useful abstraction for controlling access by multiple processes to a common resource in a parallel programming environment.

--
A mutex is essentially the same thing as a binary semaphore, and sometimes uses the same basic implementation. However, the term "mutex" is used to describe a construct which prevents two processes from executing the same piece of code, or accessing the same data, at the same time. The term "binary semaphore" is used to describe a construct which limits access to a single resource.

In many cases a mutex has a concept of an "owner": the process which locked the mutex is the only process allowed to unlock it. In contrast, semaphores generally do not have this restriction, something the producer-consumer example above depends upon.

Thursday, February 2, 2012

Semaphores in JDK 1.5

http://www.developerfusion.com/article/84294/semaphores-in-jdk-15/

very good article about threads and semaphore, easy to understand

Tuesday, January 31, 2012

Concurrency Utilities in JDK 1.5 (Tiger)

http://www.cs.umd.edu/class/spring2006/cmsc433/lectures/util-concurrent.pdf

a slide summarizing concurrency changes in java 1.5

w classes and enhancements

Executors, Thread Pools, and Futures
• Concurrent collections: Queues, Blocking
Queues, ConcurrentHashMap
• Locks and Conditions
• Synchronizers: Semaphores, Barriers, etc.
• Atomic Variables
Low-level compare-and-set operation
• Other enhancements
Nanosecond-granularity timing


------------------
class WebServer {
Executor pool =
Executors.newFixedThreadPool(7);
public static void main(String[] args) {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable r = new Runnable() {
public void run() {
handleRequest(connection);
}
};
pool.execute(r);
}
}


Saturday, January 28, 2012

Double-checked locking

http://en.wikipedia.org/wiki/Double-checked_locking

see why double-checked locking does not work, and what is the solution
volatile

volatile in java

the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

Friday, January 27, 2012

multi-threading


Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

the sleep period can be terminated by interrupts,

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness,

Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.


read this page carefully if there is no time to read everything

Locks In Synchronized Methods

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

public void addName(String name) {     synchronized(this) {         lastName = name;         nameCount++;     }     nameList.add(name); }


But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization.

Using volatile variables reduces the risk of memory consistency errors, because any write to avolatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
1. java 1.5 multithread concept
2. compare 1.4 vs 1.5
3. produce consumer
4. double checked locking
5.write lazy load, multithread safe, a singlton class
6. implement multiple threading pool (queue data structure, plus produce consumer)

Monday, January 23, 2012

difference between process and thread

http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread

Process
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

Thread
A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.



--

A process is a collection of code, memory, data and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.

--

The major difference between threads and processes is:

  1. Threads share the address space of the process that created it; processes have their own address space.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. Threads have almost no overhead; processes have considerable overhead.
  5. New threads are easily created; new processes require duplication of the parent process.
  6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

Thursday, January 5, 2012

Safe Lock examples

http://docs.oracle.com/javase/tutorial/essential/concurrency/examples/Safelock.java

Java Multithreading examples

http://www.tutorialspoint.com/java/java_multithreading.htm

I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.


Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).


  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  • Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.