Java.Threads.Synchronized

sync methods

package org.example;

import java.util.concurrent.Executors;

public class Counter {

    private static int count = 0;

    public static synchronized int getCount() {
        return count;
    }

    public static synchronized void increase(int sleepTimeMiliseconds) {
        count++;
        try {
            Thread.sleep(sleepTimeMiliseconds);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static synchronized void decrease(int sleepTimeMiliseconds) {
        count--;
        try {
            Thread.sleep(sleepTimeMiliseconds);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public static void execute() {
        var executorService = Executors.newFixedThreadPool(2);

        executorService.execute(() -> {
            while (true) {
                increase(1000);
                System.out.printf("count is: %s%n", count);
            }
        });

        executorService.execute(() -> {
            while (true) {
                int count = getCount();
                decrease(2000);
                System.out.printf("count is: %s%n", count);
            }
        });
    }
}

sync static class

public class OurPresident {
    private static OurPresident president;

    static {
        synchronized (OurPresident.class) {
            president = new OurPresident();
        }
    }

    private OurPresident() {
    }

    public static OurPresident getOurPresident() {
        return president;
    }
}
Posted in Без рубрики | Comments Off on Java.Threads.Synchronized

Java. DeepCloneExample

import java.util.LinkedHashMap;
import java.util.Map;

/* 
Deep clone example
*/

public class Solution implements Cloneable {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.users.put("Hubert", new User(172, "Hubert"));
        solution.users.put("Zapp", new User(41, "Zapp"));
        try {
            Solution clone = (Solution) solution.clone();
            System.out.println(solution);
            System.out.println(clone);

            System.out.println(solution.users);
            System.out.println(clone.users);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace(System.err);
        }
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        Solution o = (Solution) super.clone();

        //clone users
        Map<String, User> newUsers = new LinkedHashMap<>();
        for (String key : o.users.keySet()) {
            User user = o.users.get(key);
            newUsers.put(key, (User) user.clone());
        }
        o.users = newUsers;

        return o;
    }

    protected Map<String, User> users = new LinkedHashMap<>();

    public static class User implements Cloneable {
        int age;
        String name;

        public User(int age, String name) {
            this.age = age;
            this.name = name;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            User user = (User) o;

            if (age != user.age) {
                return false;
            }
            return name != null ? name.equals(user.name) : user.name == null;
        }

        @Override
        public int hashCode() {
            int result = age;
            result = 31 * result + (name != null ? name.hashCode() : 0);
            return result;
        }
    }
}
Posted in Без рубрики | Comments Off on Java. DeepCloneExample

Abstract Classes vs Interfaces

https://javarush.com/groups/posts/431

Posted in Без рубрики | Comments Off on Abstract Classes vs Interfaces

SQL. NULL and logical operators

Posted in Без рубрики | Comments Off on SQL. NULL and logical operators

Java. Simple Gradle Application

By default there is no application plugin, so lets set it

plugins {
    id("application")
}

application {
    mainClass.set("org.example.Main");
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.9.1"))
    testImplementation("org.junit.jupiter:junit-jupiter")
}

tasks.test {
    useJUnitPlatform()
}

Posted in Без рубрики | Comments Off on Java. Simple Gradle Application

Leetcode.Solved.Missing-number

// https://leetcode.com/problems/missing-number
public class Solution {
    public int MissingNumber(int[] nums) {
                    
    int[] arr = new int[nums.Length + 1];

    for (int i = 0; i < nums.Length; i++) {
       arr[nums[i]] = 1; 
    }
    
    for(int i=0; i< arr.Length; i++)
    {
      if(arr[i] == 0)        
        return i;
        
    }
    
      return 0;    
  }
}
// this decision doesn't work well because of unclear conditions
// https://leetcode.com/problems/missing-number
public class Solution {
    

    public int MissingNumber(int[] nums) {
        
		// to add many cases here, not submitting        
		 
        int min = nums[0];
        int max = nums[0];
        var set = new HashSet<int>();
        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] < min) {
                min = nums[i];
            }

            if (nums[i] > max) {
                max = nums[i];
            }                        

            set.Add(nums[i]);
        }
         
        for (int num = min; num <= max; num++) {
          if (!set.Contains(num))
            return num;
        }

        return ++max; // not clear from conditions of the task        
    }
}
Posted in Без рубрики | Comments Off on Leetcode.Solved.Missing-number

Leetcode.Solved.Intersection-of-two-arrays

// https://leetcode.com/problems/intersection-of-two-arrays
public class Solution {
    public int[] Intersection(int[] nums1, int[] nums2) {

       var set = new HashSet<int>();
       for (int i = 0; i < nums1.Length; i++) {
         set.Add(nums1[i]); 
       }

       var resSet = new HashSet<int>();
       for (int i = 0; i < nums2.Length; i++) {
         if (set.Contains(nums2[i]))
         resSet.Add(nums2[i]);
       }

      return resSet.ToArray();                
    }
}
Posted in Без рубрики | Comments Off on Leetcode.Solved.Intersection-of-two-arrays

DesignPatterns.AbstractFactory

MyCodeExample

Posted in Без рубрики | Comments Off on DesignPatterns.AbstractFactory

DesignPatterns.Factory

MyCodeExample

Posted in Без рубрики | Comments Off on DesignPatterns.Factory

Leetcode.Solved.ContainsDublicate

// https://leetcode.com/problems/contains-duplicate
public class Solution {
    public bool ContainsDuplicate(int[] nums) {        
        Array.Sort(nums);

        for (int i = 0; i < nums.Length - 1; i++) {
            if (nums[i] == nums[i+1])
              return true;
        }  
             
        return false;
    }
}
// https://leetcode.com/problems/contains-duplicate
public class Solution {
    public bool ContainsDuplicate(int[] nums) {
        
        HashSet<int> set = new HashSet<int>();

        for (int i = 0; i < nums.Length; i++) {
            if (set.Contains(nums[i]))
              return true;
              
            set.Add(nums[i]);
        }  
             
        return false;
    }
}
Posted in Без рубрики | Comments Off on Leetcode.Solved.ContainsDublicate