Java Curator implements distributed locks

Curator's implementation of distributed locks mainly relies on zookeeper

// Curator implements distributed lock
			CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
														.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
// must be started first otherwise invalid
			client.start();
			final InterProcessMutex lock = new InterProcessMutex(client, "/zk-xxx/childs");
			
			for(int i=0;i<10;i++){
				new Thread(){
					@Override
					public void run() {
						try {
							lock.acquire();
							System.out.println(code.getCode());
							lock.release();
						} catch (Exception e) {
							e.printStackTrace ();
						}
					}
				}.start();
			}


class GenerateCode{
	public String getCode(){
		SimpleDateFormat fomat = new SimpleDateFormat("HH:mm:ss|SSS");
		System.out.println("Your thread number: "+Thread.currentThread().getName());
		return fomat.format(new Date());
	}
}


<dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>2.7.0</version>
    </dependency>


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326880400&siteId=291194637