Coder Social home page Coder Social logo

xsync's Introduction

build status codecov Maven Central

XSync Library

What is it

XSync is a thread-safe mutex factory, that provide ability to synchronize by the value of the object(not by the object).

And you can use it for all type of objects which you need.

XSync mutex behavior

You can read more about this library here: Synchronized by the value of the object

Add dependencies

You need to add the next dependencies:

<dependency>
    <groupId>com.antkorwin</groupId>
    <artifactId>xsync</artifactId>
    <version>1.3</version>
</dependency>

Create the XSync instance

You can create XSync instances parametrized by the type of key which you need. For example we create two XSync instances for Integer and String keys and made it as Spring beans:

@Configuration
public class XSyncConfig {
   
    @Bean
    public XSync<Integer> intXSync(){
        return new XSync<>();
    }
    
    @Bean
    public XSync<String> xSync(){
        return new XSync<>();
    }
}

Use it

Simple example

@Autowired
private XSync<String> xSync;

@Test
public void testLock() throws InterruptedException {
    // Arrange
    NonAtomicInt variable = new NonAtomicInt(0);
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    // Act
    executorService.submit(() -> {
        System.out.println("firstThread started.");
        xSync.execute(new String("key"), () -> {
            System.out.println("firstThread took a lock");
            sleep(2);
            variable.increment();
            System.out.println("firstThread released a look");
        });
    });

    executorService.submit(() -> {
        sleep(1);
        System.out.println("secondThread started.");
        xSync.execute(new String("key"), () -> {
            System.out.println("secondThread took a lock");

            // Assert
            Assertions.assertThat(variable.getValue()).isEqualTo(1);
            sleep(1);
            variable.increment();
            System.out.println("secondThread released a look");
        });
    });

    executorService.awaitTermination(5, TimeUnit.SECONDS);

    // Assert
    Assertions.assertThat(variable.getValue()).isEqualTo(2);
} 

Result of this test:

result

Example of usage in a banking system

You can read more details about this example in my article: Synchronized by the value of the object

A business logic, that we need to synchronize:

public class PaymentService {

    ...

    @Autowired
    private XSync<UUID> xSync;

    public void withdrawMoney(UUID userId, int amountOfMoney) {
        xSync.execute(userId, () -> {  
            Result result = externalCashBackService.evaluateCashBack(userId, amountOfMoney); 
            accountService.transfer(userId, amountOfMoney + result.getCashBackAmount()); 
            externalCashBackService.cashBackComplete(userId, result.getCashBackAmount()); 
        });
    }
}

And places of usages:

public void threadA() {
    paymentService.withdrawMoney(UUID.fromString("11111111-2222-3333-4444-555555555555"), 1000);
}


public void threadB() {
    paymentService.withdrawMoney(UUID.fromString("11111111-2222-3333-4444-555555555555"), 5000);
}

Examples on github

You can find a project with examples here: github.com/antkorwin/xsync-example

License

XSync is Open Source Software released under the Apache 2.0 license.

xsync's People

Contributors

antkorwin avatar l0s avatar ravenvss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

xsync's Issues

Support building with JDK 10 and 11

As mentioned in #10, the build fails with JDK 10 and higher. Travis CI supports JDK 10 and 11 so at minimum, those versions should be supported.

JDK 10, 12, 14 issue:

[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ xsync ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 5 source files to /Users/cmacasaet/var/git/xsync/target/test-classes
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by lombok.javac.apt.LombokProcessor to field com.sun.tools.javac.processing.JavacProcessingEnvironment.discoveredProcs
WARNING: Please consider reporting this to the maintainers of lombok.javac.apt.LombokProcessor
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  5.028 s
[INFO] Finished at: 2020-10-03T18:57:34-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile (default-testCompile) on project xsync: Fatal error compiling: java.lang.ExceptionInInitializerError: com.sun.tools.javac.code.TypeTags -> [Help 1]

Support StampedLock

Introduce a StampedLockFactory similar to XMutexFactory, except instead of generating a synchronization monitor, it would generate a StampedLock instance. This would be useful for applications that could benefit from the performance characteristics of StampedLock: https://blog.overops.com/java-8-stampedlocks-vs-readwritelocks-and-synchronized/ . It would also be useful for applications that need read-locking vs. write-locking semantics, i.e. allowing multiple concurrent readers provided there are no writers.

Optional: Also introduce a ReadWriteLockFactory which would be useful for applications that prefer the simpler ReadWriteLock interface, require re-entrant capabilities, or need to define whether or not the lock is fair.

improve documentation

it would be good to show how to use multi-key synchronization in your code with XSync.

Remove hibernate package

This library currently uses a class from Hibernate and my guess is that in order to keep the size of the lib small this class has been copied from hibernate into an org.hibernate.validator.internal.util package.
The problem is that using this package name in this library means it can not be used in a modular way with other libraries that depend on hibernate due to a package name conflict.

This library should either depend on hibernate or place this class somewhere within its own namespace (com.antkorwin.xsync).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.