In the Ignite distributed cache, there is a common application scenario is distributed lock, the use of distributed locks we can achieve a simple cluster master election function.
Here is an example of using a distributed lock:
Package My.ignitestudy.datagrid;
Import Org.apache.ignite.Ignite;
Import Org.apache.ignite.IgniteCache;
Import org.apache.ignite.Ignition;
Import Org.apache.ignite.cache.CacheAtomicityMode;
Import org.apache.ignite.configuration.CacheConfiguration;
Import org.apache.ignite.configuration.IgniteConfiguration;
Import Org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
Import Org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
Import Java.util.Arrays;
Import Java.util.concurrent.locks.Lock;
public class Distributedlockexample {public static void main (string[] args) throws Exception {test ();
private static Ignite Getignite () {Tcpdiscoveryspi SPI = new Tcpdiscoveryspi ();
Tcpdiscoveryvmipfinder Ipfinder = new Tcpdiscoveryvmipfinder ();
Ipfinder.setaddresses (Arrays.aslist ("192.168.0.192:47500..47509"));
Spi.setipfinder (Ipfinder);
Igniteconfiguration ignitecfg = new Igniteconfiguration (); IgniteCFG.SETDISCOVERYSPI (SPI);
Ignitecfg.setclientmode (TRUE);
Ignite Ignite = Ignition.start (ignitecfg);
return ignite;
private static void Test () throws Exception {cacheconfiguration cachecfg = new Cacheconfiguration ();
Cachecfg.setname ("Default");
Cachecfg.setbackups (1);
ignitecache<string, string> cache = Getignite (). Getorcreatecache (CACHECFG);
String Mylock = "Mylock"; New Thread (New Runnable () {@Override public void run () {System.out.println ("thre
Ad 1:before lock ");
Lock lock = Cache.lock (Mylock);
Lock.lock ();
System.out.println ("Thread 1:after lock");
try {cache.put (Mylock, "Thread 1");
Thread.CurrentThread (). Sleep (10 * 1000);
catch (Exception ex) {ex.printstacktrace ();
finally { System.out.println ("Thread 1:before unlock");
Lock.unlock ();
System.out.println ("Thread 1:after unlock");
}}). Start ();
Thread.CurrentThread (). Sleep (2 * 1000); New Thread (New Runnable () {@Override public void run () {System.out.println ("thre
Ad 2:before lock ");
Lock lock = Cache.lock (Mylock);
Lock.lock ();
System.out.println ("Thread 2:after lock");
try {cache.put (Mylock, "Thread 2");
catch (Exception ex) {ex.printstacktrace ();
finally {System.out.println ("Thread 2:before unlock");
Lock.unlock ();
System.out.println ("Thread 2:after unlock");
}}). Start (); }
}
The example uses two threads to simulate a preemption lock scene. In order to test the convenience, the first line enters upgradeable starts, after obtains the lock to sleep for a while, waits for the second thread to start. The second thread tries to acquire the lock after it starts, and the second thread waits because the first thread has acquired the lock. The first thread, after sleep for a while, releases the lock, and the second thread immediately acquires the lock and executes its own logic.