About thread safety class

  If you use this class multi-threaded, multi-threaded, but how to use and schedule the class, which always shows the correct behavior, this class is thread-safe; do not do proper synchronization, shared state between multiple threads time, there will be thread safe;

 

  

  Thread-safe performance class as follows:

  • Atomic operation

  • Visibility memory

 

  • Stack closed

    All variables are declared inside the method, these variables are in the stack closed state;

 

  • no status

    No member variables of the class

 

  • Let immutable class

    1. Add keywords, all member variables should be private, the same as long as possible, all member variables should add keywords, but with , pay attention if the member variable is an object, the object corresponding to the class should not be changed, in order to ensure that the entire class is immutable;finalfinalfinal

public class FinalRef {
	
	private final int a;
	private final int b;
	private final User user; // here it can not guarantee thread safety
	
	public FinalRef(int a, int b) {
		this.a = a;
		this.b = b;
		this.user = new User();
	}

	public int getA() {
		return a;
	}

	public int getB() {
		return b;
	}
	
	public User getUser() {
		return user;
	}

	public static class User{
		private int age;

		public User(int age) {
			super();
			this.age = age;
		}

		public int getAge() {
			return age;
		}

		public void setAge(int age) {
			this.age = age;
		}
		
	}
	
	public static void main(String[] args) {
		FinalRef ref = new FinalRef (12,23);
		User u = ref.getUser();
        // Here the user can modify the value
		//u.setAge(35);
	}
}

  

  2. does not provide any places to modify member variables, member variables at the same time as the method does not return value;

 

  • volatile

    volatileIt can be used in a multi-threaded environment, guaranteed class visibility , i.e. a modified thread, another thread can be read, but does not guarantee atomicity;volatile

 

   Java memory model specifies that all variables are stored in the main memory; each thread also has its own working memory, working memory thread stored in the main memory copy of the copy is to use the thread variable (if a local variable is reference type, shared objects it references are various threads in the Java heap available, but the table itself refers to a local variable stack in Java, it is a private thread) , thread all operations on variables (reading, assignments, etc.) It must be carried out in the working memory, but can not read and write directly to main memory variables; between different threads can not access the working memory variables directly, the variable value passed between threads are required to complete the main memory;

   Exchange relationship thread, main memory, working memory of the three

     

 

 

  From the variable, main memory, we define the term working memory, main memory, the main object instance corresponding to the data part of the Java heap, while the portion corresponding to the working memory area of ​​the virtual machine stack; lower level from said main memory directly correspond to the physical hardware, memory, and in order to get better speed, virtual machine (even optimizations hardware system itself) may give priority to working memory and cache memory and registers, as the main access to the program is running reading and writing is the working memory;

 

  The following code: Running result is a cycle of death

public class RunThread extends Thread {
    private boolean isRunning = true;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 进入run");
        while (isRunning) {
        }
        System.out.println (. Thread.currentThread () getName () + "thread to stop");
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread thread = new RunThread();
        thread.start();
        Thread.sleep(1000);
        thread.setRunning(false);
        System.out.println (Thread.currentThread () getName () + "has been assigned false".);
    }
}

  

  IsRunning stack variables exist in public and private to the thread stack (where the common stack refers to the main memory, threads private stack refers to a thread of working memory), the program has been operating in the private value of acquired isRunning thread's stack true, although execution thread.setRunning (false) in the main thread, the update is isRunning variable common stack, the modification to the threads is no perceptual variables, two memory operation is data address, as shown below:

 

    

 

  The variables above code isRunning with modifications, the results are normal exit procedures;volatile

 

  On the volatile and reordering, see

 

  JVM defined Happens-Before principle is a group of partial order, in the JMM, if a result of executing the operation requires another operation to be seen, these two operations must be present happens-before relation, two mentioned here operative relationship may be in a thread, the thread may be different in direct, i.e., for the two operations a and B, these two operations may be performed in different threads; if a Happens-Before B, it can be guaranteed, a operates when executed, perform operations on the result of the a operation B is visible;

 

  If the sleep commented above, the end result of the program may be normal, thread.setRunning (false) operation execution is completed, another thread isRunning be read as a value of false;

 

  When a variable is later modified, it will have two features, the first is to ensure that this variable visibility to all threads, the visibility here is when a thread changes the value of this variable, the new value is visible to another thread can be immediately learned;volatile and common variables can not do this, the value of the common variable transmission are required to complete the main memory between threads, such as thread a modification of the value of a common variable, and then written back to main memory, in addition a write-back thread B thread a after the completion of the read operation from the main memory, working memory B to read the thread, a new variable will be visible to thread B;

 

  Use keyword, the variables can be forced to read from the main memory (common memory) value, bypassing the working memory of the threadvolatile , as shown below:

    

 

  • CAS and lock

    Class using an atomic operation, synchronized, Lock Lock

     

  • ThreadLocal

   Use thread-local variables

 

  

  Servlet is not thread-safe class. For shared resources, there will be thread safe; Servlet life cycle is to receive a request to create a Servlet, returns a response, the destruction of Servlet, are responsible by a thread;

 

  • Deadlock

  Deadlock refers to two or more than two threads in the implementation process, due to the competition for resources or communicate with each other and because the A blocking phenomenon caused , in the absence of external force, they will not be able to promote it. At this time, say the system is in deadlock state or system to produce a deadlock , which is always in the process of waiting for each other is called a deadlock ;

  When more than one resource, but less than the number of threads equal competition; order to obtain the lock inconsistency will lead to deadlock; when only one resource, will produce competitive; Solution: jstack View holdings application locks; assure an orderly locked ;

  Dynamic sequence deadlock in achieving a lock in a certain order, but because of problems external calls, resulting in no guarantee that locking sequence generated; resolve: sort through the inherent, assure an orderly locked; can also try take the lock;

 

  • Livelock

  Livelock refers to the task or performer is not blocked , because some conditions are not met, resulting in repeated attempts - failed - attempt - failure of the process; entity is active lock is in constant state of change, it is possible to live on their own locks unlock; following examples:

/**
 * Class Description: no secure method of transferring the deadlock, trying to get a lock
 */
public class SafeOperate implements ITransfer {

    @Override
    public void transfer(UserAccount from, UserAccount to, int amount)
            throws InterruptedException {
    	Random r = new Random();
    	while(true) {
    		if(from.getLock().tryLock()) {
    			try {
    				System.out.println(Thread.currentThread().getName()
    						+" get "+from.getName());
    				if(to.getLock().tryLock()) {
    					try {
    	    				System.out.println(Thread.currentThread().getName()
    	    						+" get "+to.getName());    						
    						// two locks have got
    	                    from.flyMoney(amount);
    	                    to.addMoney(amount);
    	                    break;
    					}finally {
    						to.getLock().unlock();
    					}
    				}
    			}finally {
    				from.getLock().unlock();
    			}
    		}
            // staggered thread lock to take the time
    		//Thread.sleep(r.nextInt(10));
    	}
    }
}

  

  The above thread sleep for staggered thread lock to take the time to look dormant time-consuming, but the efficiency will be improved, to reduce repeated attempts to appear - the number of failures;

 

 

 

Guess you like

Origin www.cnblogs.com/coder-zyc/p/12650557.html